A thermometer with an alarm
Section 11: Smart systemsLesson 11.3 · ⏱ 8 min
The temperature on the screen, and above 30 degrees the red LED lights up.
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
DHT dht(2, DHT11);
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
dht.begin();
lcd.init();
lcd.backlight();
pinMode(13, OUTPUT);
}
void loop() {
float t = dht.readTemperature();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(t);
if (t > 30) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
delay(500);
}


🖥️ What happens on the stage?
We ran this code in Robo Maker and the challenge passed: “Bravo! It works”.
📌 Another example: the cold alarm
The LED lights if the temperature drops below 10.
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
DHT dht(2, DHT11);
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
dht.begin();
lcd.init();
lcd.backlight();
pinMode(13, OUTPUT);
}
void loop() {
float t = dht.readTemperature();
lcd.setCursor(0, 0);
lcd.print(t);
if (t < 10) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
delay(500);
}


✍️ Practise
Make the thermometer.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
A heat alarm: above 30 the LED lights up and it writes “HOT!”.
👀 Show the solution🙈 Hide the solution
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
DHT dht(2, DHT11);
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
dht.begin();
lcd.init();
lcd.backlight();
pinMode(13, OUTPUT);
}
void loop() {
float t = dht.readTemperature();
lcd.clear();
lcd.setCursor(0, 0);
if (t > 30) {
digitalWrite(13, HIGH);
lcd.print("HOT!");
} else {
digitalWrite(13, LOW);
lcd.print(t);
}
delay(500);
}

Result: HOT! and the LED is on.
Medium
The LED blinks if the temperature goes above 35.
👀 Show the solution🙈 Hide the solution
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
DHT dht(2, DHT11);
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
dht.begin();
lcd.init();
lcd.backlight();
pinMode(13, OUTPUT);
}
void loop() {
float t = dht.readTemperature();
if (t > 35) {
digitalWrite(13, HIGH);
delay(200);
digitalWrite(13, LOW);
delay(200);
} else {
digitalWrite(13, LOW);
}
}

Result: blinking in great heat.
Hard
Three states on the screen: COLD below 15, HOT above 30, otherwise NICE.
👀 Show the solution🙈 Hide the solution
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
DHT dht(2, DHT11);
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
dht.begin();
lcd.init();
lcd.backlight();
pinMode(13, OUTPUT);
}
void loop() {
float t = dht.readTemperature();
lcd.clear();
lcd.setCursor(0, 0);
if (t < 15) {
lcd.print("COLD");
} else if (t > 30) {
lcd.print("HOT");
} else {
lcd.print("NICE");
}
delay(500);
}

Result: NICE, then COLD.

