From e7a22580ed693e4b409a181257cbed6ea7ce7342 Mon Sep 17 00:00:00 2001 From: joeycastillo Date: Fri, 12 Jul 2024 18:13:41 -0400 Subject: [PATCH] add yield functionality, make delays play nice with USB tasks --- common/app.h | 7 +++++++ common/delay.c | 10 ++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/common/app.h b/common/app.h index 5bbc85e..4e01627 100644 --- a/common/app.h +++ b/common/app.h @@ -59,3 +59,10 @@ void app_setup(void); * app_loop method will be called again immediately. */ bool app_loop(void); + +/** @brief OPTIONAL: A function to yield control of the CPU to other tasks. This function is called in the delay + * function to allow other tasks to run while the CPU is busy waiting. By default, this function + * does nothing, but if you are using the USB peripheral, you should implement this function and call + * `tud_task` at minumum, along with any other USB-related tasks you need to run. +*/ +void yield(void); diff --git a/common/delay.c b/common/delay.c index fd56bb2..495fea5 100644 --- a/common/delay.c +++ b/common/delay.c @@ -2,6 +2,12 @@ #include "sam.h" #include "system.h" +static void __empty() { + // Empty +} + +void yield(void) __attribute__ ((weak, alias("__empty"))); + void delay_init(void) { SysTick->LOAD = SysTick_LOAD_RELOAD_Msk; SysTick->CTRL = SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_CLKSOURCE_Msk; @@ -14,14 +20,14 @@ static void _delay_cycles(uint32_t cycles) { while (n--) { SysTick->LOAD = 0xFFFFFF; SysTick->VAL = 0xFFFFFF; - while (!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk)); + while (!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk)) yield(); buf -= 0xFFFFFF; } SysTick->LOAD = buf; SysTick->VAL = buf; - while (!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk)); + while (!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk)) yield(); } static uint32_t _cycles_for_ms(const uint16_t ms) {