Arduino Program to Display Temperature in °C on Serial
Monitor
We will use the DHT11 or DHT22 temperature sensor to measure the temperature and display it
on the Serial Monitor.
🛠️ Required Components
1. Arduino Uno (R3)
2. DHT11 or DHT22 Temperature Sensor
3. 10kΩ Pull-up Resistor (Required for DHT22)
4. Jumper Wires
5. Breadboard (Optional)
🔌 Circuit Connections
DHT Sensor Pin Arduino Pin
VCC (Power) 5V
GND (Ground) GND
DATA (Signal) D2
(For DHT22, connect a 10kΩ resistor between VCC and DATA pin.)
📜 Arduino Code
cpp
CopyEdit
#include <DHT.h> // Include the DHT library
#define DHTPIN 2 // Define the pin connected to the DHT sensor
#define DHTTYPE DHT11 // Change to DHT22 if using DHT22
DHT dht(DHTPIN, DHTTYPE); // Initialize the sensor
void setup() {
Serial.begin(9600); // Start Serial Monitor
Serial.println("DHT Sensor Initialized");
dht.begin(); // Start the DHT sensor
}
void loop() {
float temperature = dht.readTemperature(); // Read temperature in °C
if (isnan(temperature)) { // Check if reading is valid
Serial.println("Error reading temperature!");
} else {
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
}
delay(2000); // Wait 2 seconds before the next reading
}
📖 Code Explanation
1⃣ Including the DHT Library
cpp
CopyEdit
#include <DHT.h>
This library helps in reading data from the DHT sensor.
2️⃣ Defining Sensor Pin and Type
cpp
CopyEdit
#define DHTPIN 2
#define DHTTYPE DHT11
We define DHTPIN as 2 (connected to Arduino digital pin 2).
The DHTTYPE is set to DHT11 (change to DHT22 if using DHT22).
3️⃣ Initializing the Sensor
cpp
CopyEdit
DHT dht(DHTPIN, DHTTYPE);
This creates a DHT object to handle temperature readings.
4️⃣ Setup Function
cpp
CopyEdit
void setup() {
Serial.begin(9600);
Serial.println("DHT Sensor Initialized");
dht.begin();
}
Start serial communication at 9600 baud for displaying output.
Initialize the DHT sensor.
5️⃣ Loop Function
cpp
CopyEdit
void loop() {
float temperature = dht.readTemperature();
This reads the temperature in Celsius from the DHT sensor.
6️⃣ Checking if Reading is Valid
cpp
CopyEdit
if (isnan(temperature)) {
Serial.println("Error reading temperature!");
}
If the sensor fails to read data, it prints an error message.
7️⃣ Printing the Temperature
cpp
CopyEdit
else {
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
}
If the reading is successful, it prints the temperature.
8️⃣ Delay Before Next Reading
cpp
CopyEdit
delay(2000);
The code waits 2 seconds before taking the next reading.
📟 Output on Serial Monitor
1. Open Arduino IDE.
2. Upload the Code.
3. Open Serial Monitor (Baud Rate: 9600).
4. You will see:
makefile
CopyEdit
DHT Sensor Initialized
Temperature: 28.5 °C
Temperature: 28.6 °C
Temperature: 28.4 °C