|
31 | 31 | #if MICROPY_PY_MACHINE_PULSE
|
32 | 32 |
|
33 | 33 | MP_WEAK mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t timeout_us) {
|
| 34 | + mp_uint_t nchanges = 2; |
34 | 35 | mp_uint_t start = mp_hal_ticks_us();
|
35 |
| - while (mp_hal_pin_read(pin) != pulse_level) { |
36 |
| - if ((mp_uint_t)(mp_hal_ticks_us() - start) >= timeout_us) { |
37 |
| - return (mp_uint_t)-2; |
38 |
| - } |
39 |
| - } |
40 |
| - start = mp_hal_ticks_us(); |
41 |
| - while (mp_hal_pin_read(pin) == pulse_level) { |
42 |
| - if ((mp_uint_t)(mp_hal_ticks_us() - start) >= timeout_us) { |
43 |
| - return (mp_uint_t)-1; |
| 36 | + for (;;) { |
| 37 | + // Sample ticks and pin as close together as possible, and always in the same |
| 38 | + // order each time around the loop. This gives the most accurate measurement. |
| 39 | + mp_uint_t t = mp_hal_ticks_us(); |
| 40 | + int pin_value = mp_hal_pin_read(pin); |
| 41 | + |
| 42 | + if (pin_value == pulse_level) { |
| 43 | + // Pin is at desired value. Flip desired value and see if we are done. |
| 44 | + pulse_level = 1 - pulse_level; |
| 45 | + if (--nchanges == 0) { |
| 46 | + return t - start; |
| 47 | + } |
| 48 | + start = t; |
| 49 | + } else { |
| 50 | + // Pin hasn't changed yet, check for timeout. |
| 51 | + mp_uint_t dt = t - start; |
| 52 | + if (dt >= timeout_us) { |
| 53 | + return -nchanges; |
| 54 | + } |
| 55 | + |
| 56 | + // Allow a port to perform background task processing if needed. |
| 57 | + #ifdef MICROPY_PY_MACHINE_TIME_PULSE_US_HOOK |
| 58 | + MICROPY_PY_MACHINE_TIME_PULSE_US_HOOK(dt); |
| 59 | + #endif |
44 | 60 | }
|
45 | 61 | }
|
46 |
| - return mp_hal_ticks_us() - start; |
47 | 62 | }
|
48 | 63 |
|
49 | 64 | static mp_obj_t machine_time_pulse_us_(size_t n_args, const mp_obj_t *args) {
|
|
0 commit comments