#include <TinyDebug.h>
#define DHT_PIN PB4
#define READ_PIN PB3
uint16_t temperature, humidity;
void setup() {
// put your setup code here, to run once:
Debug.begin();
DDRB |= _BV(READ_PIN); // Set READ_PIN as output
}
void read_dht() {
uint32_t startTime = millis();
uint16_t data;
DDRB |= _BV(DHT_PIN); // Set DHT_PIN as output
PORTB |= _BV(DHT_PIN); // set DHT_PIN HIGH
delayMicroseconds(2);
PORTB &= ~(_BV(DHT_PIN)); // Set DHT_PIN LOW
delayMicroseconds(1000);
DDRB &= ~(_BV(DHT_PIN)); // Set DHT_PIN as input
for (int8_t i = -3; i < 2 * 40; i++) {
uint8_t age;
startTime = micros();
do {
age = (uint32_t)(micros() - startTime);
PORTB |= _BV(READ_PIN); // set DHT_PIN HIGH
PORTB &= ~(_BV(READ_PIN)); // Set DHT_PIN LOW
if (age > 90) {
Debug.print("Timeout error\n");
return;
}
} while (((PINB & _BV(DHT_PIN)) >> DHT_PIN) == (i & 1));
if (i >= 0 && (i & 1)) {
data <<= 1;
// Debug.print(age);
if (age > 30) {
data |= 1;
}
}
if (i == 31) {
humidity = data;
} else if (i == 63) {
temperature = data;
}
}
if ((uint8_t)(((uint8_t)humidity) + (humidity >> 8) + ((uint8_t)temperature) + (temperature >> 8)) != (uint8_t)data ) {
Debug.print("Checksum error\n");
return;
}
}
void loop() {
// put your main code here, to run repeatedly:
read_dht();
int16_t temp = (int16_t)temperature;
Debug.print("Temperature: ");
Debug.println((float)(temperature & 0x8000 ? -1 : 1) * (temperature & 0x7FFF) * 0.1);
Debug.print("Humidity: ");
Debug.println((float)(humidity * 0.1));
exit(0);
}