Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
For Loop Examples in Embedded C: LED Scanner, ADC Average, Soft SPI, CRC-8 and Keypad Scan
Eight worked examples with real output: a Knight-Rider LED scanner, moving average, bit counting and reversal, software SPI, bubble sort, CRC-8, DAC waveform tables and a keypad matrix scan. Study this one of the for loop examples in embedded C closely.
For Loop Examples in Embedded C: What This Page Covers
These for loop examples in embedded C apply Lesson 7.1 to typical firmware jobs: LED animations, filtering ADC samples, bit manipulation, a software SPI byte, sorting, a CRC, waveform tables and a keypad scan. Every program was compiled with GCC and run, and the output you see is real. Hardware registers are simulated by variables carrying the real STM32F407 names. These for loop examples in embedded C build on each other.
| # | Example | Skill |
|---|---|---|
| 1 | Knight-Rider scanner on PD12–PD15 | Counting up and down |
| 2 | Moving average of ADC samples | Window loops |
| 3 | Count and reverse the bits of a byte | Bit loops |
| 4 | Software SPI: shifting out a byte | MSB-first loop |
| 5 | Bubble sort of sensor readings | Nested for |
| 6 | CRC-8 of a message | Loop within a loop |
| 7 | Waveform tables for a 12-bit DAC | Table generation |
| 8 | 4×4 keypad scan | Row/column scanning |
| 9 | Mini exercises | Self-test |
Example 1: A Knight-Rider Scanner on the Four LEDs
Problem: Make one lit LED move from PD12 to PD15 and back. Each pass of the loop writes a single-bit mask to the output data register. The return sweep starts at PD14 and stops at PD13 so that the end LEDs are not lit twice in a row. Among the for loop examples in embedded C this pattern is very common.
1u << pin.Example 2: A Moving Average of ADC Samples
Problem: Smooth noisy 12-bit readings by averaging the last four. The inner loop walks backwards from the current index, and its condition k <= i stops at the start of the data so that no sample before index 0 is read. Keep these for loop examples in embedded C for revision.
The spike of 250 is reduced to an average of 138 and then fades as it leaves the window. For a real-time filter keep a running sum and a circular buffer instead of re-adding the window each time (cost O(1) instead of O(window)).
Example 3: Count and Reverse the Bits of a Byte
Problem: Count the set bits (parity checks, error detection) and reverse the bit order (needed when a peripheral sends LSB first but the protocol expects MSB first). Both loops make exactly 8 passes.
RBIT instruction (reverse bits) available through the CMSIS function __RBIT(), and GCC offers __builtin_popcount(). The loops show the algorithm; use the intrinsics in production code.Example 4: Software SPI: Shifting Out a Byte
Problem: Send a byte over two GPIO pins in SPI mode 0, most significant bit first. The counter runs from 7 down to 0 and is a signed int, so the test bit >= 0 works. On the STM32F407 the lines would be PB13 (SCK) and PB15 (MOSI) written through the BSRR register.
Read the output as a pairs of lines per bit: data first, then the clock rising edge at which the slave samples. The data bits appear as 1, 0, 1, 0, 0, 1, 1, 0, which is 0xA6.
Example 5: Bubble Sort of Sensor Readings
Problem: Sort six readings in ascending order so that the median can be picked. The outer loop counts the passes; the inner loop compares neighbours and shrinks by one each pass because the largest value has bubbled to the end. The swapped flag ends the sort early.
qsort or insertion sort on nearly-sorted data.Example 6: CRC-8 of a Message
Problem: Protect a serial frame with a cyclic redundancy check. The outer loop takes bytes; the inner loop of exactly 8 passes shifts the register bit by bit and XORs the polynomial whenever the top bit falls out. The well-known check value for the ASCII string “123456789” with polynomial 0x07 is 0xF4.
CRC->DR) for bulk data.Example 7: Waveform Tables for a 12-bit DAC
Problem: Fill two lookup tables for the STM32F407’s 12-bit DAC (full scale 4095): a sawtooth ramp and a triangle wave. Timer-triggered DMA can then stream the table to the DAC at a fixed sample rate with zero CPU load.
Computing the table at start-up costs RAM; for a fixed waveform declare it static const so that the table lives in flash. Sine tables are made the same way, using sinf() in the loop on a PC and pasting the result.
Example 8: A 4×4 Keypad Scan with Nested Loops
Problem: A keypad connects 4 row lines (outputs) to 4 column lines (inputs). To find the pressed key, drive one row high at a time and read the columns. The outer loop selects the row, the inner loop tests the 4 column bits, and a lookup table turns the position into a character.
| col 0 | col 1 | col 2 | col 3 | |
|---|---|---|---|---|
| row 0 | 1 | 2 | 3 | A |
| row 1 | 4 | 5 | 6 | B |
| row 2 | 7 | 8 | 9 | C |
| row 3 | * | 0 | # | D |
A real scanner also needs debouncing (Lesson 6.1 edge detection) and a short settling delay after each row change.
Example 9: Mini Exercises
Exercise 1: How many times does for (i = 2; i < 20; i += 4) run?
Exercise 2: What is i after for (i = 0; i < 7; i += 3);?
Exercise 3: Write a loop that clears all 16 bytes of buf in reverse order using a size_t counter.
for (size_t i = 16; i-- > 0; ) buf[i] = 0;Exercise 4: How many comparisons does bubble sort make at most for n = 6?
Exercise 5: How can the knight-rider sweep be written as one loop instead of two?
pos = i < 4 ? i : 6 - i.Exercise 6: Why does the SPI loop use a signed counter?
bit >= 0 must be able to become false when the counter reaches -1.Exercise 7: What is the trip count of the inner CRC loop per message byte?
Key Takeaways from the For Loop Examples in Embedded C
- These for loop examples in embedded C show that the loop variable is often a bit position, a pin number or a table index.
- Nested loops multiply: sorting and scanning both cost the product of their trip counts.
- Down-counting loops need a signed counter or the
i-- > 0form. - Tables built in loops belong in flash when they are constant.
- Check the loop limits against the data actually present (
k <= iin the moving average). - Prefer hardware (CRC unit, DMA,
RBIT) over loops for bulk work.
Ready for the quiz?
Next: predict loop output, find the off-by-one bug and answer the for loop interview questions.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments