inital commit working
This commit is contained in:
79
dht11.cpp
Normal file
79
dht11.cpp
Normal file
@ -0,0 +1,79 @@
|
||||
#include "dht11.h"
|
||||
|
||||
Dht11::Dht11(volatile unsigned char *port, volatile unsigned char *inPort, volatile unsigned char *port_ctl, const unsigned char pin): _port(port), _inPort(inPort), _port_ctl(port_ctl), _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(2);
|
||||
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;
|
||||
|
||||
// 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) return 3;
|
||||
|
||||
loopCnt = 0;
|
||||
while(readPin(_inPort, _pin))
|
||||
{
|
||||
_delay_us(10);
|
||||
if (loopCnt++ > LOOP_TIMEOUT_SMALL_COUNT) return 4;
|
||||
}
|
||||
|
||||
if( loopCnt > BIT_COUNT )bits[idx] |= (1 << cnt);
|
||||
if (cnt == 0) // next byte?
|
||||
{
|
||||
cnt = 7; // restart at MSB
|
||||
idx++; // next byte!
|
||||
}
|
||||
else cnt--;
|
||||
}
|
||||
|
||||
// WRITE TO RIGHT VARS
|
||||
// as bits[1] and bits[3] are allways zero they are omitted in formulas.
|
||||
uint8_t sum;
|
||||
if constexpr(DHT22) sum= bits[0] + bits[1] + bits[2] + bits[3];
|
||||
else sum = bits[1] + bits[3];
|
||||
|
||||
if(bits[4] == sum && sum != 0)
|
||||
{
|
||||
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[1];
|
||||
temperature = bits[3]*10;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
else return 5;
|
||||
}
|
Reference in New Issue
Block a user