Cosa/DHT11 and DHT22 device driver

One of the latest improvements and additions to the Cosa Arduino framework is a major rewrite of the DHT11/DHT22 device driver. The new version is interrupt driven and fully integrated with the Cosa event framework. The traditional procedural variant looks like this (CosaDHT).

DHT11 outdoors(Board::EXT0);
#if !defined(__ARDUINO_TINY__)
DHT22 indoors(Board::EXT1);

void setup()
  // Start trace output stream on the serial port
  trace.begin(&uart, PSTR("CosaDHT: started"));

  // Check amount of free memory and size of instance

  // Start the watchdog for low power sleep

void loop()
  // Sample every 2 seconds

  // Read and print humidity and temperature
#if !defined(__ARDUINO_TINY__)
  trace << PSTR("indoors: ") << indoors << endl;
  trace << PSTR("outdoors: ") << outdoors << endl;

The output operator<< for DHT11/22 will write the sampled humidity and temperature to the output stream (LCD, Serial, etc). The active object/event driven variant uses the Cosa default loop() function (CosaDHTevent).

// Example of DHT22 sub-class and periodic member function;
// on_sample_completed() prints current value to the trace stream.
class DHTevent : public DHT22 {
  DHTevent(Board::ExternalInterruptPin pin) : DHT22(pin) {}
  virtual void on_sample_completed() { trace << *this << endl; }

// The DHT event object
DHTevent dht(Board::EXT1);

void setup()
  // The trace output stream on serial output
  trace.begin(&uart, PSTR("CosaDHTevent: started"));

  // Watchdog will issue timeout events
  Watchdog::begin(16, SLEEP_MODE_IDLE, Watchdog::push_timeout_events);

  // The DHT event object is started with default 2 second period

A program is viewed as a set of active objects communicating by events. In the example above the DHT object will sample the sensor every 2 seconds and call the on_sample_completed() virtual member function (callback), which in this example does the trace.

For more details see:

  1. Github GitHub - mikaelpatel/Cosa: An Object-Oriented Platform for Arduino/AVR
  2. Interface DHT.hh
  3. Example sketch CosaDHT
  4. Example sketch CosaDHTevent
  5. Blog
  6. On-line documentation