Summary - Embedded C
- C course
- Expert
- Lesson 42/47
- 5 min
Combine MMIO, interrupts and bit manipulation to write an LED blink app.
Summary - LED blink app
In this lesson you'll combine MMIO, interrupts and bit manipulation to write an LED blink app. The program toggles a fake GPIO register in a loop, printing the LED state each step.
The register is volatile (MMIO). Inside the loop, ^= does the bit toggle (bit manipulation). Each iteration prints the state; this is like monitoring interrupt activity. Three iterations: LED turns on, then off, then on again. This exercise combines the core patterns of embedded C in one program.
Practice Write an LED blink program
Define static volatile unsigned int gpio = 0; (fake GPIO register). In int main(void) write for (int i = 0; i < 3; i++). Inside the loop toggle the LED with gpio ^= (1 << 0); and print the state with printf("LED: %d\n", gpio & 1).
Starter code
#include <stdio.h>
// sahte GPIO yazmacı tanımla (volatile)
// üç adımlı döngü yaz
// her adımda toggle yap ve yazdırSample solution
#include <stdio.h>
static volatile unsigned int gpio = 0;
int main(void) {
for (int i = 0; i < 3; i++) {
gpio ^= (1 << 0);
printf("LED: %d\n", gpio & 1);
}
return 0;
}Expected output
LED: 1 LED: 0 LED: 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which operation is used for LED toggle?
- |=
- ^= Correct answer
- &=
- =
Explanation: ^= toggles the bit; it fits LED toggle.
2 Complete the toggle operation
gpio ^= (1 << ____); /* LED'i değiştir */
gpio ^= (1 << 0); /* LED'i değiştir */
Explanation: (1 << 0) toggles bit 0; the LED flips.
3 Match embedded concept to role
| Term | Meaning |
|---|---|
MMIO |
Hardware access |
volatile |
Prevent optimization |
Toggle |
Flip with ^= |
Loop |
Keep running |