89 lines
2.1 KiB
C++
89 lines
2.1 KiB
C++
#include "dht11.h"
|
|
|
|
Dht11::Dht11(volatile unsigned char * const port, volatile unsigned char * const inPort, volatile unsigned char * const port_ctl, const unsigned char pin): _port(port), _port_ctl(port_ctl), _inPort(inPort), _pin(pin)
|
|
{}
|
|
|
|
uint8_t Dht11::read()
|
|
{
|
|
// BUFFER TO RECEIVE
|
|
uint8_t bits[5];
|
|
uint8_t cnt = 7;
|
|
uint8_t idx = 0;
|
|
|
|
// EMPTY BUFFER
|
|
for (uint8_t i=0; i< 5; i++) bits[i] = 0;
|
|
|
|
// REQUEST SAMPLE
|
|
setDirection(_port_ctl, _pin, true);
|
|
writePin(_port, _pin, false);
|
|
_delay_ms(18);
|
|
writePin(_port, _pin, true);
|
|
setDirection(_port_ctl, _pin, false);
|
|
_delay_us(42);
|
|
|
|
// ACKNOWLEDGE or TIMEOUT
|
|
unsigned int loopCnt = LOOP_TIMEOUT_COUNT;
|
|
while(!readPin(_inPort, _pin)) if (loopCnt-- == 0) return 1;
|
|
|
|
loopCnt = LOOP_TIMEOUT_COUNT;
|
|
while(readPin(_inPort, _pin) ) if (loopCnt-- == 0) return 2;
|
|
|
|
PORTD |= 1 << PD1;
|
|
PORTD &= ~(1 << PD1);
|
|
PORTD |= 1 << PD1;
|
|
PORTD &= ~(1 << PD1);
|
|
|
|
// READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
|
|
for (uint8_t i=0; i<40; i++)
|
|
{
|
|
loopCnt = LOOP_TIMEOUT_COUNT;
|
|
while(!readPin(_inPort, _pin))
|
|
if (loopCnt-- == 0)
|
|
{
|
|
PORTD |= 1 << PD1;
|
|
return 3;
|
|
}
|
|
|
|
loopCnt = 0;
|
|
while(readPin(_inPort, _pin))
|
|
{
|
|
_delay_us(10);
|
|
if (loopCnt++ > LOOP_TIMEOUT_SMALL_COUNT) return 4;
|
|
}
|
|
|
|
if( loopCnt > BIT_COUNT )
|
|
{
|
|
PORTD |= 1 << PD1;
|
|
PORTD &= ~(1 << PD1);
|
|
bits[idx] |= (1 << cnt);
|
|
}
|
|
if (cnt == 0) // next byte?
|
|
{
|
|
cnt = 7; // restart at MSB
|
|
idx++; // next byte!
|
|
}
|
|
else cnt--;
|
|
}
|
|
|
|
uint8_t sum;
|
|
if constexpr(DHT22) sum= bits[0] + bits[1] + bits[2] + bits[3];
|
|
else sum = bits[0] + bits[2];
|
|
|
|
if(bits[4] == sum && sum != 0 || true)
|
|
{
|
|
if constexpr(DHT22)
|
|
{
|
|
humidity = (static_cast<uint16_t>(bits[0]) << 8) + bits[1];
|
|
temperature = (static_cast<uint16_t>((bits[2] & 0b01111111) << 8) + bits[3]);
|
|
if(bits[2] & 0b10000000) temperature=temperature*-1;
|
|
}
|
|
else
|
|
{
|
|
humidity = bits[0]*10;
|
|
temperature = bits[2]*10;
|
|
}
|
|
return 0;
|
|
}
|
|
else return 5;
|
|
}
|