Display#

Let’s add a diplay to our scale. The SSD1306 can be configured over I2C or SPI. We will use the I2C interface.

The first step is getting a driver. Fortunately someone has already written it (Driver & Tutorial). For convenience it’s also included here:

%connect balance
Connected to balance @ serial:///dev/ttyUSB1
!head code/lib/ssd1306.py
# MicroPython SSD1306 OLED driver, I2C and SPI interfaces

from micropython import const
import time
import framebuf

# register definitions
SET_CONTRAST        = const(0x81)
SET_ENTIRE_ON       = const(0xa4)
SET_NORM_INV        = const(0xa6)

To try out the display, we need to copy it to the microcontroller. Modify the device configuration as shown below (change the UID to match your device):

!cat ../devices/balance.yaml
balance:
    uid: 24:0a:c4:12:87:7c
    path: balance
    resources:
        - code

%rsync uploads the files in the code directory to the microcontroller:

%rsync

Verify:

%rlist
                            lib/
   2713  Jul 09 18:28 2021      ble_advertising.py
   3475  Jul 09 18:28 2021      ble_uart_peripheral.py
    551  Jul 10 17:37 2021      button.py
    738  Jul 10 17:37 2021      scale.py
   4899  Jul 09 17:33 2021      ssd1306.py
    776  Jul 09 20:47 2021  main.py

Let’s check out the display:

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

i2c = machine.I2C(0, scl=Pin(22), sda=Pin(23))

oled_width = 128
oled_height = 32
oled = SSD1306_I2C(oled_width, oled_height, i2c)

for i in range(10):
    oled.fill(0)   # clear display
    oled.text(str(i**3), 0, 0)
    oled.text(str(i**5), 0, 12)
    oled.text(str(i**7), 0, 24)
    oled.show()
    time.sleep(0.5)

Connect it to the scale:

from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
from scale import Scale

i2c = I2C(0, scl=Pin(22), sda=Pin(23))

oled_width = 128
oled_height = 32
oled = SSD1306_I2C(oled_width, oled_height, i2c)

scale = Scale()
start = time.ticks_ms()

last_weight = 500
while time.ticks_diff(time.ticks_ms(), start) < 20000:
    weight = scale.measure()
    if abs(weight-last_weight) > 3:
        oled.fill(0)
        oled.text("{:8.0f} gram".format(weight), 0, 12)
        oled.show()
        last_weight = weight

Great! We have a scale with a display.

Let’s add some features.