Micropython on ESP32

I guess I cannot avoid using Python. As much fun as Node.js is and as much as I like the ability to do work in the background, a lot of my simpler scripts use async/await which reduces the program to simply do its work one line at a time. And in order.

Python on normal Linux machines is way too boring. Running it on an ESP32 is far better: I got plenty examples using Espruino (JavaScript), so I can use those to re-program them in MicroPython. Should be easy, right?

Step 1: Install MicroPython

./esptool.py --chip esp32 --port /dev/ttyUSB0 erase_flash
./esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 460800 write_flash -z 0x1000 esp32-20190125-v1.10.bin

You should now be able to connect to /dev/ttyUSB0 (115200 bit/s) and get the Micropython REPL. Get the ESP32 binary from here. esptool from here.

Step 2: Install ampy

ampy is used to upload and run Python programs on your microcontroller.

pip install adafruit-ampy --user

Now you can do things like showing the internal flash filesystem:

ampy --port /dev/ttyUSB0 ls
export AMPY_PORT=/dev/ttyUSB0
ampy ls
ampy get /boot.py

Step 3: Run a simple program

def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('sauerkraut2', 'AntonAnton')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())

do_connect()

Save this as a file (e.g. wlan.py). Replace WLAN SSID and PASSWORD of course:

$ ampy run wlan.py
network config: ('192.168.22.219', '255.255.255.0', '192.168.22.1', '192.168.22.1')

So the ESP32 connected to the WLAN and got an IP 192.168.22.219!

Step 4: Use the OLED

Obviously at this point you want to see the microntroller do something you cannot do by your main Linux (or Windows) machines. E.g. link a LED. Or write something on the OLED. I happen to have an128x64 OLED with a SSD1306 controller, so I'll use that. Here the program taken from here from Lauri Võsandi (call it esp32-oled-demo.py):

from time import sleep_ms
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C

buf = "wubba lubba dub dub  "

i2c = I2C(-1, Pin(4),Pin(5),freq=40000) # Bitbanged I2C bus
assert 60 in i2c.scan(), "No OLED display detected!"

oled = SSD1306_I2C(128, 64, i2c)
oled.invert(0) # White text on black background
oled.contrast(255) # Maximum contrast

for j in range(0, 500):
    oled.fill(0)
    oled.text(buf[j%len(buf):]+buf, 10, 10)
    oled.show()
sleep_ms(40)

However it needs the ssd1306 module, which you can get like this:

wget https://raw.githubusercontent.com/adafruit/micropython-adafruit-ssd1306/master/ssd1306.py

and then you upload it to the microcontroller:

ampy put ssd1306.py

Now you can run your program from above:

ampy run esp32-oled-demo.py