Home / Learn Embedded C / Writing a Hardware Register

Writing a Hardware Register

How a control register's bits are written in real embedded C.

The gistHow a control register's bits are written in real embedded C.

The idea, explained simply

The basic idea

Writing a hardware register means storing a value at its fixed memory address, which hardware observes and reacts to immediately (unlike writing a normal variable, which only your own code ever reads).

Why this comes up

Enabling a peripheral, starting an ADC conversion, or turning on a GPIO pin are all, underneath any friendly library function, exactly one register write.

The mechanics

In real C: CONTROL_REG |= ENABLE_BIT; both computes the new value AND immediately tells the hardware about it — the moment that line executes, real pins or peripherals can change state.

Where it is used

  • Peripheral enable/disable
  • Starting conversions/transfers
  • GPIO output control

Try it

Simulating turning a peripheral on via a control registerC: edit and run

This single |= line is, underneath any driver library, what actually turns real hardware on.

Careful:As in the previous lesson, this course's sandbox simulates "the register" with a plain variable; the bitwise technique is identical to the real thing, only the physical memory address is missing.
Writing a real memory-mapped control register (reference only — not runnable in this sandbox)
#define CONTROL_REG (*(volatile unsigned int*)0x40001004)
#define ENABLE_BIT  (1 << 0)

CONTROL_REG |= ENABLE_BIT;  /* hardware reacts to this immediately */

Try it: writing several control bits in sequence

Starting, then stopping, a simulated peripheralC: edit and run

Each write immediately affects real hardware state in a true register — here, STOP clears just the START bit while ENABLE stays on.

Quick check

1. What is different about writing a hardware register compared to writing a normal C variable?