Little Bird Curriculum / code littlebird.com.au
vce_u1_04_read_dht22.ino Arduino (C/C++) 30 lines · 2 views ✦ Open in English IDE Raw Download Embed view

Read a DHT22 and print temperature and humidity in a form the serial plotter can graph.

From the unit VCE Systems Engineering Unit 1 — Electrotechnological systems design · activity PRP 4: Temperature and humidity, plotted over time
// PRP 4 — temperature and humidity, plotted over time.
// Requires the DHT sensor library.
//
// The DHT22 needs at least 2 seconds between reads. Sampling faster
// returns stale values or nan — it is the most common cause of both.

#include <DHT.h>

const int DHT_PIN = 2;
DHT dht(DHT_PIN, DHT22);

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

void loop() {
  float humidity = dht.readHumidity();
  float tempC = dht.readTemperature();

  if (isnan(humidity) || isnan(tempC)) {
    Serial.println("read failed");   // check wiring, and check you waited 2s
  } else {
    Serial.print(tempC);
    Serial.print(" ");
    Serial.println(humidity);       // two values, space separated, for the plotter
  }

  delay(2000);                       // minimum sampling interval for this sensor
}

Embed this snippet

As an iframe:

Or drop it inline with a script tag (injects the highlighted block where included):

Shared from Little Bird Electronics curriculum.

Copied to clipboard