Digital ChallengeArduino × Processing
P1Project module

Temperature & Humidity — DHT11

Build a mini weather station that streams live climate data.

Measure air temperature and relative humidity with a DHT11 sensor, send both values as CSV over serial, and visualize them in real time with Processing — your first IoT-style system.

2 × 45 min difficultyPhysicsComputer ScienceMathematics
Temperature & Humidity — DHT11
LibrariesCSV over serialisnan() checksThreshold alarms
01Before you start

What you’ll learn

By the end of this module you can…
  • 1Install and use an Arduino library (Adafruit DHT sensor library).
  • 2Wire a digital sensor and explain the role of a pull-up resistor.
  • 3Explain what relative humidity means physically.
  • 4Send two measurements in one CSV line and parse them in Processing.
  • 5Detect sensor errors with isnan() and add a high-temperature alarm.
Key vocabulary
DHT11
A low-cost digital sensor for temperature (0–50 °C, ±2 °C) and humidity (20–90 % RH, ±5 %).
Relative humidity (RH)
How much water vapour the air holds compared with the maximum it could hold at that temperature, in %.
Library
Ready-made code you include to talk to a component without writing everything yourself.
Pull-up resistor
A resistor that keeps a signal line at HIGH when nothing is pulling it LOW.
NaN
“Not a Number” — the value returned when a reading failed. Test with isnan().
IoT
Internet of Things — everyday objects with sensors that share data.
02Kit list

Required equipment

ComponentQtyPurpose
Arduino Uno1Microcontroller
DHT11 sensor1Temperature and humidity measurement
10 kΩ resistor1Pull-up resistor (only for the bare 3/4-pin sensor)
Breadboard1Component connection
Jumper wires~5Component connection
USB cable1Connection to computer
Arduino IDE + Processing1Programming and visualization
03Theory

Theoretical Background

What is the DHT11?

The DHT11 is a digital sensor: it measures temperature and relative humidity and sends the result as a digital signal. No analog-to-digital conversion is needed, it is easy to connect, and ready-made libraries exist — perfect for beginners.

What is relative humidity?

Relative humidity is the percentage of water vapour in the air compared with the maximum amount the air can hold at that temperature and normal pressure. Warm air can hold more water than cold air — that’s why a cold bottle from the fridge “sweats” on a warm day.

Formula
RH = (actual water vapour ÷ maximum possible at this temperature) × 100 %

Serial communication

Arduino sends both readings in one line, separated by a comma:

Serial.println("24.5,60");   // temperature = 24.5 °C, humidity = 60 %
04Hands-on

Exercise 1 — Connecting the DHT11

DHT11 wiring to the Arduino Uno.
DHT11 wiring to the Arduino Uno.
DHT11 pinArduino pin
VCC5V
GNDGND
DATADigital pin 2

Using the bare 3/4-pin sensor? Place a 10 kΩ resistor between VCC and DATA.

Tip
The 3-pin DHT11 module (on a small PCB) already has a built-in pull-up resistor.

Step 1 — Install the library

  1. 01In the Arduino IDE open Sketch → Include Library → Manage Libraries.
  2. 02Search for “DHT sensor library” by Adafruit.
  3. 03Click Install (accept the “Adafruit Unified Sensor” dependency).

Step 2 — Arduino code

DHT11_Serial.inoArduino · C++
#include "DHT.h"

#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
}

void loop() {
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();   // Celsius

  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT sensor!");
    delay(2000);
    return;
  }

  Serial.print(temperature);
  Serial.print(",");
  Serial.println(humidity);
  delay(2000);                                 // DHT11: max. 1 reading per second
}
CommandExplanation
dht.readTemperature()Reads the temperature in °C
dht.readHumidity()Reads the relative humidity in %
isnan(x)True if the reading failed (Not a Number)
Serial.print()Sends data to the computer
delay(2000)Waits 2 seconds between readings
Tip
Data is sent as comma-separated values because Processing can split them easily.
05Hands-on

Exercise 2 — Data Visualization in Processing

The sketch reads the data from Arduino, shows temperature and humidity as text, and visualizes both with bars.

WeatherStation.pdeProcessing · Java
import processing.serial.*;

