MODULE 5 · LESSON 5.3 · EXAMPLES
Bit Manipulation Examples: Registers, LEDs, Button Edges, Alternate Functions and Bitmaps
Eight worked examples with real output: single-bit helpers, before/after register diagrams, GPIOD LED setup, BSRR patterns, edge detection, USART2 pin alternate functions, event flags and a bitmap allocator. Study this one of the bit manipulation examples before the next.
Real output
Compiled and run
Bit Manipulation Examples: What This Page Covers
These bit manipulation examples apply the five idioms of Lesson 5.3 to realistic problems. The register examples use ordinary variables as stand-ins for the STM32F407 registers, with their real names, bit positions and reset values, so each program compiles and runs on a PC and the very same expressions work on the board. These bit manipulation examples build on each other.
| # | Example | Skill |
|---|
| 1 | The four single-bit helpers and a table of results | Set, clear, toggle, read |
| 2 | Before/after register pictures | Visualising changes |
| 3 | Four LEDs: configure PD12–PD15 as outputs | Multi-bit fields, loops |
| 4 | Blinking patterns with ODR and BSRR | Output control |
| 5 | Reading a button and detecting edges | Read, edge masks |
| 6 | Alternate function setup for USART2 on PA2/PA3 | 4-bit fields in AFR |
| 7 | An event-flag word shared by application tasks | Flags and masks |
| 8 | A bitmap allocator for 64 buffers | Bit arrays |
| 9 | Mini exercises | Self-test |
Example 1: The Four Single-Bit Helpers
Problem: Write small functions for the four single-bit operations and apply them to 0x00F0 at four positions, including bit 31 where a signed shift would fail. Of all the bit manipulation examples this is the most common in drivers.
bit_helpers.c
#include <stdio.h>
#include <stdint.h>
static uint32_t set_bit(uint32_t r, unsigned n) { return r | (1u << n); }
static uint32_t clear_bit(uint32_t r, unsigned n) { return r & ~(1u << n); }
static uint32_t toggle_bit(uint32_t r, unsigned n) { return r ^ (1u << n); }
static unsigned read_bit(uint32_t r, unsigned n) { return (r >> n) & 1u; }
int main(void)
{
uint32_t r = 0x00F0;
unsigned tests[] = { 0, 4, 8, 31 };
printf(“start r = 0x%08X\n\n”, (unsigned)r);
printf(” n set clear toggle read\n”);
for (unsigned i = 0; i < 4; i++) {
unsigned n = tests[i];
printf(“%3u %08X %08X %08X %u\n”, n, (unsigned)set_bit(r, n), (unsigned)clear_bit(r, n), (unsigned)toggle_bit(r, n), read_bit(r, n));
}
return 0;
}
Output (verified by compiling and running)
start r = 0x000000F0
n set clear toggle read
0 000000F1 000000F0 000000F1 0
4 000000F0 000000E0 000000E0 1
8 000001F0 000000F0 000001F0 0
31 800000F0 000000F0 800000F0 0
| n | Bit state in 0x00F0 | set | clear | toggle |
|---|
| 0 | 0 | sets it | no change | sets it |
| 4 | 1 | no change | clears it | clears it |
| 8 | 0 | sets it | no change | sets it |
| 31 | 0 | sets MSB (0x800000F0) | no change | sets MSB |
Observe: Set on an already-set bit and clear on an already-clear bit are no-ops (idempotent), while toggle always changes the bit. The functions use 1u, so bit 31 works; with 1 the last row would be undefined behavior.
Example 2: Before/After Register Pictures
Problem: Visualise what each idiom does to a 16-bit register with the value 0x30A0 (0011 0000 1010 0000). Amber cells are the bits that changed. Keep these bit manipulation examples beside the reference manual.
SET bit 8: reg |= (1u << 8)
CLEAR bit 5: reg &= ~(1u << 5)
TOGGLE bit 13: reg ^= (1u << 13)
WRITE the 3-bit field [14:12] with the value 5
before_after.c
#include <stdio.h>
#include <stdint.h>
static void show(const char *label, uint32_t v)
{
printf(“%-22s “, label);
for (int i = 31; i >= 0; i–) { printf(“%d”, (int)((v >> i) & 1u)); if (i % 4 == 0 && i) printf(“_”); }
printf(” 0x%08X\n”, (unsigned)v);
}
int main(void)
{
uint32_t reg = 0x30A0;
show(“start”, reg);
show(“set bit 8”, reg | (1u << 8));
show(“clear bit 5”, reg & ~(1u << 5));
show(“toggle bit 13”, reg ^ (1u << 13));
show(“field[14:12] = 5”, (reg & ~(7u << 12)) | (5u << 12));
return 0;
}
Output (verified by compiling and running)
start 0000_0000_0000_0000_0011_0000_1010_0000 0x000030A0
set bit 8 0000_0000_0000_0000_0011_0001_1010_0000 0x000031A0
clear bit 5 0000_0000_0000_0000_0011_0000_1000_0000 0x00003080
toggle bit 13 0000_0000_0000_0000_0001_0000_1010_0000 0x000010A0
field[14:12] = 5 0000_0000_0000_0000_0101_0000_1010_0000 0x000050A0
The last row first clears the whole 3-bit field with the mask 7u << 12, then ORs in the value 5 (binary 101) shifted into position. The neighbouring bits 15 and 11:0 are not touched.
Example 3: Four LEDs, Configure PD12 to PD15 as Outputs
Problem: Enable the GPIOD clock and set pins 12 to 15 to general-purpose output mode (01) in a loop, using macros that compute the mask from the pin number.
led_init.c
#include <stdio.h>
#include <stdint.h>
static void show(const char *label, uint32_t v)
{
printf(“%-22s “, label);
for (int i = 31; i >= 0; i–) { printf(“%d”, (int)((v >> i) & 1u)); if (i % 4 == 0 && i) printf(“_”); }
printf(” 0x%08X\n”, (unsigned)v);
}
#define PIN_MODER_MASK(p) (3u << ((p) * 2))
#define PIN_MODER_OUTPUT(p) (1u << ((p) * 2))
#define RCC_GPIODEN (1u << 3)
static uint32_t RCC_AHB1ENR = 0x00100000; /* reset value */
static uint32_t GPIOD_MODER = 0x00000000; /* reset value for port D */
int main(void)
{
RCC_AHB1ENR |= RCC_GPIODEN;
show(“RCC_AHB1ENR”, RCC_AHB1ENR);
for (unsigned pin = 12; pin <= 15; pin++) {
GPIOD_MODER &= ~PIN_MODER_MASK(pin); /* clear the 2-bit field */
GPIOD_MODER |= PIN_MODER_OUTPUT(pin); /* write 01 = output */
printf(“after PD%u:”, pin);
show(“”, GPIOD_MODER);
}
printf(“\nmode of each pin 12..15:”);
for (unsigned pin = 12; pin <= 15; pin++) printf(” %u”, (unsigned)((GPIOD_MODER >> (pin * 2)) & 3u));
printf(“\n”);
return 0;
}
Output (verified by compiling and running)
RCC_AHB1ENR 0000_0000_0001_0000_0000_0000_0000_1000 0x00100008
after PD12: 0000_0001_0000_0000_0000_0000_0000_0000 0x01000000
after PD13: 0000_0101_0000_0000_0000_0000_0000_0000 0x05000000
after PD14: 0001_0101_0000_0000_0000_0000_0000_0000 0x15000000
after PD15: 0101_0101_0000_0000_0000_0000_0000_0000 0x55000000
mode of each pin 12..15: 1 1 1 1
MODER after configuration: 0x55000000
| LED | Pin | MODER bits | Value |
|---|
| Green | PD12 | 25:24 | 01 |
| Orange | PD13 | 27:26 | 01 |
| Red | PD14 | 29:28 | 01 |
| Blue | PD15 | 31:30 | 01 |
Reset value of MODER: For port D the reset value is 0x00000000 (all inputs). Ports A and B reset to different values because of the debug pins (SWD/JTAG), so never assume zero there: always use the clear-then-set form.
Example 4: Blink Patterns With ODR and BSRR
Problem: Create named masks for the four LEDs and produce typical patterns: all on, partial off, toggle, only one on, a running light, and the same changes using BSRR.
led_patterns.c
#include <stdio.h>
#include <stdint.h>
static void show(const char *label, uint32_t v)
{
printf(“%-22s “, label);
for (int i = 31; i >= 0; i–) { printf(“%d”, (int)((v >> i) & 1u)); if (i % 4 == 0 && i) printf(“_”); }
printf(” 0x%08X\n”, (unsigned)v);
}
static uint32_t ODR;
static void write_BSRR(uint32_t v) { ODR = (ODR & ~((v >> 16) & 0xFFFFu)) | (v & 0xFFFFu); }
#define LED_GREEN (1u << 12)
#define LED_ORANGE (1u << 13)
#define LED_RED (1u << 14)
#define LED_BLUE (1u << 15)
#define LED_ALL (LED_GREEN | LED_ORANGE | LED_RED | LED_BLUE)
int main(void)
{
ODR = 0;
ODR |= LED_ALL; show(“all on”, ODR);
ODR &= ~(LED_ORANGE | LED_BLUE); show(“orange+blue off”, ODR);
ODR ^= LED_ALL; show(“toggle all (swap)”, ODR);
ODR = (ODR & ~LED_ALL) | LED_RED; show(“only red”, ODR);
write_BSRR(LED_GREEN | (LED_RED << 16)); show(“BSRR: +green -red”, ODR);
write_BSRR(LED_ALL << 16); show(“BSRR: all off”, ODR);
printf(“\nrunning light:\n”);
for (int i = 0; i < 4; i++) {
ODR = (ODR & ~LED_ALL) | (LED_GREEN << i);
printf(” step %d: “, i);
show(“”, ODR);
}
return 0;
}
Output (verified by compiling and running)
all on 0000_0000_0000_0000_1111_0000_0000_0000 0x0000F000
orange+blue off 0000_0000_0000_0000_0101_0000_0000_0000 0x00005000
toggle all (swap) 0000_0000_0000_0000_1010_0000_0000_0000 0x0000A000
only red 0000_0000_0000_0000_0100_0000_0000_0000 0x00004000
BSRR: +green -red 0000_0000_0000_0000_0001_0000_0000_0000 0x00001000
BSRR: all off 0000_0000_0000_0000_0000_0000_0000_0000 0x00000000
running light:
step 0: 0000_0000_0000_0000_0001_0000_0000_0000 0x00001000
step 1: 0000_0000_0000_0000_0010_0000_0000_0000 0x00002000
step 2: 0000_0000_0000_0000_0100_0000_0000_0000 0x00004000
step 3: 0000_0000_0000_0000_1000_0000_0000_0000 0x00008000
LED_ALL = LED_GREEN | LED_ORANGE | LED_RED | LED_BLUE builds a combined mask with OR.ODR ^= LED_ALL inverts the four LEDs at once and leaves PD0–PD11 unchanged.(ODR & ~LED_ALL) | pattern replaces the four LED bits as a field without touching other pins.- BSRR combines a set and a reset in one write:
LED_GREEN | (LED_RED << 16) switches green on and red off.
Why a running light needs the field idiom: Writing ODR = LED_GREEN << i would also clear PD0–PD11, which may be driving other hardware. Always replace only your own bits.
Example 5: Reading a Button and Detecting Edges
Problem: The user button B1 of the Discovery board is connected to PA0 and read through bit 0 of GPIOA->IDR. Count presses by detecting the 0 to 1 transition, and then extend the idea to eight buttons at once.
edges.c
#include <stdio.h>
#include <stdint.h>
int main(void)
{
/* PA0 samples from a push-button, one reading per loop pass (bit 0 of IDR) */
uint32_t idr_samples[] = { 0, 0, 1, 1, 1, 0, 0, 1, 0 };
unsigned n = sizeof idr_samples / sizeof idr_samples[0];
uint32_t prev = 0;
unsigned presses = 0;
printf(“pass IDR.0 rising falling held\n”);
for (unsigned i = 0; i < n; i++) {
uint32_t cur = (idr_samples[i] >> 0) & 1u;
uint32_t rising = cur & ~prev; /* 1 only where 0 -> 1 */
uint32_t falling = ~cur & prev & 1u; /* 1 only where 1 -> 0 */
uint32_t held = cur & prev;
if (rising) presses++;
printf(“%4u %5u %6u %7u %4u\n”, i, (unsigned)cur, (unsigned)(rising & 1u), (unsigned)falling, (unsigned)held);
prev = cur;
}
printf(“button presses counted: %u\n”, presses);
/* Many inputs at once: detect which of 8 buttons changed */
uint8_t before = 0x35, after = 0x3C;
printf(“\nchanged = 0x%02X\n”, before ^ after);
printf(“pressed = 0x%02X (0->1)\n”, (uint8_t)(~before & after));
printf(“released = 0x%02X (1->0)\n”, (uint8_t)(before & ~after));
return 0;
}
Output (verified by compiling and running)
pass IDR.0 rising falling held
0 0 0 0 0
1 0 0 0 0
2 1 1 0 0
3 1 0 0 1
4 1 0 0 1
5 0 0 1 0
6 0 0 0 0
7 1 1 0 0
8 0 0 1 0
button presses counted: 2
changed = 0x09
pressed = 0x08 (0->1)
released = 0x01 (1->0)
| Quantity | Expression | True when |
|---|
| rising edge | cur & ~prev | it is 1 now and was 0 before |
| falling edge | ~cur & prev | it is 0 now and was 1 before |
| changed | cur ^ prev | it differs |
| held | cur & prev | it is 1 in both samples |
Because the operators work on every bit of a word in parallel, the same four expressions find edges on all 16 pins of a port in one operation. A real driver would also debounce the input, for example by requiring several identical samples in a row.
Example 6: Alternate Function Setup for USART2 on PA2 and PA3
Problem: Route the USART2 signals to pins PA2 (TX) and PA3 (RX) of the STM32F407. This needs two multi-bit fields per pin: 2 bits in MODER (value 10, alternate function) and 4 bits in the low alternate function register AFRL (value 7, meaning AF7). The program uses the real reset value of GPIOA MODER, 0xA8000000, to show that other pins are preserved.
usart_pins.c
#include <stdio.h>
#include <stdint.h>
static void show(const char *label, uint32_t v)
{
printf(“%-22s “, label);
for (int i = 31; i >= 0; i–) { printf(“%d”, (int)((v >> i) & 1u)); if (i % 4 == 0 && i) printf(“_”); }
printf(” 0x%08X\n”, (unsigned)v);
}
#define AFRL_MASK(pin) (0xFu << ((pin) * 4)) /* pins 0..7: 4 bits each */
#define AFRL_VALUE(pin, af) ((uint32_t)(af) << ((pin) * 4))
static uint32_t GPIOA_MODER = 0xA8000000; /* reset value of GPIOA (SWD pins PA13/14 are AF) */
static uint32_t GPIOA_AFRL = 0x00000000;
int main(void)
{
show(“GPIOA_MODER reset”, GPIOA_MODER);
/* USART2: TX = PA2, RX = PA3, alternate function AF7 */
for (unsigned pin = 2; pin <= 3; pin++) {
GPIOA_MODER = (GPIOA_MODER & ~(3u << (pin * 2))) | (2u << (pin * 2)); /* 10 = alternate function */
GPIOA_AFRL = (GPIOA_AFRL & ~AFRL_MASK(pin)) | AFRL_VALUE(pin, 7); /* AF7 */
}
show(“MODER PA2,PA3 = AF”, GPIOA_MODER);
show(“AFRL PA2,PA3 = AF7”, GPIOA_AFRL);
printf(“\nAF number of PA2 = %u\n”, (unsigned)((GPIOA_AFRL >> (2 * 4)) & 0xFu));
printf(“AF number of PA3 = %u\n”, (unsigned)((GPIOA_AFRL >> (3 * 4)) & 0xFu));
printf(“PA13 mode (SWDIO, untouched) = %u\n”, (unsigned)((GPIOA_MODER >> (13 * 2)) & 3u));
return 0;
}
Output (verified by compiling and running)
GPIOA_MODER reset 1010_1000_0000_0000_0000_0000_0000_0000 0xA8000000
MODER PA2,PA3 = AF 1010_1000_0000_0000_0000_0000_1010_0000 0xA80000A0
AFRL PA2,PA3 = AF7 0000_0000_0000_0000_0111_0111_0000_0000 0x00007700
AF number of PA2 = 7
AF number of PA3 = 7
PA13 mode (SWDIO, untouched) = 2
AFRL: four bits per pin, pins 0 to 7
| Register | Pins | Field width | Field position of pin n |
|---|
| MODER | 0–15 | 2 bits | 2n |
| AFRL | 0–7 | 4 bits | 4n |
| AFRH | 8–15 | 4 bits | 4(n − 8) |
Datasheet check: The alternate function number is not a rule you can derive: look up the pin in the alternate-function table of the STM32F407 datasheet. PA2 and PA3 map USART2_TX and USART2_RX to AF7. Using the wrong AF number leaves the pin disconnected from the peripheral.
Example 7: An Event-Flag Word Shared by Application Tasks
Problem: A communication module reports events to the main loop. Eight on/off events fit in one byte instead of eight separate variables. Build the set / clear / any / all operations from the idioms.
event_flags.c
#include <stdio.h>
#include <stdint.h>
enum {
EVT_RX_READY = 1u << 0,
EVT_TX_DONE = 1u << 1,
EVT_TIMEOUT = 1u << 2,
EVT_BUTTON = 1u << 3,
EVT_ERROR = 1u << 7
};
static uint32_t events;
#define EVT_SET(e) (events |= (e))
#define EVT_CLEAR(e) (events &= ~(e))
#define EVT_ANY(m) ((events & (m)) != 0u)
#define EVT_ALL(m) ((events & (m)) == (m))
static void print_events(const char *label)
{
printf(“%-26s 0x%02X RX:%d TX:%d TMO:%d BTN:%d ERR:%d\n”, label, (unsigned)events,
!!(events & EVT_RX_READY), !!(events & EVT_TX_DONE), !!(events & EVT_TIMEOUT), !!(events & EVT_BUTTON), !!(events & EVT_ERROR));
}
int main(void)
{
print_events(“start”);
EVT_SET(EVT_RX_READY | EVT_BUTTON); print_events(“RX + button”);
printf(“any of RX/TX? %d\n”, EVT_ANY(EVT_RX_READY | EVT_TX_DONE));
printf(“all of RX and TX? %d\n”, EVT_ALL(EVT_RX_READY | EVT_TX_DONE));
EVT_SET(EVT_TX_DONE); print_events(“+ TX done”);
printf(“all of RX and TX? %d\n”, EVT_ALL(EVT_RX_READY | EVT_TX_DONE));
EVT_CLEAR(EVT_RX_READY | EVT_TX_DONE); print_events(“handled RX, TX”);
EVT_SET(EVT_ERROR); print_events(“error raised”);
printf(“sizeof(events) = %zu bytes holds up to %zu flags\n”, sizeof events, sizeof events * 8);
return 0;
}
Output (verified by compiling and running)
start 0x00 RX:0 TX:0 TMO:0 BTN:0 ERR:0
RX + button 0x09 RX:1 TX:0 TMO:0 BTN:1 ERR:0
any of RX/TX? 1
all of RX and TX? 0
+ TX done 0x0B RX:1 TX:1 TMO:0 BTN:1 ERR:0
all of RX and TX? 1
handled RX, TX 0x08 RX:0 TX:0 TMO:0 BTN:1 ERR:0
error raised 0x88 RX:0 TX:0 TMO:0 BTN:1 ERR:1
sizeof(events) = 4 bytes holds up to 32 flags
| Question | Expression | Reads as |
|---|
| Is event e pending? | (events & e) != 0 | any |
| Are all events in mask m pending? | (events & m) == m | all |
| Acknowledge events m | events &= ~m | clear |
| None of m pending? | (events & m) == 0 | none |
Shared with an interrupt? If an ISR sets flags and the main loop clears them, events |= e in the ISR and events &= ~e in the main loop are both read-modify-write. Make events volatile, and disable interrupts around the clear or use an atomic operation (Module 14).
Example 8: A Bitmap Allocator for 64 Buffers
Problem: Track which of 64 fixed-size buffers are in use with one bit each instead of a byte or a struct each. This gives an allocator that needs only 8 bytes of RAM.
bitmap_alloc.c
#include <stdio.h>
#include <stdint.h>
#define N_BUF 64
static uint32_t used[N_BUF / 32]; /* 1 bit per buffer: 1 = in use */
static void mark_used(unsigned i) { used[i / 32] |= (1u << (i % 32)); }
static void mark_free(unsigned i) { used[i / 32] &= ~(1u << (i % 32)); }
static unsigned is_used(unsigned i) { return (used[i / 32] >> (i % 32)) & 1u; }
static int alloc(void)
{
for (unsigned i = 0; i < N_BUF; i++)
if (!is_used(i)) { mark_used(i); return (int)i; }
return –1;
}
int main(void)
{
int a = alloc(), b = alloc(), c = alloc();
printf(“allocated %d, %d, %d\n”, a, b, c);
mark_free((unsigned)b);
printf(“freed %d, next alloc gives %d\n”, b, alloc());
for (int i = 0; i < 61; i++) alloc(); /* use up the rest */
printf(“pool full, alloc returns %d\n”, alloc());
printf(“bitmap words: 0x%08X 0x%08X\n”, (unsigned)used[0], (unsigned)used[1]);
printf(“bitmap uses %zu bytes for %d buffers\n”, sizeof used, N_BUF);
return 0;
}
Output (verified by compiling and running)
allocated 0, 1, 2
freed 1, next alloc gives 1
pool full, alloc returns -1
bitmap words: 0xFFFFFFFF 0xFFFFFFFF
bitmap uses 8 bytes for 64 buffers
Bit i lives in word i / 32 at position i % 32
Example: buffers 0 and 2 in use. i / 32 selects the word and i % 32 the bit (or i & 31).
The division and remainder by 32 are a shift and a mask after optimisation. On a Cortex-M4 you can find the first free bit faster with __builtin_ctz(~word), which compiles to RBIT + CLZ instructions.
Example 9: Mini Exercises
Exercise 1: Write the statement that sets bit 3 and clears bit 5 of reg in one line.
reg = (reg | (1u << 3)) & ~(1u << 5);
Exercise 2: What are 0x00 | (1u << 4) and 0xFF & ~(1u << 4)?
0x10 and 0xEF.
Exercise 3: Write the expression that makes PD14 output (MODER field 29:28 = 01).
GPIOD->MODER = (GPIOD->MODER & ~(3u << 28)) | (1u << 28);
Exercise 4: Which single write turns PD12 on and PD13 off without a read?
GPIOD->BSRR = (1u << 12) | (1u << (13 + 16));
Exercise 5: Which bit position and which mask enable the GPIOA clock in RCC_AHB1ENR?
Bit 0, mask (1u << 0) = RCC_AHB1ENR_GPIOAEN.
Exercise 6: What does x & -x give for x = 0b0110 1000 (unsigned arithmetic)?
The lowest set bit: 0b0000 1000 = 8.
Exercise 7: In a bitmap, which word and bit hold buffer 45?
Word 1 (45 / 32), bit 13 (45 % 32).
Key Takeaways from the Bit Manipulation Examples
- These bit manipulation examples show that all register work reduces to set, clear, toggle, read and field-write.
- Use
1u masks and named constants; build multi-LED masks with OR. - Replace a field with
(reg & ~MASK) | VALUE; never assign over a shared register. - BSRR combines atomic set and reset in one write.
- Edge detection is
cur & ~prev and ~cur & prev; it works on all pins at once. - AF selection uses 2-bit MODER and 4-bit AFR fields: pin n at 2n and 4n.
- Flags and bitmaps pack many booleans into a word: set with OR, test with AND, acknowledge with AND-NOT.
Ready for the quiz?
Next: write the expression to set, clear or toggle bit N, register MCQs, code challenges and the interview questions every embedded engineer is asked.
2 Comments