#include <LiquidCrystal_I2C.h>
#include <DHT.h>
uint8_t dot[] = {0x0e, 0x0A, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00};
LiquidCrystal_I2C lcd(0x27, 20, 4); // Update address
DHT dht(32, DHT22);
unsigned long prevMillis = 0;
const unsigned long interval = 4000; // 4 second interval
bool alarmOn = false;
void setup() {
Serial.begin(115200);
Serial.println("Hello Lab 3");
dht.begin();
lcd.init();
lcd.backlight();
lcd.createChar(0, dot); // Use slot 0
}
void loop() {
unsigned long currentMillis = millis();
// Non-blocking 4-second timer
if (currentMillis - prevMillis >= interval) {
prevMillis = currentMillis;
// Read sensor data
float h = dht.readHumidity(); // Relative humidity
float c = dht.readTemperature(); // Celsius
float f = dht.readTemperature(true); // Fahrenheit
// Check if any reads failed and try again
if (isnan(h) || isnan(c) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print temp & humidity to serial port
Serial.printf("Temp=%.2f °C, %.2f °F; RH=%.1f%%\n", c, f, h);
// Print to LCD
lcd.setCursor(0, 0);
lcd.print("RH=");
lcd.print(h, 1);
lcd.print("% ");
lcd.setCursor(0, 1);
lcd.print("Temp=");
lcd.print(c, 2);
lcd.write(0); // degree symbol
lcd.print("C ");
lcd.setCursor(0, 2);
lcd.print("Temp=");
lcd.print(f, 2);
lcd.write(0); // degree symbol
lcd.print("F ");
// Alarm for threshold temperature exceeding or equal to 90 °F
if (f >= 90.0 && !alarmOn) {
Serial.println("Temp >= 90 °F App");
lcd.setCursor(0, 3);
lcd.print("Temp >= 90 F App ");
alarmOn = true;
}
else if (f < 90.0 && alarmOn) {
Serial.println("Temp >= 90 °F Disp");
lcd.setCursor(0, 3);
lcd.print("Temp >= 90 F Disp");
alarmOn = false;
}
}
}Practical Test 1: Question 3 (Friday)
1. Print temperatures and humidity on the serial port
2. Print humidity on the 1st row of the LCD
3. Print temperature with with °C on the 2nd row of the LCD
4. Print temperature with the with °F on the 3rd row of the LCD
5. Alarm processing on 90 °F on the 4th row of the LCD