Lessons and the learning game

Pi hardware in Python: I2C, SPI and PWM

Drive a Raspberry Pi's hardware from Python: gpiozero, smbus2 sensors, an SPI ADC, a gauge needle, your own OLED driver, and a weather terminal.

The bench

Every lesson opens one weather bench on a Raspberry Pi 4:

  • a BME280 sensor and an SSD1306 OLED on I2C bus 1 (SDA GPIO 2, SCL GPIO 3)
  • an MCP3008 ADC on SPI0 (CE0) with a knob on channel 0
  • a servo on GPIO 18, set to 1.0 to 2.0 ms pulses, used as a gauge needle
  • a green LED through 330 ohms on GPIO 17 and a button on GPIO 27

Take the course at /learn/path/pi-hardware-python on /learn.

The lessons

  1. gpiozero beyond basics. PWMLED values, blink a set number of times, pulse in the background, and devices wired together with source.
  2. smbus2 sensors. A bus scan, one register and a block of registers from a BME280, a driver on top, and Errno 121 when nobody answers.
  3. spidev ADC. The MCP3008's three bytes sent by hand with xfer2, the 10-bit answer decoded, then gpiozero's MCP3008.
  4. PWM servos: a gauge needle. A 50 Hz pulse from 1 to 2 ms as a 5 to 10 percent duty cycle with RPi.GPIO, and air pressure mapped to the dial.
  5. An OLED driver in Python. oled.py, written from the datasheet: setup commands, a 1024-byte framebuffer, pixel() with bit arithmetic, and show() in 16-byte I2C writes.
  6. Callbacks. when_pressed, when_released and when_held with a free main loop.
  7. Boss: a Pi weather terminal. Pages on a knob, the needle, a damp-air light, and a button that logs readings to a CSV file.

How it runs

The Pi runs the lesson's main.py on Mokxi's Python engine, with gpiozero, RPi.GPIO, smbus2 and spidev driving the buses on the header, clocked out to the parts at the kernel's default speeds. See Python on a Raspberry Pi.

Honest limits

  • The engine is MicroPython, not CPython: a dict does not keep the order its keys went in, and a few str methods are missing. The lessons use nothing that would not run on a real Pi.
  • There is no Linux underneath: no shell, no pip, no i2cdetect command (the bus scan does the same in Python).
  • PWM has none of the jitter a busy Linux system gives software PWM; the servo lesson says when to use a hardware PWM board.