Serial myPort;
float temp = 0, hum = 0;

void setup() {
  size(500, 260);
  myPort = new Serial(this, Serial.list()[0], 9600);
  myPort.bufferUntil('\n');
}

void draw() {
  background(255);
  fill(0);
  textSize(20);
  text("Temperature: " + nf(temp, 1, 1) + " \u00B0C", 50, 70);
  text("Humidity: " + nf(hum, 1, 1) + " %", 50, 150);

  fill(220, 50, 50);                                  // temperature bar 0–50 °C
  rect(50, 85, map(temp, 0, 50, 0, 400), 25);
  fill(50, 100, 220);                                 // humidity bar 0–100 %
  rect(50, 165, map(hum, 0, 100, 0, 400), 25);

  if (temp > 30) {                                    // alert system
    fill(255, 0, 0);
    text("WARNING: HIGH TEMPERATURE!", 50, 235);
  }
}

void serialEvent(Serial p) {
  String data = p.readStringUntil('\n');
  if (data != null && data.contains(",")) {
    String[] values = split(trim(data), ",");
    if (values.length == 2) {
      temp = float(values[0]);
      hum  = float(values[1]);
    }
  }
}
UpdatedAdded the missing import processing.serial.*;, moved reading into serialEvent() and added bars and the alarm.
InteractiveCSV parserSimulate the weather station: type what Arduino would send.
  1. 1readStringUntil('\n')"23.5,61.0"
  2. 2data != null
  3. 3data.contains(",")
  4. 4split(trim(data), ",")["23.5", "61.0"]
  5. 5values.length == 2length = 2
  6. 6float(values[0]), float(values[1])23.5, 61
Processing window
Temperature: 23.5 °C
Humidity: 61.0 %

Line accepted and displayed.

06From the original handbook

Student tasks

Basic
Display temperature and humidity
Intermediate
Add graphical progress bars
Advanced
Add a high-temperature alarm
Challenge
Save data to a CSV file
Challenge
Draw a real-time graph
07When it doesn’t work

Troubleshooting

ProblemLikely causeFix
No data receivedIncorrect COM portUse printArray(Serial.list()) to find the correct port.
“Failed to read” messagePoorly connected sensor or wrong pinCheck DATA → pin 2 and that DHTTYPE is DHT11 (not DHT22).
Unstable valuesPoor contact on the breadboardPress wires in firmly; avoid long loose jumpers.
Processing not receiving dataSerial speed mismatchBoth sides 9600 baud.
Golden rule
Check the physical connections first, then the code. If nothing works, unplug, close both programs, reconnect and try again.
08New in this edition

Exercises

Basic · 2Intermediate · 2Advanced · 1Challenge · 1
P1.1BasicExplain 10 min

Read the datasheet

The DHT11 datasheet says: range 0–50 °C, accuracy ±2 °C; humidity 20–90 % RH, accuracy ±5 %. Your sensor shows 22 °C and 48 %. What are the possible real values? Could you use this sensor in a freezer?

Real temperature is between 20 °C and 24 °C, humidity between 43 % and 53 %. A freezer (≈ −18 °C) is outside the 0–50 °C range, so the DHT11 is not suitable — a DHT22 (−40…80 °C) would be.
P1.2BasicPredict 5 min

Parse it in your head

For each line Arduino might send, write what temp and hum become in the Processing sketch (or “unchanged”): 25.0,40.0 · Failed to read from DHT sensor! · 26.1, · 27.3,55.0,1

Check each guard: contains(",") and values.length == 2.
25.0,40.0 → temp 25.0, hum 40.0. · Error line → unchanged (no comma). · 26.1, → split gives ["26.1", ""], length 2, so temp = 26.1 and hum = NaN — a hidden bug! · 27.3,55.0,1 → length 3 → unchanged. Improvement: also check that both parts are not empty.
P1.3IntermediateCode 15 min

Comfort zone indicator

Classrooms are comfortable between 20–24 °C and 40–60 % RH. Add a large circle to the Processing sketch that is green inside the comfort zone, yellow if only one value is outside, and red if both are outside. Write the status text next to it.

