Skip to content

Commit

Permalink
add yield functionality, make delays play nice with USB tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
joeycastillo committed Jul 12, 2024
1 parent 62df07a commit e7a2258
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
7 changes: 7 additions & 0 deletions common/app.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
10 changes: 8 additions & 2 deletions common/delay.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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) {
Expand Down

0 comments on commit e7a2258

Please sign in to comment.