@@ -26,13 +26,20 @@ extern "C" {
26
26
27
27
extern uint32_t xthal_get_ccount ();
28
28
29
- #define WAIT_FOR_PIN_STATE (state ) \
30
- while (digitalRead(pin) != (state)) { \
31
- if (xthal_get_ccount () - start_cycle_count > timeout_cycles) { \
32
- return 0 ; \
33
- } \
34
- optimistic_yield (1000 ); \
29
+ namespace {
30
+ inline __attribute__ ((always_inline)) bool waitForPinState(
31
+ const uint8_t pin, const uint8_t state,
32
+ const uint32_t timeout_cycles, const uint32_t start_cycle_count)
33
+ {
34
+ while (digitalRead (pin) != state) {
35
+ if (xthal_get_ccount () - start_cycle_count > timeout_cycles) {
36
+ return false ;
37
+ }
38
+ optimistic_yield (1000 );
39
+ }
40
+ return true ;
35
41
}
42
+ }
36
43
37
44
// max timeout is 27 seconds at 160MHz clock and 54 seconds at 80MHz clock
38
45
unsigned long pulseIn (uint8_t pin, uint8_t state, unsigned long timeout)
@@ -43,10 +50,16 @@ unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
43
50
}
44
51
const uint32_t timeout_cycles = microsecondsToClockCycles (timeout);
45
52
const uint32_t start_cycle_count = xthal_get_ccount ();
46
- WAIT_FOR_PIN_STATE (!state);
47
- WAIT_FOR_PIN_STATE (state);
53
+ if (!waitForPinState (pin, !state, timeout_cycles, start_cycle_count)) {
54
+ return 0 ;
55
+ }
56
+ if (!waitForPinState (pin, state, timeout_cycles, start_cycle_count)) {
57
+ return 0 ;
58
+ }
48
59
const uint32_t pulse_start_cycle_count = xthal_get_ccount ();
49
- WAIT_FOR_PIN_STATE (!state);
60
+ if (!waitForPinState (pin, !state, timeout_cycles, start_cycle_count)) {
61
+ return 0 ;
62
+ }
50
63
return clockCyclesToMicroseconds (xthal_get_ccount () - pulse_start_cycle_count);
51
64
}
52
65
0 commit comments