MODULE 9 · LESSON 9.6 · EXAMPLES
Memory Mapped Register Examples in Embedded C: GPIO, BSRR, USART, SysTick and Testable Drivers
Eight worked STM32F407 examples with real output: an LED chase with BSRR, pin configuration in MODER and AFR, USART status polling, button debouncing, BSRR word calculation, baud-rate registers, a testable driver and SysTick setup. Study this one of the memory mapped register examples in embedded C closely.
Intermediate → Advanced
Level
Real output
Compiled and run
Memory Mapped Register Examples in Embedded C: What This Page Covers
These memory mapped register examples in embedded C apply Lesson 9.6 to real STM32F407 peripherals: GPIOD, GPIOA, USART2 and SysTick. Because a PC has no such hardware, each program replaces the base address by a RAM structure and marks the few lines that exist only to imitate the hardware (PC only). The driver logic, the masks, the offsets and the register values are the ones the board uses. Every program was compiled with GCC and run; the output shown is real. These memory mapped register examples in embedded C build on each other.
| # | Example | Skill |
|---|
| 1 | LED chase using one BSRR write per step | BSRR, masks |
| 2 | Configuring pins: MODER and alternate functions | Field update |
| 3 | Polling a USART status flag with a timeout | volatile, SR |
| 4 | Debouncing a button read from IDR | Bit extraction |
| 5 | Computing a BSRR word for any pin pattern | Atomic update |
| 6 | USART2 registers and the baud-rate register | Offsets, BRR |
| 7 | A driver that can be unit-tested on a PC | Testability |
| 8 | Configuring SysTick for a 1 ms tick | Core peripheral |
| 9 | Mini exercises | Self-test |
Example 1: LED Chase Using One BSRR Write per Step
Problem: Light the four discovery-board LEDs (PD12 green, PD13 orange, PD14 red, PD15 blue) one after another, without disturbing the other pins of port D. The trick is the BSRR word (LED_MASK << 16) | (1u << pin): the upper half asks to reset all four LED pins and the lower half asks to set one of them. The hardware gives the set action priority when a pin is in both halves, so exactly one LED is on after the single store. In the output the low bits 0x0003 (PD0 and PD1, pretend they drive something else) survive every step, which proves that BSRR changed only the pins named in the word. A read-modify-write sequence would need an interrupt lock to be equally safe. Among the memory mapped register examples in embedded C this pattern is very common.
led_chase.c
#include <stdio.h>
#include <stdint.h>
#define __IO volatile
typedef struct { __IO uint32_t MODER, OTYPER, OSPEEDR, PUPDR, IDR, ODR, BSRR, LCKR, AFR[2]; } GPIO_TypeDef;
static GPIO_TypeDef sim_gpiod; /* board: #define GPIOD ((GPIO_TypeDef *)0x40020C00UL) */
#define GPIOD (&sim_gpiod)
/* PC only: what the hardware does when software writes BSRR (board: GPIOD->BSRR = v;) */
static void write_bsrr(GPIO_TypeDef *port, uint32_t v)
{
port->ODR = (port->ODR & ~(v >> 16)) | (v & 0xFFFFu); /* reset first, then set: set wins */
}
#define LED_MASK 0xF000u /* PD12..PD15 */
static void show(const char *tag)
{
uint32_t o = GPIOD->ODR;
printf(“%-9s ODR=0x%04X green=%c orange=%c red=%c blue=%c\n”, tag, (unsigned)o,
(o >> 12 & 1) ? ‘X’ : ‘-‘, (o >> 13 & 1) ? ‘X’ : ‘-‘, (o >> 14 & 1) ? ‘X’ : ‘-‘, (o >> 15 & 1) ? ‘X’ : ‘-‘);
}
int main(void)
{
GPIOD->ODR = 0x0003; /* PD0 and PD1 are used by something else: must stay set */
for (int step = 0; step < 6; step++) {
unsigned pin = 12u + (unsigned)(step % 4);
/* one store: reset the four LED pins and set exactly one; other pins are not touched */
write_bsrr(GPIOD, (LED_MASK << 16) | (1u << pin));
char tag[16];
snprintf(tag, sizeof tag, “step %d:”, step);
show(tag);
}
return 0;
}
Output (verified by compiling and running)
step 0: ODR=0x1003 green=X orange=- red=- blue=-
step 1: ODR=0x2003 green=- orange=X red=- blue=-
step 2: ODR=0x4003 green=- orange=- red=X blue=-
step 3: ODR=0x8003 green=- orange=- red=- blue=X
step 4: ODR=0x1003 green=X orange=- red=- blue=-
step 5: ODR=0x2003 green=- orange=X red=- blue=-
Where the model ends: The function write_bsrr exists only on the PC. On the board the single statement GPIOD->BSRR = word; is the whole driver.
Example 2: Configuring Pins in MODER and the Alternate-Function Registers
Problem: Make PA2 and PA3 the transmit and receive pins of USART2, and make PA0 an input for the user button. Each pin uses a two-bit field in MODER (00 input, 01 output, 10 alternate function, 11 analog) and a four-bit field in the alternate-function registers: AFR[0] (AFRL) for pins 0–7 and AFR[1] (AFRH) for pins 8–15. The helpers first clear the pin’s field, then insert the new value, so earlier contents never leak in. The program starts from the reset value 0xA8000000 of GPIOA_MODER and the result 0xA80000A0 shows the debug pins unchanged and PA2, PA3 set to 10 (bits 5:4 and 7:6). AFRL = 0x7700: AF7 sits in bits 11:8 for PA2 and 15:12 for PA3. Changing PA2 again to output produces 0xA8000090: the field became 01 and the neighbouring pin kept 10, which a plain |= without clearing would have corrupted. Keep these memory mapped register examples in embedded C for revision.
gpio_config.c
#include <stdio.h>
#include <stdint.h>
#define __IO volatile
typedef struct { __IO uint32_t MODER, OTYPER, OSPEEDR, PUPDR, IDR, ODR, BSRR, LCKR, AFR[2]; } GPIO_TypeDef;
enum { MODE_INPUT = 0, MODE_OUTPUT = 1, MODE_AF = 2, MODE_ANALOG = 3 };
static void gpio_set_mode(GPIO_TypeDef *port, unsigned pin, unsigned mode)
{
uint32_t v = port->MODER;
v &= ~(3u << (2u * pin)); /* clear the 2-bit field of this pin */
v |= (uint32_t)mode << (2u * pin); /* insert the new mode */
port->MODER = v;
}
static void gpio_set_af(GPIO_TypeDef *port, unsigned pin, unsigned af)
{
unsigned reg = pin >> 3; /* pins 0..7 -> AFR[0], 8..15 -> AFR[1] */
unsigned sh = (pin & 7u) * 4u; /* 4 bits per pin */
uint32_t v = port->AFR[reg];
v &= ~(0xFu << sh);
v |= (uint32_t)(af & 0xFu) << sh;
port->AFR[reg] = v;
}
int main(void)
{
GPIO_TypeDef gpioa = { .MODER = 0xA8000000u }; /* GPIOA reset value: debug pins PA13..PA15 are AF */
gpio_set_mode(&gpioa, 2, MODE_AF); /* PA2 = USART2_TX */
gpio_set_mode(&gpioa, 3, MODE_AF); /* PA3 = USART2_RX */
gpio_set_af(&gpioa, 2, 7); /* AF7 = USART1..3 */
gpio_set_af(&gpioa, 3, 7);
gpio_set_mode(&gpioa, 0, MODE_INPUT); /* PA0 = user button */
printf(“MODER = 0x%08X\n”, (unsigned)gpioa.MODER);
printf(“AFRL = 0x%08X\n”, (unsigned)gpioa.AFR[0]);
printf(“AFRH = 0x%08X\n”, (unsigned)gpioa.AFR[1]);
gpio_set_mode(&gpioa, 2, MODE_OUTPUT); /* change the same pin again: the old value must not leak in */
printf(“PA2 changed to output, MODER = 0x%08X\n”, (unsigned)gpioa.MODER);
return 0;
}
Output (verified by compiling and running)
MODER = 0xA80000A0
AFRL = 0x00007700
AFRH = 0x00000000
PA2 changed to output, MODER = 0xA8000090
The debug pins: PA13 (SWDIO), PA14 (SWCLK) and PA15 (JTDI) are alternate-function pins after reset. A driver that rewrites the whole MODER with a constant can lock you out of the debugger, which is another reason to update fields instead of assigning the register.
Example 3: Polling a USART Status Flag with a Timeout
Problem: Wait for a received byte, but never hang forever. USART_SR bit 5 (RXNE) becomes 1 when a byte is waiting in USART_DR; bit 7 is TXE (transmit buffer empty) and bit 6 TC (transmission complete). The loop while (!(USART2->SR & USART_SR_RXNE)) only works because SR is volatile: each pass performs a real read. The hardware model arrives with a byte after a number of polling steps, so the first call (a byte after 5 polls, up to 20 allowed) succeeds with A, while the second (a byte after 50 polls, only 10 allowed) times out with -1. The last line decodes SR = 0xC0 as TXE=1, TC=1, RXNE=0.
uart_poll.c
#include <stdio.h>
#include <stdint.h>
#define __IO volatile
typedef struct { __IO uint32_t SR, DR, BRR, CR1, CR2, CR3, GTPR; } USART_TypeDef;
#define USART_SR_RXNE (1u << 5)
#define USART_SR_TC (1u << 6)
#define USART_SR_TXE (1u << 7)
static USART_TypeDef sim_usart2; /* board: #define USART2 ((USART_TypeDef *)0x40004400UL) */
#define USART2 (&sim_usart2)
/* —- PC only: a tiny model of the receiver. A byte arrives after ‘arrive_in’ polling steps —- */
static int arrive_in = –1;
static uint8_t incoming;
static void hw_step(void)
{
if (arrive_in > 0 && –arrive_in == 0) { USART2->DR = incoming; USART2->SR |= USART_SR_RXNE; }
}
static void hw_receive_after(int steps, uint8_t byte) { arrive_in = steps; incoming = byte; }
/* —- driver code: this is what you would write on the board —- */
static int uart_getc_timeout(uint8_t *out, unsigned max_polls)
{
while (!(USART2->SR & USART_SR_RXNE)) { /* poll the status flag: volatile makes each read real */
if (max_polls– == 0) return –1; /* timeout: never wait forever */
hw_step(); /* PC only */
}
*out = (uint8_t)USART2->DR; /* reading DR clears RXNE on the real chip */
USART2->SR &= ~USART_SR_RXNE; /* PC only: emulate that clearing */
return 0;
}
int main(void)
{
uint8_t c;
hw_receive_after(5, ‘A’);
int r = uart_getc_timeout(&c, 20);
printf(“first call : result %d, byte ‘%c’\n”, r, r == 0 ? c : ‘?’);
hw_receive_after(50, ‘B’);
r = uart_getc_timeout(&c, 10);
printf(“second call: result %d (timeout, nothing arrived within 10 polls)\n”, r);
USART2->SR = USART_SR_TXE | USART_SR_TC;
printf(“SR = 0x%02X TXE=%u TC=%u RXNE=%u\n”, (unsigned)USART2->SR, (unsigned)((USART2->SR >> 7) & 1u), (unsigned)((USART2->SR >> 6) & 1u), (unsigned)((USART2->SR >> 5) & 1u));
return 0;
}
Output (verified by compiling and running)
first call : result 0, byte ‘A’
second call: result -1 (timeout, nothing arrived within 10 polls)
SR = 0xC0 TXE=1 TC=1 RXNE=0
Real behaviour: On the chip, reading DR returns the received byte and clears RXNE; the explicit clear in the program is part of the PC model. Also check the error flags (ORE, FE, NE, PE) in a production driver: an overrun stops reception until the flag is cleared.
Example 4: Debouncing a Button Read from IDR
Problem: The user button is on PA0, read from bit 0 of GPIOA->IDR. A mechanical contact bounces for a few milliseconds, so single samples cannot be trusted. The program receives one IDR snapshot per millisecond (other bits hold unrelated pin levels, so the code isolates its bit with (idr >> BUTTON_BIT) & 1u) and accepts a new state only after four identical samples in a row. The data contains 8 raw edges, but only two real events come out: PRESSED at sample 10 and RELEASED at sample 18. In a driver the snapshot would be GPIOA->IDR read once per tick (a read, not a read-modify-write, so IDR is safe to poll at any rate).
button_debounce.c
#include <stdio.h>
#include <stdint.h>
#define BUTTON_BIT 0u /* PA0 */
#define STABLE_SAMPLES 4
int main(void)
{
/* snapshots of GPIOA->IDR taken every millisecond; other pins carry unrelated levels */
const uint32_t idr[] = {
0x0004, 0x0004, 0x0005, 0x0004, 0x0005, 0x0005, 0x0004, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005,
0x0005, 0x0004, 0x0005, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004
};
const int n = (int)(sizeof idr / sizeof idr[0]);
unsigned state = 0, candidate = 0, count = 0, events = 0;
for (int i = 0; i < n; i++) {
unsigned raw = (idr[i] >> BUTTON_BIT) & 1u; /* isolate PA0 */
if (raw == candidate) {
if (count < STABLE_SAMPLES) count++;
} else {
candidate = raw;
count = 1;
}
if (count == STABLE_SAMPLES && candidate != state) {
state = candidate;
events++;
printf(“sample %2d: button %s\n”, i, state ? “PRESSED” : “RELEASED”);
}
}
printf(“raw edges seen in the data: “);
unsigned edges = 0;
for (int i = 1; i < n; i++) edges += (((idr[i] ^ idr[i – 1]) & 1u) != 0);
printf(“%u, debounced events: %u\n”, edges, events);
return 0;
}
Output (verified by compiling and running)
sample 10: button PRESSED
sample 18: button RELEASED
raw edges seen in the data: 8, debounced events: 2
Example 5: Computing a BSRR Word for Any Pin Pattern
Problem: Make the pins selected by mask take the levels given by value, atomically. A pin of the mask whose value bit is 1 goes into the lower (set) half; one whose value bit is 0 goes into the upper (reset) half. The output starts from ODR = 0x00A5. Writing bsrr_word(0xF000, 0x5000) gives 0xA0005000 (set PD12 and PD14, reset PD13 and PD15) and the result 0x50A5 leaves the low byte alone. The second call changes only the low nibble (5 → 9) with 0x00060009: set bits 0 and 3, reset bits 1 and 2. An empty mask produces 0 and nothing changes, a safe no-op.
bsrr_word.c
#include <stdio.h>
#include <stdint.h>
/* Build the BSRR word that makes the pins in ‘mask’ take the levels in ‘value’ and leaves all other pins alone */
static uint32_t bsrr_word(uint16_t mask, uint16_t value)
{
uint32_t set = (uint32_t)(mask & value);
uint32_t reset = (uint32_t)(mask & (uint16_t)~value);
return set | (reset << 16);
}
static uint32_t odr; /* PC model of the output register */
static void write_bsrr(uint32_t v) { odr = (odr & ~(v >> 16)) | (v & 0xFFFFu); }
int main(void)
{
odr = 0x00A5;
printf(“start ODR = 0x%04X\n”, (unsigned)odr);
uint32_t w = bsrr_word(0xF000, 0x5000); /* LEDs: green and red on, orange and blue off */
write_bsrr(w);
printf(“BSRR = 0x%08X ODR = 0x%04X\n”, (unsigned)w, (unsigned)odr);
w = bsrr_word(0x000F, 0x0009); /* low nibble becomes 1001, nothing else changes */
write_bsrr(w);
printf(“BSRR = 0x%08X ODR = 0x%04X\n”, (unsigned)w, (unsigned)odr);
w = bsrr_word(0x0000, 0xFFFF); /* empty mask: a write of zero, no effect */
write_bsrr(w);
printf(“BSRR = 0x%08X ODR = 0x%04X\n”, (unsigned)w, (unsigned)odr);
return 0;
}
Output (verified by compiling and running)
start ODR = 0x00A5
BSRR = 0xA0005000 ODR = 0x50A5
BSRR = 0x00060009 ODR = 0x50A9
BSRR = 0x00000000 ODR = 0x50A9
Why not write ODR directly? ODR = (ODR & ~mask) | value; is a read-modify-write: an interrupt that updates another pin of the port between the read and the write loses its change. The BSRR form is a single store.
Example 6: USART2 Register Offsets and the Baud-Rate Register
Problem: Calculate the value for USART_BRR and enable the USART. With 16-times oversampling BRR = fck / baud, where the integer part (the “mantissa”) occupies bits 15:4 and the fraction (in sixteenths) bits 3:0, so rounding the quotient to an integer produces the register value directly. USART2 sits on APB1, which runs at 42 MHz when the core runs at 168 MHz. The static asserts check the layout against the reference manual (SR 0x00, DR 0x04, BRR 0x08, CR1 0x0C, …) and the printed addresses show base 0x40004400 plus each offset. For 115200 baud the result is 0x016D: mantissa 22, fraction 13, actual 115068.5 baud, an error of −0.11%, well inside the roughly 2–3% tolerance of a UART link. At 921600 baud the rounding error is already −0.93%. Finally CR1 = UE | TE | RE equals 0x200C (bits 13, 3 and 2).
usart_regs.c
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#define __IO volatile
typedef struct { __IO uint32_t SR, DR, BRR, CR1, CR2, CR3, GTPR; } USART_TypeDef;
_Static_assert(offsetof(USART_TypeDef, DR) == 0x04, “DR”);
_Static_assert(offsetof(USART_TypeDef, BRR) == 0x08, “BRR”);
_Static_assert(offsetof(USART_TypeDef, CR1) == 0x0C, “CR1”);
_Static_assert(offsetof(USART_TypeDef, GTPR) == 0x18, “GTPR”);
#define USART2_BASE 0x40004400u
#define CR1_UE (1u << 13)
#define CR1_TE (1u << 3)
#define CR1_RE (1u << 2)
/* oversampling by 16: BRR = fck / baud, rounded (the mantissa is bits 15:4, the fraction bits 3:0) */
static uint32_t brr_value(uint32_t fck, uint32_t baud) { return (fck + baud / 2u) / baud; }
int main(void)
{
printf(“USART2 registers: SR %#x DR %#x BRR %#x CR1 %#x CR2 %#x CR3 %#x\n”, USART2_BASE,
USART2_BASE + 4u, USART2_BASE + 8u, USART2_BASE + 0xCu, USART2_BASE + 0x10u, USART2_BASE + 0x14u);
const uint32_t fck = 42000000u; /* APB1 clock when the core runs at 168 MHz */
const uint32_t bauds[] = { 9600u, 115200u, 921600u };
for (int i = 0; i < 3; i++) {
uint32_t brr = brr_value(fck, bauds[i]);
double actual = (double)fck / (double)brr;
printf(“%7lu baud: BRR=0x%04X (mantissa %u, fraction %u) actual %.1f baud, error %+.2f%%\n”,
(unsigned long)bauds[i], (unsigned)brr, (unsigned)(brr >> 4), (unsigned)(brr & 0xFu),
actual, (actual – (double)bauds[i]) * 100.0 / (double)bauds[i]);
}
USART_TypeDef sim = {0};
sim.BRR = brr_value(fck, 115200u);
sim.CR1 = CR1_UE | CR1_TE | CR1_RE; /* enable USART, transmitter and receiver */
printf(“CR1 = 0x%04X\n”, (unsigned)sim.CR1);
return 0;
}
Output (verified by compiling and running)
USART2 registers: SR 0x40004400 DR 0x40004404 BRR 0x40004408 CR1 0x4000440c CR2 0x40004410 CR3 0x40004414
9600 baud: BRR=0x1117 (mantissa 273, fraction 7) actual 9600.0 baud, error +0.00%
115200 baud: BRR=0x016D (mantissa 22, fraction 13) actual 115068.5 baud, error -0.11%
921600 baud: BRR=0x002E (mantissa 2, fraction 14) actual 913043.5 baud, error -0.93%
CR1 = 0x200C
Check your clock: The result is only valid for the stated peripheral clock. USART1 and USART6 are on APB2 (84 MHz at full speed), USART2 and USART3 on APB1 (42 MHz). A wrong bus frequency gives a wrong baud rate even though the driver “works”.
Example 7: A Register Driver That Can Be Unit-Tested on a PC
Problem: Test LED logic without a board. The driver functions receive the port as a parameter (GPIO_TypeDef *port) instead of using the global GPIOD macro. On the target the caller passes GPIOD; the test passes the address of an ordinary structure. led_toggle follows the approach of the ST HAL: read ODR to decide, then write a single BSRR word (reset if the pin is on, set if it is off). The six checks all pass, including the last one, which proves the driver never touched pins outside the LEDs. Passing the peripheral as a parameter is a small design decision that turns hardware code into testable code and costs one register in the call.
driver_test.c
#include <stdio.h>
#include <stdint.h>
#define __IO volatile
typedef struct { __IO uint32_t MODER, OTYPER, OSPEEDR, PUPDR, IDR, ODR, BSRR, LCKR, AFR[2]; } GPIO_TypeDef;
/* PC model of the hardware effect of a BSRR write */
static void bsrr_effect(GPIO_TypeDef *p, uint32_t v) { p->ODR = (p->ODR & ~(v >> 16)) | (v & 0xFFFFu); }
/* —- driver: takes the port as a parameter, so a test can pass a fake block —- */
static void led_set(GPIO_TypeDef *port, unsigned pin, int on)
{
uint32_t v = on ? (1u << pin) : (1u << (pin + 16u));
port->BSRR = v;
bsrr_effect(port, v); /* PC only: the hardware would act on the write */
}
static void led_toggle(GPIO_TypeDef *port, unsigned pin)
{
uint32_t odr = port->ODR; /* same idea as the ST HAL: decide from ODR, act through BSRR */
uint32_t v = ((odr & (1u << pin)) << 16) | (~odr & (1u << pin));
port->BSRR = v;
bsrr_effect(port, v); /* PC only */
}
static int failures;
#define CHECK(cond) do { if (cond) printf(“PASS %s\n”, #cond); else { printf(“FAIL %s\n”, #cond); failures++; } } while (0)
int main(void)
{
GPIO_TypeDef fake = {0};
led_set(&fake, 12, 1); CHECK(fake.ODR == 0x1000);
led_set(&fake, 15, 1); CHECK(fake.ODR == 0x9000);
led_toggle(&fake, 12); CHECK(fake.ODR == 0x8000);
led_toggle(&fake, 12); CHECK(fake.ODR == 0x9000);
led_set(&fake, 15, 0); CHECK(fake.ODR == 0x1000);
CHECK((fake.ODR & 0x0FFF) == 0);
printf(“%d failure(s)\n”, failures);
return failures != 0;
}
Output (verified by compiling and running)
PASS fake.ODR == 0x1000
PASS fake.ODR == 0x9000
PASS fake.ODR == 0x8000
PASS fake.ODR == 0x9000
PASS fake.ODR == 0x1000
PASS (fake.ODR & 0x0FFF) == 0
0 failure(s)
Model versus chip: BSRR is write-only: on the real chip, reading it returns 0. The model above therefore applies the effect from the value computed in the driver, not by reading BSRR back.
Example 8: Configuring SysTick for a 1 ms Tick
Problem: Set up the Cortex-M4 SysTick timer, a core peripheral at 0xE000E010, to interrupt every millisecond. Its registers are CTRL (offset 0), LOAD (4), VAL (8) and the read-only CALIB (0xC). The counter counts from LOAD down to 0, which is LOAD + 1 clock ticks per period, hence LOAD = ticks − 1. With a 168 MHz clock a 1 ms period is 168,000 ticks, giving LOAD = 167999 = 0x02903F. CTRL = 0x7 means enable (bit 0), interrupt (bit 1) and processor clock source (bit 2). The reload register is only 24 bits wide, so the function refuses periods above 16,777,216 ticks: at 168 MHz the longest period is 99.9 ms, so the 200 ms request fails with a result of 1. This is the same check the CMSIS function SysTick_Config performs.
systick_config.c
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#define __IO volatile
#define __I volatile const
typedef struct
{
__IO uint32_t CTRL; /* 0x00 control and status */
__IO uint32_t LOAD; /* 0x04 reload value (24 bits) */
__IO uint32_t VAL; /* 0x08 current value */
__I uint32_t CALIB; /* 0x0C calibration */
} SysTick_Type;
_Static_assert(offsetof(SysTick_Type, LOAD) == 4 && offsetof(SysTick_Type, CALIB) == 0xC, “layout”);
#define SYSTICK_CTRL_ENABLE (1u << 0)
#define SYSTICK_CTRL_TICKINT (1u << 1)
#define SYSTICK_CTRL_CLKSOURCE (1u << 2) /* 1 = processor clock */
#define SYSTICK_CTRL_COUNTFLAG (1u << 16)
static SysTick_Type sim_systick; /* board: #define SysTick ((SysTick_Type *)0xE000E010UL) */
#define SysTick (&sim_systick)
static int systick_config(uint32_t ticks)
{
if (ticks == 0u || (ticks – 1u) > 0x00FFFFFFu) return 1; /* the reload register has 24 bits */
SysTick->LOAD = ticks – 1u; /* counts N .. 0, which is N ticks per period */
SysTick->VAL = 0u;
SysTick->CTRL = SYSTICK_CTRL_CLKSOURCE | SYSTICK_CTRL_TICKINT | SYSTICK_CTRL_ENABLE;
return 0;
}
int main(void)
{
const uint32_t hclk = 168000000u; /* STM32F407 at full speed */
int r = systick_config(hclk / 1000u); /* 1 ms tick */
printf(“1 ms tick : result %d, LOAD = %lu (0x%06lX), CTRL = 0x%X\n”, r, (unsigned long)SysTick->LOAD, (unsigned long)SysTick->LOAD, (unsigned)SysTick->CTRL);
r = systick_config(hclk / 5u); /* 200 ms would need 33,600,000 ticks */
printf(“200 ms tick: result %d (too long for 24 bits; the largest period at 168 MHz is %.1f ms)\n”, r, 16777216.0 * 1000.0 / hclk);
printf(“CTRL bits: ENABLE=%u TICKINT=%u CLKSOURCE=%u COUNTFLAG=%u\n”, (unsigned)(SysTick->CTRL & 1u), (unsigned)((SysTick->CTRL >> 1) & 1u), (unsigned)((SysTick->CTRL >> 2) & 1u), (unsigned)((SysTick->CTRL >> 16) & 1u));
return 0;
}
Output (verified by compiling and running)
1 ms tick : result 0, LOAD = 167999 (0x02903F), CTRL = 0x7
200 ms tick: result 1 (too long for 24 bits; the largest period at 168 MHz is 99.9 ms)
CTRL bits: ENABLE=1 TICKINT=1 CLKSOURCE=1 COUNTFLAG=0
Reading COUNTFLAG: Bit 16 (COUNTFLAG) is set when the counter reaches 0 and is cleared by reading CTRL. Reading it for debugging therefore changes it, an example of a register read with a side effect.
Example 9: Mini Exercises
Exercise 1: What is the address of GPIOD_BSRR?
0x40020C00 + 0x18 = 0x40020C18.
Exercise 2: Which BSRR word turns PD13 off and PD14 on?
(1u << 14) | (1u << (13 + 16)) = 0x20004000.
Exercise 3: In which register and bits does PB5 mode live?
GPIOB_MODER, bits 11:10 (pin × 2 + 1 down to pin × 2).
Exercise 4: Where does AF7 for PA9 go?
PA9 is in AFR[1] (AFRH); its field is bits 7:4, so the value is 7u << 4.
Exercise 5: What is the value of LOAD for a 10 ms SysTick period at 168 MHz?
1,680,000 − 1 = 1,679,999 (0x19A27F), well inside the 24-bit limit.
Exercise 6: Why is reading USART_DR in a debugger watch window risky?
Reading DR clears RXNE and consumes the received byte, so the program may never see it.
Exercise 7: Why is IDR declared volatile const?
const forbids software writes (it is read-only hardware); volatile forces every read to reach the pin level.
Key Takeaways from the Memory Mapped Register Examples in Embedded C
- These memory mapped register examples in embedded C show that every register access is an ordinary pointer dereference through a
volatile type. - Update multi-bit fields by clearing and then inserting; never OR into a field that may be non-zero.
- Use BSRR for atomic pin changes and compute its word from a mask and a value.
- Poll status flags with a timeout; read the manual for side effects of reading data and status registers.
- Pass the peripheral pointer into driver functions so the logic can be tested on a PC.
- Check the hardware limits (24-bit SysTick reload, APB clock frequencies) in code.
Ready for the quiz?
Next: predict register values, find the volatile and read-modify-write bugs and answer the interview questions.
2 Comments