#include #include LiquidCrystal_I2C lcd(0x27, 16, 2); constexpr unsigned int SENSOR_PIN {7U}; AM2302::AM2302_Sensor am2302{SENSOR_PIN}; const int potPin = A1; // Timing unsigned long lastLcdUpdate = 0; unsigned long lastSensorRead = 0; const unsigned long lcdInterval = 1000; const unsigned long sensorInterval = 2000; // State int lastMenuIndex = -1; float temperature = NAN; float humidity = NAN; const int relayPin = 12; unsigned long lastRelayToggle = 0; const unsigned long relayInterval = 2000; bool relayState = false; void readSensor(unsigned long now) { if (now - lastSensorRead >= sensorInterval) { lastSensorRead = now; if (am2302.read() == AM2302::AM2302_READ_OK) { humidity = am2302.get_Humidity(); temperature = am2302.get_Temperature(); } } } void updateRelay(unsigned long now) { if (now - lastRelayToggle >= relayInterval) { lastRelayToggle = now; relayState = !relayState; // toggle state digitalWrite(relayPin, relayState ? HIGH : LOW); } } void updateLCD(unsigned long now) { int potValue = analogRead(potPin); int menuIndex = (potValue < 512) ? 0 : 1; if (menuIndex != lastMenuIndex || now - lastLcdUpdate >= lcdInterval) { lastMenuIndex = menuIndex; lastLcdUpdate = now; lcd.clear(); if (menuIndex == 0) { lcd.setCursor(0, 0); lcd.print("Humidity:"); lcd.setCursor(0, 1); if (!isnan(humidity)) { lcd.print(humidity); lcd.print("%"); } else { lcd.print("No data"); } } else { lcd.setCursor(0, 0); lcd.print("Temperature:"); lcd.setCursor(0, 1); if (!isnan(temperature)) { lcd.print(temperature); lcd.print(" C"); } else { lcd.print("No data"); } } } } void setup() { pinMode(relayPin, OUTPUT); digitalWrite(relayPin, LOW); // start OFF lcd.init(); lcd.backlight(); am2302.begin(); lcd.setCursor(0, 0); lcd.print("Starting..."); } void loop() { unsigned long now = millis(); readSensor(now); updateLCD(now); updateRelay(now); }