C
Hardware timing
Learn hardware timing and delay patterns.
Hardware timing
In embedded systems timing is critical. To blink an LED at intervals or read a sensor periodically, you need a delay. The simplest method is a busy-wait loop.
Busy-wait: for (volatile int i = 0; i < 100000; i++);. Here volatile prevents the compiler from optimizing the loop away. This method is simple but inefficient: the processor runs continuously, consuming power. A better method uses a hardware timer and interrupts. The timer generates an interrupt after a set period; the processor can sleep. But for simple tasks, busy-wait suffices.
Timer and interrupt
For more efficient timing, a hardware timer is used. The timer counts based on the processor clock; when it reaches a set value, it generates an interrupt. In the ISR the counter is reset and a flag is set.
The main loop checks the flag: while (1) { if (timer_flag) { timer_flag = 0; ... } }. The processor can enter sleep mode while waiting for the flag; this greatly reduces power consumption. This is critical in battery-powered embedded systems. The timer is a hardware unit independent of embedded C; software configures it through registers. MMIO and bit manipulation come together here.
Exercise Write a delay loop
Define volatile int delay_counter = 0;. In int main(void) wait 100 units with for (int i = 0; i < 100; i++) { delay_counter++; }. Print the counter with printf("Gecikme: %d\n", delay_counter).
Show example solution
#include <stdio.h>
int main(void) {
volatile int delay_counter = 0;
for (int i = 0; i < 100; i++) {
delay_counter++;
}
printf("Gecikme: %d\n", delay_counter);
return 0;
}
Test yourself
-
Match timing method
- Busy-wait
- For loop
- Timer
- Hardware counter
- Interrupt
- After set period
- Sleep mode
- Power saving
-
Why must the counter be volatile in busy-wait?
- So the compiler does not delete the loop
- For thread safety
- For memory savings
- For speed
Show answer
So the compiler does not delete the loop — Without volatile the compiler can optimize the loop away.
-
Complete the delay loop limit
for (int i = 0; i < ____; i++) { delay_counter++; }
Show answer
for (int i = 0; i < 100; i++) { delay_counter++; }
Next lesson: Summary - Embedded C