Hardware timing
- C course
- Expert
- Lesson 41/47
- 5 min
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.
Practice 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).
Starter code
#include <stdio.h>
// volatile sayaç tanımla
// for döngüsüyle 100 birim bekle
// sayacı yazdırSample 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;
}Expected output
Gecikme: 100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match timing method
| Term | Meaning |
|---|---|
Busy-wait |
For loop |
Timer |
Hardware counter |
Interrupt |
After set period |
Sleep mode |
Power saving |
2 Why must the counter be volatile in busy-wait?
- So the compiler does not delete the loop Correct answer
- For thread safety
- For memory savings
- For speed
Explanation: Without volatile the compiler can optimize the loop away.
3 Complete the delay loop limit
for (int i = 0; i < ____; i++) { delay_counter++; }
for (int i = 0; i < 100; i++) { delay_counter++; }
Explanation: 100 iterations give 100 units of delay.