@@ -27,27 +27,25 @@ extern unsigned long countPulseASM(const volatile uint32_t *port, uint32_t bit,
27
27
* or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds
28
28
* to 3 minutes in length, but must be called at least a few dozen microseconds
29
29
* before the start of the pulse. */
30
- uint32_t pulseIn (uint32_t pin , uint32_t state , uint32_t timeout )
30
+ uint32_t pulseIn (uint32_t ulPin , uint32_t state , uint32_t timeout )
31
31
{
32
32
// cache the port and bit of the pin in order to speed up the
33
33
// pulse width measuring loop and achieve finer resolution. calling
34
34
// digitalRead() instead yields much coarser resolution.
35
35
// PinDescription p = g_APinDescription[pin];
36
- uint32_t bit = 1 << pin ; //p. ulPin;
36
+ uint32_t bit = 1 << digitalPinToPin ( ulPin ) ;
37
37
uint32_t stateMask = state ? bit : 0 ;
38
38
39
39
// convert the timeout from microseconds to a number of times through
40
- // the initial loop; it takes (roughly) 13 clock cycles per iteration.
41
- uint32_t maxloops = microsecondsToClockCycles (timeout ) / 13 ;
42
-
43
- uint32_t width = countPulseASM (& (NRF_GPIO -> IN ), bit , stateMask , maxloops );
44
-
45
- // convert the reading to microseconds. The loop has been determined
46
- // to be 13 clock cycles long and have about 16 clocks between the edge
47
- // and the start of the loop. There will be some error introduced by
48
- // the interrupt handlers.
49
- if (width )
50
- return clockCyclesToMicroseconds (width * 13 + 16 );
51
- else
52
- return 0 ;
40
+ // the initial loop; it takes (roughly) 10 clock cycles per iteration.
41
+ uint32_t maxloops = microsecondsToClockCycles (timeout ) / 10 ;
42
+
43
+ // count low-level loops during the pulse (or until maxLoops)
44
+ // a zero loopCount means that a complete pulse was not detected within the timeout
45
+ uint32_t loopCount = countPulseASM (& (NRF_GPIO -> IN ), bit , stateMask , maxloops );
46
+
47
+ // convert the reading to (approximate) microseconds. The loop time as measured with an
48
+ // oscilloscope is 10 cycles on a BBC micro:bit 1.3 (nRF51822). There is error because the
49
+ // time is quantized to an integral number of loops and because interrupt may steal cycles.
50
+ return clockCyclesToMicroseconds (10 * loopCount );
53
51
}
0 commit comments