An opinionated MicroPython Setup

Setup MicroPython Environment (host computer only)

In preparation for an upcoming hackathon, we needed to set up a coding environment. Since this is something we'd most probably do again, we decided to document our take on this.

Set up a virtual environment...

python3 -m venv .

...activate the Python environment automagically (in future) with direnv:

echo source bin/activate > .envrc; direnv allow .

Store the port name of the board (OSX version only) in the .envrc file.

Warning: This requires exactly one microcontroller board connected to the computer.

echo export PORT_NAME=$(ls /dev/cu.usb*) >> .envrc && direnv allow .

Prepare the stage

Using the MicroPython stubs

pip install -U micropython-esp32-stub

Check micropython-esp32-stubs for more details.

Install MicroPython firmware (ESP32 WROOM)

Please check MicroPython ESP32 WROOM for more documentation.

echo export FIRMWARE=ESP32_GENERIC-20240602-v1.23.0.bin >> .envrc && direnv allow .

Tip: You might want to check for newer binaries for ESP32_GENERIC.

curl -O https://micropython.org/resources/firmware/${FIRMWARE?}

Install esptool to flash the firmware.

pip install esptool

Erase flash with...

esptool.py --port ${PORT_NAME?} erase_flash

afterwards, flash the firmware with:

esptool.py --chip esp32 --port $PORT_NAME write_flash -z 0x1000 ${FIRMWARE?}

Install dependencies

Add Adafruit Ampy (Filemanager)

You cannot use the REPL to upload files to the board. Instead, you need to use a file manager. Adafruit Ampy is a good choice.

pip install adafruit-ampy
echo export AMPY_PORT='$PORT_NAME' >> .envrc && direnv allow .

Tip: You can use ampy ls to list files on the board.

Note: This command requires MicroPython installed on the board.

Use the screen tool to connect to the board

screen $PORT_NAME 115200

You'll see the MicroPython REPL:

>>> 1+1
2
>>>

Tip: Exit screen with Ctrl-a k y.

Please note the soft reset command is Ctrl-D.

To (hard) reset the controller from within the REPL, use machine.reset()... ...or press the reset button on the board.

Tips for the REPL

To post multiline statements, use Ctrl-E to enter paste mode. Exit paste mode with Ctrl-D (this includes execution).

You can print files (e.g. boot.py) with:

print(open('/boot.py').read())

Freeze the dependencies

You can freeze your local development dependencies with:

pip freeze > requirements.txt

Happy coding!


🙌 Photo by David Clode on Unsplash