Lessons and the learning game

Build a programming language

Write Orbit, a small language for a mission control panel, in Python on a Raspberry Pi, and end with a REPL whose red on lights a real lamp.

The course

Build a programming language is an advanced Coding course in eight lessons. Every lesson runs on the same circuit: a Raspberry Pi 4 with a traffic light module (red on GPIO17, amber on GPIO27, green on GPIO22), which is Orbit's panel. Each step is checked against what the Pi prints or which lamp it lights.

  1. Tokens: a tokenizer that cuts text into numbers, names, strings and symbols, with comments, whitespace and an END token.
  2. Recursive descent: one method per grammar rule. Precedence, left associativity, brackets, unary minus and % fall out of which method calls which.
  3. An AST: the parser builds a tree of tuples, and small recursive functions draw it, evaluate it and print it in reverse Polish notation.
  4. Evaluating: statements. print, lamps that switch real GPIO pins, wait, and a launch sequence written in Orbit.
  5. Scope: let, assignment and repeat blocks, then environments chained to their parents, so a block's names stay in the block.
  6. Functions: def, calls, return as an exception, lexical against dynamic scope shown on one program, if and recursion up to fib(15).
  7. Errors: tokens that know their line and column, one OrbitError, a caret under the mistake, and division by zero and type errors caught before Python sees them.
  8. Boss: a calculator language on a board: Orbit 1.0.

The finale

The boss lesson turns the interpreter into a read-eval-print loop on the Serial Monitor. It keeps one global environment for the session, reads a block over several lines while its braces are open (with a ...> prompt), survives errors and Ctrl-C, and has sqrt, round and abs built in. The last step types a whole mission live:

let t = 3
def launch() {
  red on
  repeat t {
    print "T minus", t
    amber on wait 0.5 amber off wait 0.5
    t = t - 1
  }
  red off
  green on
  print "LIFTOFF at", round(sqrt(398600 / 6771), 2), "km/s"
}
launch()

The panel counts down and goes green, and Orbit works out the space station's orbital speed, 7.67 km/s.

What the Pi's engine does differently

The Pi runs MicroPython 1.29, not CPython. For this course that shows in a few places:

  • str has isalpha and isdigit but no isalnum, so the tokenizer asks for both.
  • input() reads a line typed in the Serial Monitor, and Ctrl-C there raises KeyboardInterrupt in the program, which the REPL catches.
  • time.sleep runs on the simulated clock, so wait 0.5 is exactly half a simulated second.
  • When main.py ends, the Pi lets go of its pins and the lamps go dark, so the non-REPL lessons wait five seconds at the end.

Everything else, from exceptions as control flow to closures, is plain Python that runs the same on a real Pi.