]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Lib/delay.c
Completing CMake variable generation for USB parameters (AVR Support)
[kiibohd-controller.git] / Lib / delay.c
1
2 #include "delay.h"
3 #include "mk20dx128.h"
4
5 // the systick interrupt is supposed to increment this at 1 kHz rate
6 volatile uint32_t systick_millis_count = 0;
7
8 void yield(void) {};
9
10 uint32_t micros(void)
11 {
12         uint32_t count, current, istatus;
13
14         __disable_irq();
15         current = SYST_CVR;
16         count = systick_millis_count;
17         istatus = SCB_ICSR; // bit 26 indicates if systick exception pending
18         __enable_irq();
19         if ((istatus & SCB_ICSR_PENDSTSET) && current > ((F_CPU / 1000) - 50)) count++;
20         current = ((F_CPU / 1000) - 1) - current;
21         return count * 1000 + current / (F_CPU / 1000000);
22 }
23
24 void delay(uint32_t ms)
25 {
26         uint32_t start = micros();
27
28         while (1) {
29                 if ((micros() - start) >= 1000) {
30                         ms--;
31                         if (ms == 0) break;
32                         start += 1000;
33                 }
34                 yield();
35         }
36 }
37