# this program is used to read value humidity and temperature
# sensor i.e., DHT22 and DS18B20 then display them to OLED
# import library for GPIO, I2C, and Timer
from machine import Pin, I2C, Timer
from time import sleep
import dht, ds18x20, onewire
import ssd1306
# init timer
timer = Timer(0)
# init dht sensor
dht_sensor = dht.DHT22(Pin(26))
# init ds18x20 sensor
ds_sensor = ds18x20.DS18X20(onewire.OneWire(Pin(25)))
roms = ds_sensor.scan()
print('Found DS devices: ', roms)
# init I2C pin for OLED display
i2c = I2C(sda=Pin(21), scl=Pin(22))
display = ssd1306.SSD1306_I2C(128, 64, i2c)
# init variable
temp_dht, humi_dht, temp_ds = 0, 0, 0
# erase all pixel
display.fill(0)
# write a graph/image to the OLED display
display.fill_rect(0, 0, 32, 32, 1)
display.fill_rect(2, 2, 28, 28, 0)
display.vline(9, 8, 22, 1)
display.vline(16, 2, 22, 1)
display.vline(23, 8, 22, 1)
display.fill_rect(26, 24, 2, 4, 1)
display.text('MicroPython', 40, 0, 1)
display.text('Project', 40, 12, 1)
display.text('EE - UMY', 40, 24, 1)
display.show()
def handleInterrupt(timer):
# make variable 'temp_ds' as global variable
global temp_dht, humi_dht, temp_ds
# erase pixel x1,y1 to x2,y2
display.fill_rect(0, 35, 128, 64, 0)
# write text to the OLED display
display.text('T_DS: {:.2f}C'.format(temp_ds), 0, 35, 1)
display.text('T_DHT: {:.2f}C'.format(temp_dht), 0, 45, 1)
display.text('H_DHT: {:.2f}%'.format(humi_dht), 0, 55, 1)
display.show()
# configure interrupt timer every 100 ms then call the handle interrupt function
timer.init(period=1000, mode=Timer.PERIODIC, callback=handleInterrupt)
# main program
while True:
# execute below code, then if there is a mistake, jump to the exception
try:
# recovers measurements from DHT22
dht_sensor.measure()
temp_dht = dht_sensor.temperature()
humi_dht = dht_sensor.humidity()
# convert temperature from DS18B20
ds_sensor.convert_temp()
for rom in roms:
temp_ds = ds_sensor.read_temp(rom)
# the DHT22 and DS18X20 return at most 1 measurement every 2s
print("Temperature DS18X20: {:.1f}°C, Temperature DHT22: {:.1f}°C, Humidity DHT22: {:.1f}%".format(temp_ds, temp_dht, humi_dht))
sleep(2)
except OSError as e:
print("Failed reception")Loading
ds18b20
ds18b20