"""
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Humidity and Temperature Sensor with OLED Display and ┃
┃ RGB Led (MicroPython) ┃
| |
┃ A Humidity and Temperature sensors that would detect than┃
┃ display the output on the OLED Display while the RGB LED ┃
┃ would change colour whether the temp is Cold, Moderate ┃
┃ or Hot ┃
| |
┃ CHE MUHAMMAD HAFIZ HAKIMI BIN CHE MOHD YANI ┃
┃ 51221223163 ┃
┃ ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
"""
from machine import Pin
from machine import Pin, I2C
import machine
import ssd1306
import dht
import time
# Pin Definitions
DHT_PIN = 4 # DHT22 data pin
LED_R_PIN = 19 # Red LED pin
LED_G_PIN = 18 # Green LED pin
LED_B_PIN = 5 # Blue LED pin
# Initialize DHT22 sensor
dht_sensor = dht.DHT22(machine.Pin(DHT_PIN))
# Initialize OLED display
i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21))
oled = SSD1306_I2C(128, 64, i2c)
# Function to read temperature and humidity
def read_sensor():
try:
dht_sensor.measure()
temp_c = dht_sensor.temperature()
humidity = dht_sensor.humidity()
return temp_c, humidity
except Exception as e:
print("Error reading DHT22 sensor:", e)
return None, None
# Function to update OLED display
def update_display(temp, humidity):
oled.fill(0)
oled.text("Temp: {:.1f} C".format(temp), 0, 0)
oled.text("Humidity: {:.1f}%".format(humidity), 0, 16)
oled.show()
# Function to control RGB LED based on temperature
def control_led(temp):
if temp < 20:
led_r.duty(0) # Red LED off
led_g.duty(0) # Green LED off
led_b.duty(1023) # Blue LED on
elif temp >= 20 and temp < 30:
led_r.duty(0) # Red LED off
led_g.duty(1023) # Green LED on
led_b.duty(0) # Blue LED off
else:
led_r.duty(1023) # Red LED on
led_g.duty(0) # Green LED off
led_b.duty(0) # Blue LED off
# Initialize RGB LED PWM
led_r = machine.PWM(machine.Pin(LED_R_PIN), freq=1000)
led_g = machine.PWM(machine.Pin(LED_G_PIN), freq=1000)
led_b = machine.PWM(machine.Pin(LED_B_PIN), freq=1000)
# Main loop
while True:
temp, humidity = read_sensor()
if temp is not None and humidity is not None:
update_display(temp, humidity)
control_led(temp)
time.sleep(2) # Update every 2 seconds