28
28
/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH
29
29
* or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds
30
30
* to 3 minutes in length, but must be called at least a few dozen microseconds
31
- * before the start of the pulse. */
31
+ * before the start of the pulse.
32
+ *
33
+ * This function performs better with short pulses in noInterrupt() context
34
+ */
32
35
unsigned long pulseIn (uint8_t pin , uint8_t state , unsigned long timeout )
33
36
{
34
37
// cache the port and bit of the pin in order to speed up the
@@ -38,32 +41,12 @@ unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
38
41
uint8_t port = digitalPinToPort (pin );
39
42
uint8_t stateMask = (state ? bit : 0 );
40
43
unsigned long width = 0 ; // keep initialization out of time critical area
41
-
44
+
42
45
// convert the timeout from microseconds to a number of times through
43
- // the initial loop; it takes 16 clock cycles per iteration.
46
+ // the initial loop; it takes approximately 16 clock cycles per iteration
44
47
unsigned long numloops = 0 ;
45
- unsigned long maxloops = microsecondsToClockCycles (timeout ) / 16 ;
46
-
47
- // wait for any previous pulse to end
48
- while ((* portInputRegister (port ) & bit ) == stateMask )
49
- if (numloops ++ == maxloops )
50
- return 0 ;
51
-
52
- // wait for the pulse to start
53
- while ((* portInputRegister (port ) & bit ) != stateMask )
54
- if (numloops ++ == maxloops )
55
- return 0 ;
56
-
57
- // wait for the pulse to stop
58
- while ((* portInputRegister (port ) & bit ) == stateMask ) {
59
- if (numloops ++ == maxloops )
60
- return 0 ;
61
- width ++ ;
62
- }
48
+ unsigned long maxloops = microsecondsToClockCycles (timeout )/16 ;
63
49
64
- // convert the reading to microseconds. The loop has been determined
65
- // to be 20 clock cycles long and have about 16 clocks between the edge
66
- // and the start of the loop. There will be some error introduced by
67
- // the interrupt handlers.
68
- return clockCyclesToMicroseconds (width * 21 + 16 );
69
- }
50
+ width = countPulseASM (portInputRegister (port ), bit , stateMask , maxloops );
51
+ return clockCyclesToMicroseconds (width * 16 + 16 );
52
+ }
0 commit comments