The temperature on the screen
Section 10: Sensors and screens in codeLesson 10.4 · ⏱ 7 min
The DHT11 sensor reads the temperature with dht.readTemperature(), and the LCD screen writes with lcd.print. setCursor(0, 0) = the start of the screen.
#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();
}
void loop() {
float t = dht.readTemperature();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(t);
lcd.print(" C");
delay(1000);
}

🖥️ What happens on the stage?
We ran this code in Robo Maker and the challenge passed: “Bravo! It works”.
📌 Another example: temperature and humidity
The first line for the temperature, and the second line for the humidity (readHumidity).
#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();
}
void loop() {
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(dht.readTemperature());
lcd.setCursor(0, 1);
lcd.print("Hum: ");
lcd.print(dht.readHumidity());
delay(1000);
}

✍️ Practise
Write the temperature on the screen.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Write “Robo Weather” on the first line, and the temperature on the second.
👀 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();
lcd.setCursor(0, 0);
lcd.print("Robo Weather");
}
void loop() {
lcd.setCursor(0, 1);
lcd.print(dht.readTemperature());
lcd.print(" C");
delay(1000);
}

Result: the title and the temperature.
Medium
Turn it into Fahrenheit: F = C × 9 ÷ 5 + 32.
👀 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();
}
void loop() {
float c = dht.readTemperature();
float f = c * 9 / 5 + 32;
lcd.setCursor(0, 0);
lcd.print(f);
lcd.print(" F");
delay(1000);
}

Result: 25 degrees Celsius = 77 Fahrenheit.
Hard
Write “HOT” if the temperature goes above 30, otherwise “OK”.
👀 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();
}
void loop() {
float t = dht.readTemperature();
lcd.clear();
lcd.setCursor(0, 0);
if (t > 30) {
lcd.print("HOT");
} else {
lcd.print("OK");
}
delay(500);
}

Result: OK, then HOT.

