Lessons and the learning game

Build a graphing calculator

A graphing calculator from an Uno, a calculator keypad and a 2.4 inch TFT, with a real expression parser inside.

The finished calculator

Build a graphing calculator runs every lesson on the same wiring:

  • The brain: an Arduino Uno.
  • The keys: a 20-key calculator keypad on nine pins, rows on 12, 10, 8, 7 and 6 and columns on 5, 4, 3 and 2.
  • The screen: an ILI9341, 320 by 240 in landscape, on DC 9, SCK 13 and MOSI 11. Its chip select is tied to ground: it is the only thing on its bus, and that frees the pin the keypad needs.

The serial monitor is a second keyboard for anything long, and the sketches read it exactly like the keypad.

How it works

The keypad is a matrix with no chip in it: drive one row low, read the four columns with their pull-ups, then the next row. A reading counts once it has held for 15 ms. % is a 2nd key, so twenty keys type brackets, powers, sin, cos, sqrt, x, pi and ans as well. Three keys held in a rectangle make a ghost in the fourth corner, which the scan can notice but not undo.

The parser cuts a line into tokens, then puts them in reverse Polish notation with Dijkstra's shunting-yard algorithm: + and - bind loosest, then

  • and /, then unary minus, then ^, which groups from the right. A stack works the RPN out. 2x and 3(x+1) get the multiplication nobody wrote, and bad input gets an error that says what was wrong.

Variables are 26 floats and ans, each with a bit for whether it has a value. Answers show six significant digits, and NaN and infinity show as undefined and infinity.

Plotting compiles the expression once and runs it 320 times, once per column, joining each point to the last. Infinite values and leaps across the whole window are left as gaps: asymptotes are not part of the curve.

Zoom, trace and roots: with a graph on screen, 4 and 6 move a cursor a unit at a time, + and - zoom, 8 and 2 pan, and = finds the nearest root by bisection. Typing table prints seven values around the cursor.

The course

  1. Keypad input: a matrix scanned by hand, the 2nd key, and a ghost.
  2. An expression parser: tokens, shunting yard, RPN, precedence, unary minus and errors.
  3. Variables: a to z, ans, pi, functions, and honest special values.
  4. Plotting: a window, compiling once, asymptotes and domains.
  5. Zoom and trace: a cursor, bisection, zoom and pan.
  6. Project: a pocket grapher: all three roots of a cubic, a table of values, and a curve of your own to share.

Every checked step is tested against the running circuit.