commit 7fd5611193a02323fb7271aed2b5625572862ee7
parent 0989a42ecf8ddc1c38f40710db46be04932062f3
Author: Martin Kloeckner <mjkloeckner@gmail.com>
Date: Sun, 28 Sep 2025 21:42:09 -0300
add scheduler `update_cnt`
this makes `ISR` increment `update_cnt` every ms, instead of the
previous method of measuring the time difference between the previous
update
this also makes the scheduler update multiple times if the tasks running
takes more than 1 ms (because `update_cnt` increments anyway if the task
is still runnning, due to incrementing on `IRQ`)
Diffstat:
5 files changed, 22 insertions(+), 10 deletions(-)
diff --git a/src/main.c b/src/main.c
@@ -1,4 +1,5 @@
#include <avr/io.h>
+#include <stddef.h>
#include "millis.h"
#include "scheduler.h"
@@ -42,11 +43,11 @@ void io_setup(void) {
int main(void) {
io_setup();
- millis_init();
+ millis_init(&scheduler_inc_update_tick);
scheduler_init(tasks, sizeof(tasks)/sizeof(tasks[0]));
while(1) {
- scheduler_update(millis());
+ scheduler_update();
}
return 0;
diff --git a/src/millis.c b/src/millis.c
@@ -2,21 +2,28 @@
#include <avr/io.h>
#include <avr/interrupt.h>
+#include <stddef.h>
static volatile uint32_t ms = 0;
+void (*callback)(void) = NULL;
ISR(TIMER0_COMPA_vect) {
ms++;
+ if (callback != NULL) {
+ callback();
+ }
}
// normal mode, prescaler 64, max value 249: exactly 1 interrupt per ms
-void millis_init(void) {
+void millis_init(void (*new_callback)(void)) {
cli();
TCCR0A = (1 << WGM01);
TCCR0B = (1 << CS01) | (1 << CS00);
TIMSK0 = (1 << OCIE0A);
OCR0A = 249;
sei();
+
+ callback = new_callback;
}
uint32_t millis(void) {
diff --git a/src/millis.h b/src/millis.h
@@ -7,7 +7,7 @@ extern "C" {
#include <stdint.h>
-void millis_init(void);
+void millis_init(void (*callback)(void));
uint32_t millis(void);
#ifdef __cplusplus
diff --git a/src/scheduler.c b/src/scheduler.c
@@ -5,8 +5,7 @@ extern "C" {
#endif
typedef struct {
- uint32_t t_ms_dt;
- uint8_t task_cnt;
+ uint8_t task_cnt, update_cnt;
task_t *tasks;
} scheduler_t;
@@ -17,13 +16,17 @@ void scheduler_init(task_t *tasks, uint8_t task_count) {
scheduler.task_cnt = task_count;
}
+void scheduler_inc_update_tick(void) {
+ scheduler.update_cnt += (scheduler.update_cnt == 255 ? 0 : 1);
+}
+
// update every 1 ms
-void scheduler_update(uint32_t t_ms) {
- if ((t_ms - scheduler.t_ms_dt) < 1) {
+void scheduler_update(void) {
+ if (scheduler.update_cnt == 0) {
return;
}
- scheduler.t_ms_dt = t_ms;
+ scheduler.update_cnt--;
for (uint8_t i = 0; i < scheduler.task_cnt; ++i) {
if (scheduler.tasks[i].ticks > 1) {
diff --git a/src/scheduler.h b/src/scheduler.h
@@ -15,7 +15,8 @@ typedef struct {
} task_t;
void scheduler_init(task_t *tasks, uint8_t task_count);
-void scheduler_update(uint32_t t_ms);
+void scheduler_update(void);
+void scheduler_inc_update_tick(void);
void scheduler_set_task_period(uint8_t task_id, uint16_t new_period);
#ifdef __cplusplus