from machine import Pin, PWM, ADC, I2C
from time import sleep
from dht import DHT22
from servo import Servo
from ssd1306 import SSD1306_I2C
from max7219 import Matrix8x8
# Constants
DHT_PIN = Pin(15)
GAS_PIN = ADC(Pin(32))
LED_PIN = Pin(2, Pin.OUT)
SERVO_PIN = PWM(Pin(25), freq=50)
I2C_SCL = Pin(22)
I2C_SDA = Pin(21)
LCD_I2C_ADDRESS = 0x27
OLED_WIDTH = 128
OLED_HEIGHT = 64
# DHT22 sensor
dht = DHT22(DHT_PIN)
# OLED Display
i2c = I2C(1, scl=I2C_SCL, sda=I2C_SDA)
oled = SSD1306_I2C(OLED_WIDTH, OLED_HEIGHT, i2c)
# Servo motor
servo = Servo(SERVO_PIN)
# LED Dot Matrix
matrix = Matrix8x8(Pin(5), Pin(18), Pin(19))
def display_oled(temp, hum, gas_level):
oled.fill(0)
oled.text("Smart Agriculture", 0, 0)
oled.text("Temp: {:.1f} C".format(temp), 0, 10)
oled.text("Hum: {:.1f}%".format(hum), 0, 20)
oled.text("Gas: {}".format(gas_level), 0, 30)
oled.show()
def alert_system(temp, hum, gas_level):
# LED Alert
if temp > 30 or hum < 20 or gas_level > 500:
LED_PIN.value(1)
print("ALERT: Unsafe conditions detected!")
print("- Temperature above threshold: {:.1f} C".format(temp) if temp > 30 else "")
print("- Humidity below threshold: {:.1f}%".format(hum) if hum < 20 else "")
print("- Gas level above threshold: {}".format(gas_level) if gas_level > 500 else "")
else:
LED_PIN.value(0)
print("STATUS: All conditions within safe thresholds.")
# Servo Motor Control
if temp > 30:
servo.set_angle(90) # Open valve
print("Servo action: Opening valve to cool the environment.")
else:
servo.set_angle(0) # Close valve
print("Servo action: Closing valve.")
# Dot Matrix Display
matrix.fill(0)
matrix.text('H' if temp > 30 else 'L', 0, 0)
matrix.show()
print("Dot Matrix Display: Showing '{}' for temperature condition.".format('H' if temp > 30 else 'L'))
def main():
print("System is starting...")
print("Initializing sensors and components...")
sleep(2)
while True:
try:
# Read DHT22 Sensor
print("Reading DHT22 sensor...")
dht.measure()
temp = dht.temperature()
hum = dht.humidity()
# Read Gas Sensor
print("Reading Gas sensor...")
gas_level = GAS_PIN.read()
# Debugging Sensor Values
print("DEBUG: Sensor Readings")
print("- Temperature: {:.1f} C".format(temp))
print("- Humidity: {:.1f}%".format(hum))
print("- Gas Level: {}".format(gas_level))
# Update OLED Display
print("Updating OLED display...")
display_oled(temp, hum, gas_level)
# Alert System
print("Checking thresholds and activating components...")
alert_system(temp, hum, gas_level)
except Exception as e:
print("ERROR: {}".format(e))
# Wait before the next reading
print("Waiting for next cycle...\n")
sleep(2)
# Run the program
main()