Temperature sensor on arduino
Temperature and humidity are two of the most commonly measured environmental parameters. Whether you're building a weather station, an indoor climate monitor, or an automated greenhouse, sensors like DHT11 and LM35 offer simple, low-cost ways to gather this data using an Arduino board.
In this guide, we will explore how these sensors work, understand their differences, and prepare for a hands-on exercise where you'll use them to measure and display temperature and humidity values.
Video lesson: Arduino Temperature Sensor Tutorial – LM35 & DHT11 with Serial Data & Processing Challenge
Introduction – Measuring Temperature with Arduino
Temperature monitoring is essential in many embedded and environmental applications, such as climate control, soil monitoring, or weather stations. For this purpose, we commonly use temperature sensors such as:
- LM35 – an analog temperature sensor that provides a linear voltage output directly proportional to the Celsius temperature (10 mV per °C).
- DHT11 / DHT22 – digital temperature and humidity sensors that communicate using a single digital pin and provide temperature and humidity data in a digital format.
- Vcc (Pin 1) → connect to +5V on Arduino
- GND (Pin 2) → connect to GND on Arduino
- Vout (Pin 3) → connect to Analog pin A2 on Arduino (or any analog input pin)
What the Code Does
You will find comments in the code explaining the role of each line and variable.
int read_pin = A2; // Analog pin A2 is used to read the sensor's analog voltage
float readValue; // Variable to store raw analog reading (0-1023)
float calcValue; // Variable to store converted voltage
float TempC = 0; // Variable to store calculated temperature in Celsius
float scale_f = 0.01; // Scale factor: 10mV per degree Celsius → 0.01 V/°C
void setup()
{
Serial.begin(9600); // Start serial communication at 9600 baud rate
void loop()
{
calcValue = readValue * 5.0 / 1023; // Convert raw value to voltage
TempC = calcValue / scale_f; // Convert voltage to temperature (Celsius)
Serial.println("Calc value: "); // Print label
Serial.println(calcValue);
Serial.println("T[C]: ");
Serial.println(TempC);
delay(250); // Wait 250ms before the next reading
What Is the Scale Factor?
This means: If the output voltage of LM35 is 100 mV, the temperature is 10°C.
If it is 250 mV, the temperature is 25°C, and so on.
How the Scale Factor Works in This Example
Let’s break it down in this code:
calcValue = readValue * 5.0 / 1023; // convert raw value to voltage (0.0V to 5.0V)
TempC = calcValue / scale_f; // convert voltage to temperature
- analogRead() returns a value from 0 to 1023, which represents 0V to 5V.
- calcValue = readValue * 5.0 / 1023 converts the analog value into a voltage.
- scale_f = 0.01 → because:
- LM35 outputs 10 mV = 0.01 V per 1°C
- To get temperature, we divide the voltage by 0.01
So, putting it all together:
Temperature (°C) = Voltage / 0.01
For example:
- analogRead() = 512
- Voltage = 512 * 5.0 / 1023 ≈ 2.5 V
- Temperature = 2.5 / 0.01 = 250°C
Note: If you measure 2.5V from LM35, that would mean 250°C, which is unrealistic for room temperature. So usually, the reading for room temp (≈25°C) is around 0.25V, which corresponds to an analogRead() of about 51.
DHT11 – Digital Temperature and Humidity Sensor
Overview of the Sensors
DHT11 – Digital Temperature and Humidity Sensor
The DHT11 is a basic and affordable digital sensor capable of measuring both temperature and relative humidity. It integrates:
- A thermistor for temperature sensing
- A capacitive humidity sensor
- A signal processing chip that outputs clean digital data
Key Features:
- Measures temperature (0°C to 50°C) with ±2°C accuracy
- Measures humidity (20% to 90% RH) with ±5% RH accuracy
- Outputs a digital signal over a single pin
- Requires minimal external components
- Works with 3V to 5V supply
LM35 – Analog Temperature Sensor
The LM35 is a precise analog temperature sensor. Unlike the DHT11, it only measures temperature, but over a much wider range and with greater accuracy.
Key Features:
- Measures from –55°C to +150°C
- Accuracy typically ±0.5°C
- Output is analog voltage: 10 mV per °C (e.g., 250 mV = 25°C)
- Requires conversion from voltage to temperature in code
Task Title:
Read and display environmental temperature and humidity using the DHT11 sensor and Arduino.
Objective:
- Learn how to connect a DHT11 sensor to an Arduino board
- Write a program to read digital data from the sensor
- Display the temperature and humidity values using the Serial Monitor
Components Needed:
| Component | Quantity |
|---|---|
| Arduino Uno (or compatible) | 1 |
| DHT11 Sensor | 1 |
| Breadboard | 1 |
| Jumper wires | 3 |
| USB cable | 1 |
Circuit Wiring for the DHT11 Sensor
To properly connect the DHT11 sensor to your Arduino, you’ll need to make just a few simple connections.Usually on the original DHT sensor the pins are labeled as Vcc, Signal and GND. The VCC pin of the sensor should be connected to the 5V output on the Arduino, providing the necessary power. The GND pin goes to the GND on the Arduino to complete the circuit. Finally, the DATA pin is connected to digital pin 3, which is used for communication between the sensor and the microcontroller. If you’re using a DHT11 module (often with 3 pins), no additional components are necessary since it already includes a pull-up resistor. However, if you have the raw 4-pin DHT11 sensor, you’ll need to place a 10 kΩ pull-up resistor between the VCC and DATA pins to ensure stable data transmission. This simple setup allows your Arduino to accurately read temperature and humidity values from the DHT11 sensor using a digital signal.
How to Use the DHT11 Sensor with Arduino
To read environmental temperature and humidity using the DHT11 sensor, begin by connecting the sensor to your Arduino board as previously described. Once the wiring is complete, open the Arduino IDE on your computer to prepare your code. If you haven’t installed the necessary library yet, go to Sketch > Include Library > Manage Libraries, search for “DHT sensor library” by Adafruit, and install it. This library simplifies communication with the DHT11 sensor. After installing the library, open a new sketch and write your Arduino code to read temperature and humidity data. Connect your Arduino via USB and upload the sketch. Then, open the Serial Monitor (shortcut: Ctrl+Shift+M) and set the baud rate to 9600. You should see temperature (in °C) and humidity (% RH) values displayed and updated every 2 seconds.
Challenge: Visualize the Data in Processing
To extend your project, you can send the data from Arduino to a Processing sketch via serial communication. In Processing, use simple shapes to visualize the sensor readings in real time. For example: You can display a circle that turns red if the temperature exceeds 30 °C. Use a rectangle whose height reflects the current humidity. Change the background color based on humidity — for instance, make it blue when humidity drops below 30%. This optional challenge helps you explore data communication between platforms and create real-time visual feedback based on environmental conditions.
Code in ArduinoIDE
Example Arduino Code: Reading Data from the DHT11 Sensor
The following code demonstrates how to read temperature and humidity using the DHT11 sensor connected to digital pin 3 on an Arduino board. It uses the Adafruit DHT library and prints the values to the Serial Monitor at a baud rate of 115200.
// Include the DHT sensor library
#include "DHT.h"
// Define the pin where the DHT sensor is connected
#define DHTPIN 3
// Define the type of DHT sensor (DHT11 or DHT22)
#define DHTTYPE DHT11
// Create a DHT object
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Initialize serial communication at 115200 baud rate
Serial.begin(115200);
// Initialize the DHT sensor
dht.begin();
Serial.println("DHT sensor initialized");
}
void loop() {
// Wait 1 second between readings (DHT11 needs at least 1s delay)
delay(1000);
// Read humidity
Serial.println("Before reading humidity...");
float h = dht.readHumidity();
Serial.println("After reading humidity...");
delay(1000); // Optional extra delay
// Read temperature
float t = dht.readTemperature();
Serial.println("After reading temperature...");
Serial.println("Attempted sensor read");
// Check if any reads failed and exit early (returns NaN on error)
if (isnan(h) || isnan(t)) {
Serial.println("Error reading from DHT sensor!");
} else {
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\tTemperature: ");
Serial.print(t);
Serial.println(" °C");
}
}
Note: The DHT11 sensor requires a minimum delay of 1 second between consecutive readings. Always check for NaN values to detect potential read errors.
1. Including the Library and Definitions
// Include the DHT sensor library
#include "DHT.h"
// Define the pin where the DHT sensor is connected
#define DHTPIN 3
// Define the type of DHT sensor (DHT11 or DHT22)
#define DHTTYPE DHT11
#include "DHT.h" – Loads the DHT sensor library.
#define DHTPIN 3 – Assigns digital pin 3 for the sensor's DATA pin.
#define DHTTYPE DHT11 – Specifies the sensor model being used.
2. Creating the Sensor Object
// Create a DHT object
DHT dht(DHTPIN, DHTTYPE);
An object named dht is created to interact with the sensor.
3. setup() – Initialization
void setup() {
// Initialize serial communication at 115200 baud rate
Serial.begin(115200);
// Initialize the DHT sensor
dht.begin();
Serial.println("DHT sensor initialized");
}
Serial.begin(115200);– Starts serial communication with the monitor.dht.begin();– Initializes the sensor.- Prints confirmation message to the Serial Monitor.
4. loop() – Reading Sensor Data
void loop() {
// Wait 1 second between readings (DHT11 needs at least 1s delay)
delay(1000);
// Read humidity
Serial.println("Before reading humidity...");
float h = dht.readHumidity();
Serial.println("After reading humidity...");
delay(1000); // Optional extra delay
// Read temperature
float t = dht.readTemperature();
Serial.println("After reading temperature...");
Serial.println("Attempted sensor read");
...
}
delay(1000); – Ensures there's enough time between sensor reads.
Humidity and temperature values are read and debug messages are printed before and after.
5. Error Checking and Output
// Check if any reads failed and exit early (returns NaN on error)
if (isnan(h) || isnan(t)) {
Serial.println("Error reading from DHT sensor!");
} else {
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\tTemperature: ");
Serial.print(t);
Serial.println(" °C");
}
}
isnan(h) || isnan(t) – Verifies if either read returned an invalid value.
If so, prints an error message. Otherwise, prints humidity and temperature values.
Conclusion
• Serial communication and sensor setup are done in setup().
• In the loop(): delay, sensor reading, error check, and output to monitor.
• The code is clean, simple, and effective for using a DHT11 sensor with Arduino.
Read temperature data in processing
Serial myPort; // Serial port object for communication
float temperature = 0; // Variable to store the received temperature value
void setup() {
size(400, 400); // Set window size to 400x400 pixels
// Initialize serial communication
// Serial.list()[0] gets the first available serial port (you might need to change the index)
// 115200 is the baud rate and must match the rate set on the sending device
myPort = new Serial(this, Serial.list()[ 0 ], 115200);
}
void draw() {
background(200); // Light gray background
// Check if there are any bytes available to read from the serial port
int availablesByte = myPort.available();
if (availablesByte > 0) {
// Create a byte array to hold the incoming data
byte[] bytes = new byte[availablesByte];
// Read the bytes into the array
myPort.readBytes(bytes);
// Convert the byte array to a String
String str = new String(bytes);
// Try converting the string to a float (temperature value)
try {
temperature = Float.parseFloat(str.trim()); // Remove extra whitespace and parse
println("Received temperature: " + temperature); // Print the parsed temperature
} catch (NumberFormatException ex) {
// If parsing fails, print the error message
println("Conversion error: " + ex.getMessage());
}
}
}
This Processing sketch demonstrates how to read temperature data from an external device (like an Arduino) using serial communication.
First, the Serial library is imported with:
import processing.serial.*;
This enables the use of the Serial class for managing serial communication.
A variable temperature is declared to store the numeric value received:
float temperature = 0;
In the setup() function, the window size is set with:
size(400, 400);
Then, serial communication is initialized:
myPort = new Serial(this, Serial.list()[0], 115200);
The baud rate must match the sending device's rate.
The draw() function continuously runs. It starts by setting the background color:
background(200);
The sketch then checks for available bytes on the serial port:
int availablesByte = myPort.available();
If any are present, it reads them:
byte[] bytes = new byte[availablesByte];
myPort.readBytes(bytes);
The bytes are converted into a string:
String str = new String(bytes);
To extract a valid number, the sketch tries to parse the string:
try {
temperature = Float.parseFloat(str.trim());
println("Received temperature: " + temperature);
} catch (NumberFormatException ex) {
println("Conversion error: " + ex.getMessage());
}
If the conversion fails, an error message is printed to help with debugging.
|
You can download the contents of the first 3 exercises:
|
| ||
|
Previous
|< Light level display (LDR sensor) |

