From 1e8fc15a41c4145fe7aca47caf4ddad95f4ada74 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Tue, 11 Apr 2017 16:55:42 -0700 Subject: [PATCH] atmel-samd: Fix PulseIn duration math to handle case when current us time is after the last one but more than a ms has passed. --- atmel-samd/common-hal/pulseio/PulseIn.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/atmel-samd/common-hal/pulseio/PulseIn.c b/atmel-samd/common-hal/pulseio/PulseIn.c index 69eff2a0bf..de40ff0364 100644 --- a/atmel-samd/common-hal/pulseio/PulseIn.c +++ b/atmel-samd/common-hal/pulseio/PulseIn.c @@ -87,12 +87,14 @@ static void pulsein_callback(void) { } else { uint32_t ms_diff = current_ms - last_ms[self->channel]; uint16_t us_diff = current_us - last_us[self->channel]; - if (last_us[self->channel] > current_us) { - us_diff = 1000 + current_us - last_us[self->channel]; - } uint32_t total_diff = us_diff; - if (ms_diff > 1) { - total_diff += (ms_diff - 1) * 1000; + if (last_us[self->channel] > current_us) { + total_diff = 1000 + current_us - last_us[self->channel]; + if (ms_diff > 1) { + total_diff += (ms_diff - 1) * 1000; + } + } else { + total_diff += ms_diff * 1000; } uint16_t duration = 0xffff; if (total_diff < duration) {