#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
typedef union
{
float temperature;
uint8_t tBytes[4];
} FLOATUNION_t;
union {
uint8_t t[4];
float computedTemp;
} tData;
typedef union
{
float humidity;
uint8_t hBytes[4];
} FLOATUNION_h;
union {
uint8_t t[4];
float computedHum;
} hData;
void setup() {
Serial.begin(115200);
Serial.println(F("DHT22 example!"));
dht.begin();
}
void loop() {
float sensor_temp = dht.readTemperature();
float sensor_hum = dht.readHumidity();
FLOATUNION_t tFloat;
tFloat.temperature = sensor_temp; // Assign a temperature to the float
FLOATUNION_h hFloat;
hFloat.humidity = sensor_hum; // Assign a humidity to the float
// Check if any reads failed and exit early (to try again).
if (isnan(sensor_temp)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
Serial.print(F("Humidity: "));
Serial.print(sensor_hum);
Serial.print(F("% Temperature: "));
Serial.print(sensor_temp);
Serial.println(F("°C "));
Serial.println("Temperature bytes ");
for (int i=0; i<4; i++)
{
Serial.print(tFloat.tBytes[i], HEX); // Print the hex representation of the float
Serial.println(' ');
}
// recombine bytes to float
for (int i=0; i<4; i++)
{
tData.t[i] = tFloat.tBytes[i];
}
Serial.print(F("Computed temperature: "));
Serial.print(tData.computedTemp);
Serial.println(F("°C "));
// Wait a few seconds between measurements.
delay(5000);
// humidity *********
Serial.println("Humidity bytes ");
for (int i=0; i<4; i++)
{
Serial.print(hFloat.hBytes[i], HEX); // Print the hex representation of the float
Serial.println(' ');
}
// recombine bytes to float
for (int i=0; i<4; i++)
{
hData.t[i] = hFloat.hBytes[i];
}
Serial.print(F("Computed humidity: "));
Serial.print(hData.computedHum);
Serial.println(F("% "));
// Wait a few seconds between measurements.
delay(5000);
}