PrajnaEdge
An interactive engineering platform where complex concepts become experiences—through visual explorations, simulations, and practical understanding.
PrajnaEdge Navigation Tree
Embedded Systems Tree
On the Horizon
PravahaPath
Something new is taking shape.

Articles & Write-ups

Exploring how systems evolve from hardware to integration.

Sort:

Edge AI Demonstrations

Deploying neural networks and intelligent decision loops on raw silicon targets.

Sort:
Bare Metal

Teaching Time to an Infinite Loop

How to schedule multiple tasks at predictable intervals without an operating system.

Bare MetalSuperloopTimerInterruptsCooperative Scheduler

1. The Concept of Time

At the end of our previous journey, we watched the processor enter an infinite loop. It was a structural guarantee that the CPU would never run out of instructions. But we also hit a wall: the loop knows how to repeat, but it does not understand time. Consider this basic superloop:

while (1) { ReadSensor(); UpdateControl(); RefreshDisplay(); SendStatus(); }

What if the application dictates that ReadSensor() must execute every 10 milliseconds, UpdateControl() every 20 milliseconds, RefreshDisplay() every 100 milliseconds, and SendStatus() every 1000 milliseconds? Neither the CPU instruction pipeline nor the while loop has any concept of a millisecond. If we run this loop as-is, it executes as fast as the system clock allows. The tasks run at arbitrary, hardware-dependent rates. To build a reliable machine, we must teach our software how to measure intervals.

2. The Tempting Solution: Delay

The most common initial attempt to solve timing is the blocking delay. We insert waiting routines directly into the execution path:

