24
24
* before the start of the pulse.
25
25
*
26
26
* ATTENTION:
27
- * This function performs better with short pulses in noInterrupt() context
27
+ * This function relies on micros() so cannot be used in noInterrupt() context
28
28
*/
29
-
30
29
uint32_t pulseIn ( uint32_t pin, uint32_t state, uint32_t timeout )
31
30
{
31
+ // Cache the port and bit of the pin in order to speed up the
32
+ // pulse width measuring loop and achieve finer resolution.
33
+ // Calling digitalRead() instead yields much coarser resolution.
34
+ uint32_t bit = digitalPinToBitMask (pin);
35
+ __IO uint32_t *portIn = portInputRegister (digitalPinToPort (pin));
36
+ uint32_t stateMask = (state ? bit : 0 );
32
37
uint32_t startMicros = micros ();
33
- uint32_t start_level = (uint32_t )digitalRead (pin);
34
- uint32_t current_level = start_level;
35
38
36
- while (current_level == start_level) {
37
- if (micros () - startMicros > timeout) {
39
+ // wait for any previous pulse to end
40
+ while ((*portIn & bit) == stateMask) {
41
+ if (micros () - startMicros > timeout)
38
42
return 0 ;
39
- }
40
- current_level = (uint32_t )digitalRead (pin);
41
43
}
42
44
43
- while (current_level != state) {
44
- if (micros () - startMicros > timeout) {
45
+ // wait for the pulse to start
46
+ while ((*portIn & bit) != stateMask) {
47
+ if (micros () - startMicros > timeout)
45
48
return 0 ;
46
- }
47
- current_level = (uint32_t )digitalRead (pin);
48
49
}
49
50
50
- // lets start measuring the pulse time now
51
- startMicros = micros ();
52
-
53
- while (current_level == state) {
54
- if (micros () - startMicros > timeout) {
51
+ uint32_t start = micros ();
52
+ // wait for the pulse to stop
53
+ while ((*portIn & bit) == stateMask) {
54
+ if (micros () - startMicros > timeout)
55
55
return 0 ;
56
- }
57
- current_level = (uint32_t )digitalRead (pin);
58
56
}
59
-
60
- return (micros () - startMicros);
57
+ return (micros () - start);
61
58
}
62
59
63
60
/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH
@@ -66,9 +63,9 @@ uint32_t pulseIn( uint32_t pin, uint32_t state, uint32_t timeout )
66
63
* before the start of the pulse.
67
64
*
68
65
* ATTENTION:
69
- * this function relies on micros() so cannot be used in noInterrupt() context
66
+ * This function relies on micros() so cannot be used in noInterrupt() context
70
67
*/
71
- uint32_t pulseInLong (uint8_t pin, uint8_t state, unsigned long timeout)
68
+ uint32_t pulseInLong (uint32_t pin, uint32_t state, uint32_t timeout)
72
69
{
73
70
return pulseIn (pin, state, timeout);
74
71
}
0 commit comments