|
| 1 | +""" |
| 2 | +I2C OLED display SH1106 + DHT12 sensor |
| 3 | +
|
| 4 | +MicroPython script for reading data from DHT12 I2C sensor |
| 5 | +and displaying on an OLED with the SH1106 controller. The |
| 6 | +script requires SH1106 and DHT12 modules, stored in ESP32 device. |
| 7 | +
|
| 8 | +Authors: |
| 9 | +- Robert Hammelrath, https://github.com/robert-hh/SH1106 |
| 10 | +- Martin Fitzpatrick, https://blog.martinfitzpatrick.com/oled-displays-i2c-micropython/ |
| 11 | +- Tomas Fryza |
| 12 | +
|
| 13 | +Creation date: 2023-10-27 |
| 14 | +Last modified: 2026-09-01 |
| 15 | +""" |
| 16 | + |
| 17 | +# MicroPython builtin modules |
| 18 | +from machine import I2C, Pin, I2C |
| 19 | +from time import sleep |
| 20 | + |
| 21 | +# External modules |
| 22 | +from dht12 import DHT12 |
| 23 | +from bme280 import BME280 |
| 24 | +from sh1106 import SH1106_I2C |
| 25 | + |
| 26 | +# Init DHT12 sensor |
| 27 | +i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=100_000) |
| 28 | +sensor = DHT12(i2c) # 1st variant |
| 29 | +# sensor = BME280(i2c) # 2nd variant |
| 30 | + |
| 31 | +# Init OLED display |
| 32 | +display = SH1106_I2C(i2c) |
| 33 | +display.text("Temp. [C]:", 0, 40) |
| 34 | +display.text("Humid.[%]:", 0, 52) |
| 35 | + |
| 36 | +led = Pin(2, Pin.OUT) |
| 37 | + |
| 38 | +print("Read temperature and humidity every 10 secs.") |
| 39 | +print() |
| 40 | +print("Press `Ctrl+C` to stop") |
| 41 | +print() |
| 42 | + |
| 43 | +try: |
| 44 | + while True: |
| 45 | + led.on() |
| 46 | + temp, humid = sensor.read_values() # 1st variant |
| 47 | + # temp, humid, P, A = sensor.read_values() # 2nd variant |
| 48 | + print(f"T={temp:.1f}°C, H={humid:.1f}%") |
| 49 | + |
| 50 | + display.fill_rect(85, 38, 120, 50, 0) |
| 51 | + display.text(f"{temp:.1f}", 85, 40) |
| 52 | + display.text(f"{humid:.1f}", 85, 52) |
| 53 | + display.show() |
| 54 | + led.off() |
| 55 | + |
| 56 | + sleep(10) |
| 57 | + |
| 58 | +except KeyboardInterrupt: |
| 59 | + print() |
| 60 | + print("Program stopped. Exiting...") |
| 61 | + |
| 62 | + # Optional cleanup code |
| 63 | + display.poweroff() |
| 64 | + led.off() |
0 commit comments