while (1) { ReadSensor(); DelayMs(100); // Wait 100 ms UpdateDisplay(); }

During DelayMs(100), the CPU core spins in a dummy loop, burning power while executing instructions that do nothing. The entire foreground execution path is blocked. If we try to schedule multiple tasks with different intervals using this approach, the timing collapses:

while (1) { ReadSensor(); DelayMs(10); UpdateControl(); DelayMs(20); RefreshDisplay(); DelayMs(100); SendStatus(); DelayMs(1000); }

These delays do not run independently; they accumulate. The actual period between executions of ReadSensor() is not 10 milliseconds. It is the sum of all task execution times plus the sum of all delays—a cycle time exceeding 1130 milliseconds. Blocking delays only mean 'do not progress past this line of code for N milliseconds.' They are not a scheduling architecture.

ACCUMULATED LATENCY OF BLOCKING DELAYS
Time → ReadSensor() T_exec: 2ms DelayMs(10) UpdateControl() T_exec: 4ms DelayMs(20) RefreshDisplay() T_exec: 12ms DelayMs(100) Actual Loop Cycle Time = 148 ms (Expected 100 ms max)
Delays stack sequentially, so the actual period of any task is stretched by all other operations and delay cycles in the loop.

Blocking delays are appropriate only in limited situations: initializing a display chip during boot, letting voltage lines settle, or debugging simple single-task setups. In real runtime environments, they paralyze foreground logic.

3. The Machine Already Has a Clock

Instead of wasting CPU instruction cycles, we can delegate timekeeping to hardware peripherals. Microcontrollers contain hardware timers. These modules are independent binary counters on the silicon that increment based on a dedicated clock signal, running in parallel with the CPU's execution pipelines.

HARDWARE TIMER PERIPHERAL PIPELINE
CLOCK SOURCE e.g. 16 MHz PRESCALER Divide by N (e.g. 16) TIMER COUNTER Increments (CNT) COMPARE REG Target Value (ARR) Continuous hardware comparison: CNT == ARR? INTERRUPT EVENT Triggers ISR
The hardware timer counts clock pulses independently of the CPU core instruction pipeline.

Consider a simple configuration: an input clock of 1 MHz. If we set the timer's prescaler to 1, the counter increments every 1 microsecond. If we set a target compare register value of 1000, a comparator on the silicon triggers a compare match event exactly every 1000 counts—representing a precise 1 millisecond interval.

4. The Hidden Connection: The Architecture of Time

We have encountered this hardware before. In The Architecture of Time, we explored what happens when timers themselves reach their limits — overflow, wraparound, and the edge cases hidden inside measuring time. Here, we are looking at the same hardware from another direction. Not how time can fail, but how time can organize software.

5. Creating a System Tick

By configuring a hardware timer to assert an interrupt line at a periodic rate, we establish a software timebase—a system tick. Every tick, the CPU jumps to the interrupt vector to increment a global counter:

volatile uint32_t system_ticks = 0; void Timer_IRQHandler(void) { system_ticks++; }

If the timer is configured to interrupt every 1 millisecond, then system_ticks increments 1000 times a second. An elapsed tick count of 10 corresponds to 10 milliseconds, and 1000 ticks represents 1 second. This global tick is the heartbeat of the system.

6. Avoid ISR Bloat

Since we have a periodic timer interrupt, it is tempting to run our task logic directly inside the ISR:

void Timer_IRQHandler(void) { ReadSensor(); UpdateControl(); RefreshDisplay(); SendStatus(); }

This is a dangerous anti-pattern. While this code runs at precise intervals, it executes inside the high-priority interrupt context. If the display refresh or status transmission takes longer than 1 millisecond, the ISR will not complete before the next timer interrupt triggers. The system crashes or locks up. Foreground execution is starved, other interrupts are blocked, and real-time promises fail.

7. Flags: Turning Time Into Events

To keep the interrupt context lean, we use flags. The background ISR handles the timing calculations, sets boolean indicators when tasks become due, and yields control immediately. The heavy application execution is performed inside the foreground superloop:

volatile bool task_10ms = false; volatile bool task_100ms = false; volatile bool task_1000ms = false; void Timer_IRQHandler(void) { static uint32_t tick = 0; tick++; if ((tick % 10) == 0) task_10ms = true; if ((tick % 100) == 0) task_100ms = true; if ((tick % 1000) == 0) task_1000ms = true; } int main(void) { Initialize(); while (1) { if (task_10ms) { task_10ms = false; ReadSensor(); } if (task_100ms) { task_100ms = false; RefreshDisplay(); } if (task_1000ms) { task_1000ms = false; SendStatus(); } } }
TIMER TICK & FLAG-BASED SUPERLOOP DISPATCH
HARDWARE TIMER (1 ms Period) Interrupt Request (IRQ) Timer_IRQHandler() [Background] Increments tick, sets flags if due e.g. if (tick % 10 == 0) task_10ms = true task_10ms = true task_100ms = true task_1000ms = true FOREGROUND SUPERLOOP (Checks flags, runs tasks, resets flags)
The background ISR triggers at a precise frequency to raise flags, which the foreground superloop checks and processes cooperatively.

8. Why Flags Are Not Time

This split design keeps interrupts fast. However, it introduces a new variable: scheduling latency. A flag setting does not mean the task executes exactly at the due timestamp; it means the task is released for execution. The actual run begins when the foreground loop reaches the task's check block.

SCHEDULING LATENCY EFFECT
Time → Foreground busy: RunHeavyMath() Flag set (Due Time) task_10ms = true Scheduling Latency ReadSensor() Actual Execution
The difference between a task's release trigger and its actual execution start is the scheduling latency.

If the superloop is currently busy executing a 25 ms calculation when the 10 ms flag is raised, the task experiences 25 ms of scheduling latency. The execution time of the background tasks limits the timing accuracy of the foreground loop.

9. When a Boolean Flag Loses Information

What happens if the scheduling latency is longer than the period of the task itself? Suppose the foreground loop is blocked for 35 milliseconds. During this block, the background timer interrupt fires three times at 10 ms, 20 ms, and 30 ms.

With a simple boolean flag: task_10ms = true. The flag switches from false to true on the first tick, and remains true on the second and third ticks. When the foreground loop finally unblocks and checks the flag, it sees a single true event. Two occurrences have collapsed, causing data loss. If our task is to refresh a screen, this is acceptable; we simply paint the latest frame. If the task is to sample a sensor, we have lost two critical packets of information.

To resolve this, systems rely on event counters, timestamp registers, ring buffers, or hardware-managed DMA paths to capture data autonomously without depending on loop response times.

10. Timestamp-Based Periodic Execution

An alternative scheduling architecture checks elapsed timestamps directly in the superloop without setting flags in the ISR. Instead of blocking the loop using delays, we check system ticks continuously:

uint32_t last_sensor_time = 0; while (1) { uint32_t now = system_ticks; if ((uint32_t)(now - last_sensor_time) >= 10U) { last_sensor_time = now; ReadSensor(); } // Other non-blocking checks can run here }

Instead of waiting, the CPU evaluates the condition. If 10 milliseconds have not elapsed, it falls through to check other tasks. This transition from blocking waits to non-blocking timestamp comparisons keeps the loop flowing. Furthermore, by utilizing unsigned subtraction (now - last_sensor_time), the comparison remains completely wrap-safe when the 32-bit counter overflows and wraps back to zero.

11. Period Versus Execution Time

Regardless of whether we use flags, timestamps, or operating system schedulers, there is an absolute physical constraint. Suppose a task must run every 10 milliseconds, but the task itself requires 15 milliseconds of CPU execution time. No scheduling technique can resolve this. The task overflows its time budget, causing a scheduling overrun:

THE TIME BUDGET COLLAPSE (OVERRUN)
Time → Required Period: 10 ms Period 2: 10 ms Task execution: 15 ms Missed Deadline / Overrun
If execution time exceeds the required period, the system cannot meet its timing goals, regardless of the scheduler used.

To avoid timing collapses, the total processor utilization—the sum of all task execution times divided by their periods—must remain safely below 100%. If utilization exceeds this boundary, the workload must be reduced, optimized, or distributed across multiple cores.

12. A Simple Cooperative Scheduler

By organizing tasks inside non-blocking time checks, we have constructed a basic Cooperative Scheduler directly on the bare metal:

while (1) { if (TaskDue_10ms()) RunFastTask(); if (TaskDue_100ms()) RunMediumTask(); if (TaskDue_1000ms()) RunSlowTask(); }

Because there is no RTOS kernel managing preemptive context switches, every task runs to completion. This system works because each task cooperates by completing its work quickly and returning control to the superloop. It is simple, highly efficient, and predictable—but it requires discipline to avoid any blocking calls.

13. The Timer Solved 'When', But Not 'What'

We have structured our loop, bringing order and timing to our tasks. The microcontroller now executes routines at predictable frequencies.

But knowing when to run is only half of firmware behavior. A system must also know what to do at that moment. A motor controller running every 10 milliseconds must act differently if it is starting up, spinning at target speed, braking, or indicating a fault. Time tells the system when to reconsider its state. We must now explore how behavior shifts as the machine transitions across conditions.

The Division of Time

The infinite loop gave the machine repetition. The timer gave that repetition structure, dividing time into predictable intervals.

But to make that repetition useful, the machine must also understand its conditions.

A loop without time is a runaway engine. Time gives it a path; state gives it a purpose.
System Tree Node Bare Metal
ABOUT PRAJNAEDGE

Engineering concepts you don't just read — you experience.

PrajnaEdge is an interactive engineering platform where complex concepts become experiences—through visual explorations, simulations, and practical understanding.

WHY PRAJNAEDGE EXISTS

Engineering is often taught as a collection of isolated concepts.

A processor here.
A protocol there.
An operating system somewhere else.

But real systems are built by connecting these layers.

PrajnaEdge exists to make those connections visible.

Each exploration starts with a question, builds an intuition, and gradually reveals the system underneath through visualizations, simulations, practical scenarios, and connections between concepts.

HOW PRAJNAEDGE WORKS

PrajnaEdge is designed around exploration rather than passive reading.

Concepts are introduced progressively, visualized when they benefit from seeing them, and brought to life through interactive EdgeCases and simulations where appropriate.

The goal is not simply to explain what a system does, but to help the learner understand why it works the way it does.

CREATOR PROFILE

Devaharsha Meesarapu

Embedded Systems • Firmware • Edge AI

I am the engineer behind the design, development, and content of PrajnaEdge. I build low-level systems where code directly controls hardware, bridging the gap between register-level silicon behavior and intelligent edge decision loops.

View Resume →

ABOUT ME

I am an Embedded Firmware Engineer focused on developing software for resource-constrained systems. My experience spans bare-metal firmware, device drivers, microcontroller peripherals, and communication protocols, working across the boundary between hardware and software.

My work has involved microcontroller-based systems, real-time behaviour, hardware interfaces, and communication technologies such as CAN, CAN FD, UART, SPI, and I²C. I am particularly interested in understanding systems from the lowest level upward—from registers and peripherals to intelligent edge systems.

ENGINEERING PHILOSOPHY

Engineering is not just about writing code; it is about managing constraints, timings, and physical hardware characteristics. True mastery of complex systems comes from understanding the interactions across different layers of the stack.

This conviction is why I built PrajnaEdge—to bridge the gap between conceptual theory and direct, register-level physical reality.

CONNECT

LinkedIn → GitHub →

Interactive Career Journey

Let's Connect
Interested in embedded systems, AI, or building something meaningful? I'd love to hear from you.
Open to collaborations, research, and interesting engineering conversations.
Help Improve PrajnaEdge
Found something to improve? I'd love to hear your thoughts.

Bare Metal

Software that runs directly on hardware without an operating system.

Applications
Operating Systems
YOU ARE HERE
Bare Metal
Processor
Hardware

"Every embedded application begins long before main()."

Operating Systems

An Operating System manages hardware and software resources so complex applications can work efficiently.

Applications
YOU ARE HERE
Operating Systems
Bare Metal
Processor
Hardware

"When one loop is no longer enough to carry the burden."

Support PrajnaEdge

PrajnaEdge is an independent education platform built to make knowledge freely accessible.

If you find PrajnaEdge useful, you can support its continued development.

Your support helps fund the time, tools, infrastructure, and experimentation that go into building and maintaining PrajnaEdge.

Select Region
Select Amount
Select an amount to support PrajnaEdge.