Skip to content

Commit ef21ade

Browse files
committed
extmod/machine_pulse: Optimise time_pulse_us for code size.
This implementation is based on the esp8266 custom implementation, and further optimised for size and accuracy. Testing on PYBD_SF2 and RPI_PICO2_W shows that it is at least as good as the original implementation in performance. Signed-off-by: Damien George <[email protected]>
1 parent 5676b45 commit ef21ade

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

extmod/machine_pulse.c

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,34 @@
3131
#if MICROPY_PY_MACHINE_PULSE
3232

3333
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;
3435
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
4460
}
4561
}
46-
return mp_hal_ticks_us() - start;
4762
}
4863

4964
static mp_obj_t machine_time_pulse_us_(size_t n_args, const mp_obj_t *args) {

0 commit comments

Comments
 (0)