继前一贴OLED显示电位器电压与实时进度条,可以继续使用SSD1306 OLED屏幕模块搭配一些传感器组合使用,例如DHT11温湿度传感器模块,可以显示其传回的温度,湿度,并显示各自的进度条。
DHT11是一种非常基础和低成本的数字温湿度传感器。它用电容式湿度传感器和热敏电阻来测量周围空气的湿度和温度,并转换为对应数字量,在数据引脚发送数字信号给微控制器,通过其指定的单线通信协议即可在微控制器端接收到温湿度数据。
接线参考
DHT11 | Board |
---|---|
GND | GND |
DAT | GPIO1 |
VCC | 5V |
SSD1306 OLED | Board |
---|---|
GND | GND |
VCC | 5V |
SCL | 16 |
SDA | 15 |
MicroPython
Micropython 运行环境搭建 - Banana Pi Wiki (banana-pi.org)
from machine import Pin,I2C
from ssd1306 import SSD1306_I2C
import time
import dht
dht11 = dht.DHT11(Pin(1))
sda_pin=Pin(15,Pin.PULL_UP)
scl_pin=Pin(16,Pin.PULL_UP)
i2c = I2C(1,sda=sda_pin, scl=scl_pin, freq=800_000)
print(i2c.scan())
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)
#Init, white background
oled.fill(1)
oled.rect(0,22,128,10,0)
oled.rect(0,53,128,10,0)
while True:
#Read DHT11
dht11.measure() # Measure and read data once.
temperature = dht11.temperature() # -20℃ ~ 60℃
humidity = dht11.humidity() # 5%RH ~ 95%RH
#Set temperature text, centered
text_1 = str(temperature) + " C"
start_x_1 = 64 - len(text_1)*4
oled.fill_rect(0,14,128,8,1)
oled.text(text_1,start_x_1,14,0)
#Set temperature bar
bar_1 = round ((temperature+20)/80 * 128)
oled.fill_rect(bar_1,23,128-bar_1,8,0)
oled.fill_rect(0,23,bar_1,8,1)
#Set humidity text, centered
text_2 = str(humidity) + " %RH"
start_x_2 = 64 - len(text_2)*4
oled.fill_rect(0,45,128,8,1)
oled.text(text_2,start_x_2,45,0)
#Set humidity bar
humidity_bar = round (humidity/100 * 128)
oled.fill_rect(humidity_bar,54,128-humidity_bar,8,0)
oled.fill_rect(0,54,humidity_bar,8,1)
#Show
oled.show()
print("Temperature={0}℃,Humidity={1}%RH".format(temperature,humidity))
time.sleep(2.5)