Skip to content

Commit 58ba741

Browse files
authored
Merge pull request #765 from jerryneedell/jerryn_tick
modify tick_delay to handle SysTick->VAL rollover
2 parents 77092f2 + bef05ff commit 58ba741

File tree

2 files changed

+10
-13
lines changed

2 files changed

+10
-13
lines changed

ports/atmel-samd/common-hal/pulseio/PulseIn.c

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -283,12 +283,9 @@ void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self,
283283
if (trigger_duration > 0) {
284284
gpio_set_pin_pull_mode(self->pin, GPIO_PULL_OFF);
285285
gpio_set_pin_direction(self->pin, GPIO_DIRECTION_OUT);
286-
287-
common_hal_mcu_disable_interrupts();
288286
gpio_set_pin_level(self->pin, !self->idle_state);
289-
common_hal_mcu_delay_us(trigger_duration);
287+
common_hal_mcu_delay_us((uint32_t)trigger_duration);
290288
gpio_set_pin_level(self->pin, self->idle_state);
291-
common_hal_mcu_enable_interrupts();
292289
}
293290

294291
// Reconfigure the pin and make sure its set to detect the first edge.

ports/atmel-samd/tick.c

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,21 +52,21 @@ void SysTick_Handler(void) {
5252

5353
void tick_init() {
5454
uint32_t ticks_per_ms = common_hal_mcu_processor_get_frequency() / 1000;
55-
SysTick_Config(ticks_per_ms);
55+
SysTick_Config(ticks_per_ms-1);
5656
NVIC_EnableIRQ(SysTick_IRQn);
5757
}
5858

5959
void tick_delay(uint32_t us) {
6060
uint32_t ticks_per_us = common_hal_mcu_processor_get_frequency() / 1000 / 1000;
61-
uint32_t us_between_ticks = SysTick->VAL / ticks_per_us;
62-
uint64_t start_ms = ticks_ms;
63-
while (us > 1000) {
64-
while (ticks_ms == start_ms) {}
65-
us -= us_between_ticks;
66-
start_ms = ticks_ms;
67-
us_between_ticks = 1000;
61+
uint32_t us_until_next_tick = SysTick->VAL / ticks_per_us;
62+
uint32_t start_tick;
63+
while (us >= us_until_next_tick) {
64+
start_tick=SysTick->VAL; // wait for SysTick->VAL to RESET
65+
while (SysTick->VAL < start_tick) {}
66+
us -= us_until_next_tick;
67+
us_until_next_tick = 1000;
6868
}
69-
while (SysTick->VAL > ((us_between_ticks - us) * ticks_per_us)) {}
69+
while (SysTick->VAL > ((us_until_next_tick - us) * ticks_per_us)) {}
7070
}
7171

7272
// us counts down!

0 commit comments

Comments
 (0)