Add to draw()Processing · Java
boolean tempOk = temp >= 20 && temp <= 24;
boolean humOk  = hum >= 40 && hum <= 60;
int bad = (tempOk ? 0 : 1) + (humOk ? 0 : 1);

if (bad == 0)      fill(0, 200, 90);
else if (bad == 1) fill(255, 200, 0);
else               fill(230, 40, 40);
ellipse(440, 40, 40, 40);

fill(0);
textSize(14);
text(bad == 0 ? "Comfortable" : bad == 1 ? "Check climate" : "Uncomfortable", 330, 80);
P1.4IntermediateCalculate 15 min

Dew point estimate

A simple approximation for the dew point (the temperature at which water condenses) is Td ≈ T − (100 − RH) / 5. Calculate Td for (a) 25 °C / 60 % and (b) 18 °C / 90 %. Then add the calculation to Processing and display it.

(a) 25 − 40/5 = 17 °C · (b) 18 − 10/5 = 16 °C — very close to the air temperature, so fog or condensation on windows is likely. In Processing: float dew = temp - (100 - hum) / 5.0;
P1.5AdvancedCode 20 min

Log to a CSV file

Save every reading with a timestamp to weather.csv so you can open it later in a spreadsheet and draw a chart.

Use PrintWriter output = createWriter("weather.csv"); in setup(), output.println(...) in serialEvent(), and output.flush(); output.close(); when a key is pressed.
Logging additionsProcessing · Java
PrintWriter output;

// in setup():
output = createWriter("weather.csv");
output.println("time,temperature,humidity");

// in serialEvent(), after parsing successfully:
String stamp = nf(hour(), 2) + ":" + nf(minute(), 2) + ":" + nf(second(), 2);
output.println(stamp + "," + temp + "," + hum);

void keyPressed() {
  if (key == 's') {   // press S to save and stop
    output.flush();
    output.close();
    exit();
  }
}
P1.6ChallengeDesign 45 min

Classroom climate study

Run a real investigation: log the classroom climate for one full lesson with windows closed and one with windows open. Plot both datasets, compare the averages, and write a short recommendation for your school (how often should you ventilate?).

  1. 01Formulate a hypothesis.
  2. 02Collect data with your logger (P1.5).
  3. 03Compute min, max and average for each condition.
  4. 04Present a chart and a 5-sentence conclusion.
Open-ended. A good report includes: a clear hypothesis, a description of the method (sensor position, interval), a chart with labelled axes and units, averages compared in a table, a discussion of sensor accuracy (±2 °C / ±5 %) and a practical recommendation.
09Check yourself

Self-check quiz

Progress
0/5 answered · 0 correct
  1. Q01

    What does the DHT11 measure?

  2. Q02

    What does isnan(temperature) check?

  3. Q03

    Why does the code wait 2 seconds between readings?

  4. Q04

    Warm air can hold … water vapour than cold air.

  5. Q05

    The 4-pin bare DHT11 needs a 10 kΩ resistor between…

10Beyond the classroom

Real world & extensions

Where this is used
smart homesweather stationsgreenhousesserver roomsIoT systemsindustrial automationmuseums and archives (protecting artwork from damp)
Extension ideas
  • +Add an OLED display
  • +Send data over WiFi (ESP32)
  • +Create a web dashboard
  • +Connect to a cloud platform (ThingSpeak, Blynk)
  • +Build a complete mini weather station with a pressure sensor
Cross-curricular connections
SubjectConnection
PhysicsTemperature, humidity, measurement accuracy
Computer ScienceLibraries, data formats and parsing
Technology & EngineeringElectronics and digital sensors
MathematicsData analysis, averages and graphs
Biology / GeographyClimate, comfort zones, plant growth conditions
11Think about it

Reflection & conclusion

?1

Where would you place the sensor in a room to get a fair measurement? Why not next to the radiator or window?

?2

Our sensor is ±2 °C accurate. Is that good enough for a weather station? For a hospital incubator?

?3

How could this project help save energy at school?

Conclusion

This project introduced working with digital sensors, libraries, and two-value data streams. By combining the Arduino Uno with Processing you built a real-time climate monitor — the same principle used in smart homes, greenhouses and weather stations around the world.