Categories
Computing

Lox on Raspberry Pi Microcontrollers

I’ve recently read and enjoyed Robert Nystrom’s ‘Crafting Interpreters‘. I’ve also been exploring Raspberry Pi microcontrollers. I’ve used them both in this GitHub repo, which combines the C bytecode implementation of the Lox language from the book with the C SDK for the Pico.

It runs well, even on these constrained (133Mhz, 264K RAM) devices. The repl seems responsive, and the code all fits. I had to make two changes:

  • I reduced STACK_MAX, as the default produced an image that would not load in the 264k RAM on the Pico. The default ran fine on the newer Pico 2, which has 520K RAM.
  • I reworked main() to provide just the REPL directly. By default the Pico SDK does not provide a filesystem, so there’s no way to load and run scripts ‘from the command line’.

I am curious to explore this further. Clearly the amounts of RAM consumed could be refined, and it might be interesting to add a filesystem. The Micropython port does this, and provides a very productive development experience.

The repo contains some cmake configuration files, mostly because the Pico SDK defaults to using cmake. This provides a build that works on my machine, and can hopefully be compiled for a host PC (a Mac OS machine in my case), or two of the Pico boards: Pico and Pico 2.

In the specimen directory are a few lox scripts I used while reading the book, and a file of one-line scripts that I find easy to enter via cut & paste to the repl.

Pico 2 was interesting to build for, as it contains both ARM and Risc-V cores. The idea seems to be that you choose at boot time which instruction set you use. I’ve built the code for both ARM and Risc-V. I’m curious what that means in practice – in this repo, I can see no particularly obvious differences. The details of ARM vs Risc-V are all managed by simply selecting a different toolchain for the C code.