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);
#endif

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

  // Check amount of free memory and size of instance
  TRACE(free_memory());
  TRACE(sizeof(DHT));

  // Start the watchdog for low power sleep
  Watchdog::begin();
  RTC::begin();
}

void loop()
{
  // Sample every 2 seconds
  SLEEP(2);

  // Read and print humidity and temperature
#if !defined(__ARDUINO_TINY__)
  indoors.sample();
  trace << PSTR("indoors: ") << indoors << endl;
#endif
  outdoors.sample();
  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 {
public:
  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
  uart.begin(9600);
  trace.begin(&uart, PSTR("CosaDHTevent: started"));

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

  // The DHT event object is started with default 2 second period
  dht.begin();
}

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 https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Driver/DHT.hh
  3. Example sketch CosaDHT https://github.com/mikaelpatel/Cosa/tree/master/examples/Drivers/CosaDHT
  4. Example sketch CosaDHTevent https://github.com/mikaelpatel/Cosa/tree/master/examples/Drivers/CosaDHTevent
  5. Blog http://cosa-arduino.blogspot.se/
  6. On-line documentation http://dl.dropboxusercontent.com/u/993383/Cosa/doc/html/index.html

Cheers!