from machine import Pin, I2C, ADC
import utime
import ssd1306
from dht import DHT22
# ---------------------- Setup ----------------------
# Ultrasonic sensor
trigger = Pin(27, Pin.OUT)
echo = Pin(26, Pin.IN)
# DHT22
dht = DHT22(Pin(15))
# Potentiometer (Battery level)
battery = ADC(28)
# OLED display
i2c = I2C(0, scl=Pin(1), sda=Pin(0))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# ---------------------- Functions ----------------------
def get_distance():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(10)
trigger.low()
# Wait for echo
while echo.value() == 0:
signal_off = utime.ticks_us()
while echo.value() == 1:
signal_on = utime.ticks_us()
time_passed = signal_on - signal_off
distance = (time_passed * 0.0343) / 2
return round(distance, 2)
def get_battery_level():
adc_val = battery.read_u16() # 0–65535
voltage = (adc_val / 65535) * 3.3
percent = (voltage / 3.3) * 100
return round(percent, 1)
def display_data(temp, hum, dist, batt):
oled.fill(0)
oled.text("SMART MONITOR", 10, 0)
oled.text("Temp: {:.1f}C".format(temp), 0, 16)
oled.text("Hum: {:.1f}%".format(hum), 0, 26)
oled.text("Dist: {:.1f}cm".format(dist), 0, 36)
oled.text("Batt: {:.1f}%".format(batt), 0, 46)
if temp > 70:
oled.text("!! DANGER !!", 20, 56)
oled.show()
# ---------------------- Main Loop ----------------------
while True:
try:
# Read DHT22
dht.measure()
temp = dht.temperature()
hum = dht.humidity()
# Read Ultrasonic
dist = get_distance()
# Read Potentiometer
batt = get_battery_level()
# Print to console
print(f"Temp: {temp}C Hum: {hum}% Dist: {dist}cm Batt: {batt}%")
# Update OLED
display_data(temp, hum, dist, batt)
utime.sleep(2)
except Exception as e:
print("Error:", e)
utime.sleep(2)