Skip to content

Use micros() instead of cycle counting. #93

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions DHT.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -235,25 +235,30 @@ boolean DHT::read(bool force) {
// in the very latest IDE versions):
// https://github.com./arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_pulse.c
uint32_t DHT::expectPulse(bool level) {
uint32_t count = 0;
// On AVR platforms use direct GPIO port access as it's much faster and better
// for catching pulses that are 10's of microseconds in length:
#ifdef __AVR
uint32_t count = 0;
// On AVR platforms use direct GPIO port access as it's much faster and better
// for catching pulses that are 10's of microseconds in length:
uint8_t portState = level ? _bit : 0;
while ((*portInputRegister(_port) & _bit) == portState) {
if (count++ >= _maxcycles) {
return 0; // Exceeded timeout, fail.
}
}
// Otherwise fall back to using digitalRead (this seems to be necessary on ESP8266
// right now, perhaps bugs in direct port access functions?).
return count;
#else
// Otherwise fall back to using digitalRead (this seems to be necessary on ESP8266
// right now, perhaps bugs in direct port access functions?).
unsigned long start = micros();
unsigned long end = start;
while (digitalRead(_pin) == level) {
if (count++ >= _maxcycles) {
end = micros();
// When micros() wraps, we return failure. That should happen
// infrequently enough that it's not a big deal.
if (end - start >= _maxcycles || start > end) {
return 0; // Exceeded timeout, fail.
}
}
return end - start;
#endif

return count;
}
2 changes: 2 additions & 0 deletions DHT.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ class DHT {
class InterruptLock {
public:
InterruptLock() {
// This is a nop on my esp32 Arduino system. noInterrupts() is defined to
// cli(), which is empty.
noInterrupts();
}
~InterruptLock() {
Expand Down