# Importation des bibliothèques nécessaires
from machine import Pin
import time
import dht
# Initialize LEDs and the DHT22 sensor
green_led = Pin(4, Pin.OUT)
red_led = Pin(2, Pin.OUT)
PIN_DHT = 15 # GPIO for the DHT22
sensor = dht.DHT22(Pin(PIN_DHT))
def control_led_dht(command):
"""
Control the LEDs and read data from the DHT22 sensor based on the command.
"""
if command.upper() == "ON":
print("System is ON")
red_led.off() # Turn off the red LED
green_led.on() # Turn on the green LED
return True
else:
# Message d'erreur pour les commandes non reconnues
print(f"Invalid command: {command}. Please use 'ON' to start , 'Ctrl + C' to end the program ")
return False
def read_temperature_humidity():
"""
Read temperature and humidity data from the DHT22 sensor.
"""
# Gérer les erreurs de lecture
try:
sensor.measure()# Demander une mesure au capteur
temperature = sensor.temperature()# Lire la température
humidity = sensor.humidity()# Lire l'humidité
print(f"Temperature: {temperature}°C, Humidity: {humidity}%")
# Check if the temperature is critical
if temperature > 40 or temperature < 0:
show_alert(f"Critical Temperature: {temperature}°C")# Afficher une alerte
else:
green_led.on() # Turn off the red LED if no alert
red_led.off()
return temperature, humidity
except Exception as e:
print(f"Sensor read error: {e}")
return None, None
def show_alert(message):
"""
Display an alert (both on the console and the red LED).
"""
print(f"⚠️ Alert: {message}")
green_led.off()
red_led.on() # Turn on the red LED to signal an alert
time.sleep(0.5)
red_led.off()
time.sleep(0.5)
red_led.on() # Turn on the red LED to signal an alert
def main():
"""
Main function to start the program and continuously read sensor data.
"""
print("Please use 'ON' to start , 'Ctrl + C' to end the program")
while True:
command = input("Enter command: ")
if control_led_dht(command): # Start the program when 'ON' is entered
try:
# Continuously read the sensor data until the user stops the program
while True:
read_temperature_humidity()
time.sleep(2) # Read every 2 seconds
except KeyboardInterrupt:
print("Program terminated by user with Ctrl + C.")
green_led.off()
red_led.off()
break
# Run the main program
main()