Write a superloop with a millisecond tick and task flags
Run periodic work from a SysTick-driven superloop by setting task flags in the tick ISR and clearing them in main, on any Cortex-M with CMSIS.
This is how you get periodic work out of a bare-metal while (1) without an RTOS and without busy-waiting on a timer. The SysTick handler runs every millisecond and does almost nothing: it bumps a counter and raises a flag for each task whose period has elapsed. The main loop sees the flag, clears it and runs the task body at thread level, where it can take as long as it likes.
#include <stdint.h>
#include "stm32f4xx.h"
static volatile uint32_t ms_ticks;
static volatile uint8_t run_led, run_sensor;
void SysTick_Handler(void)
{
ms_ticks++;
if (ms_ticks % 500u == 0u) run_led = 1u;
if (ms_ticks % 20u == 0u) run_sensor = 1u;
}
int main(void)
{
SysTick_Config(SystemCoreClock / 1000u); // 1 ms tick
for (;;) {
if (run_led) { run_led = 0u; led_toggle(); }
if (run_sensor) { run_sensor = 0u; sensor_poll(); }
}
}SysTick_Config() from CMSIS loads the reload register and enables the interrupt, so the tick period is SystemCoreClock / 1000 core cycles. The flags are single bytes written by the ISR and cleared by the loop, which is safe on a single core because a one-byte store cannot tear. If a task overruns its period the flag is simply set again, so a missed deadline collapses into one late run instead of a queue of them. That is the cost of this pattern: nothing tells you a deadline was missed. Count it yourself, or move to a scheduler once a second task needs to preempt the first. The sketch assumes a Cortex-M part such as the STM32F4 and CMSIS-Core 5.