🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

The embedded C bridge: registers, bit masks and volatile

See why C is the language of choice on microcontrollers; set, clear, toggle and read register bits with bit masks; learn why volatile and fixed-width types matter, and get ready for the Proteus course.

Everything you've learned in this course is used to control real hardware inside a microcontroller. Turning on the LED on pin 13 of an Arduino Uno really means setting a single bit of a byte that sits at a specific address in memory. In this final lesson we'll bring pointers, bitwise operators and fixed-width types together and look at the core patterns of embedded C.

Why C on a microcontroller?

  • Direct access to hardware: with pointers you can read and write any address, and registers are just addresses.
  • Small, predictable code: It runs even in a few KB of flash and a few hundred bytes of RAM.
  • A compiler everywhere: avr-gcc for AVR, Microchip's XC8 compiler for PIC, arm-none-eabi-gcc for ARM Cortex-M… Manufacturers' register definition files and example code also come in C.
  • What about Arduino? Arduino sketches are technically C++ and are still compiled with GCC behind the scenes. But functions like digitalWrite contain exactly the register operations you'll see in this lesson; you can write the same C code inside a sketch too.

A register is an address in memory

On the ATmega328P, the PORTB register, which holds the outputs of port B, is at address 0x25 in data memory. Each bit of this byte corresponds to a pin: bit 5 is pin 13 of the Arduino Uno (PB5). In C, access to such a register is essentially defined like this:

#define PORTB (*(volatile uint8_t *)0x25)

Read this line from the inside out: interpret the number 0x25 as "the address of a uint8_t", then use * to reach the byte at that address. avr-libc defines it with its own macros, but the result is the same. From now on, anything you write to PORTB goes straight to the hardware.

Four basic bit patterns

When you change one bit of a register, you must not touch the other seven: they are other LEDs, relays or settings. There are four patterns to memorise for this. Let's try them on the computer with a variable:

#include <stdio.h>
#include <stdint.h>

#define BIT(n) (1u << (n))

static void yazdir(const char *islem, uint8_t reg) {
    printf("%-14s 0x%02X  ", islem, reg);
    for (int i = 7; i >= 0; i--) {
        putchar((reg & BIT(i)) ? '1' : '0');
    }
    putchar('\n');
}

int main(void) {
    uint8_t portb = 0x00;            // PC'de register yerine degisken

    portb |= BIT(5);                 yazdir("Bit 5 kur", portb);
    portb |= BIT(0) | BIT(1);        yazdir("Bit 0,1 kur", portb);
    portb &= (uint8_t)~BIT(5);       yazdir("Bit 5 sil", portb);
    portb ^= BIT(3);                 yazdir("Bit 3 ters", portb);

    printf("Bit 3 durumu: %u\n", (portb >> 3) & 1u);
    return 0;
}
Bit 5 kur      0x20  00100000
Bit 0,1 kur    0x23  00100011
Bit 5 sil      0x03  00000011
Bit 3 ters     0x0B  00001011
Bit 3 durumu: 1
JobPatternWhy it works
Set (make 1)reg |= (1u << n);x | 1 = 1, x | 0 = x
Clear (make 0)reg &= ~(1u << n);In the inverted mask only bit n is 0; x & 0 = 0, x & 1 = x
Togglereg ^= (1u << n);x ^ 1 = its inverse, x ^ 0 = x
Read(reg >> n) & 1uShifts bit n to the far right and masks off the rest

~BIT(5) is an unsigned int (0xFFFFFFDF); the (uint8_t) cast in front prevents a "value truncated" warning that strict warning settings may produce.

On real hardware: AVR and PIC

The code below runs not on a computer but on an ATmega328P. It is compiled with avr-gcc -mmcu=atmega328p -Os, flashed to the board, and blinks the LED on pin 13 every half second:

#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    DDRB |= (1 << DDB5);          // PB5 (Arduino pin 13) cikis
    while (1) {
        PORTB ^= (1 << PORTB5);   // LED'i ters cevir
        _delay_ms(500);
    }
}

DDRB sets the pin direction (1 = output), PORTB sets the output level. Notice that main never ends, thanks to the endless while (1) loop: on a microcontroller there's no operating system to return to. On the PIC side, for example on PIC18 models that have a LAT register, the same job is done with XC8 using bit-field names:

#include <xc.h>

void led_hazirla(void) {
    TRISBbits.TRISB0 = 0;   // RB0 cikis
    LATBbits.LATB0 = 1;     // LED yak
}

Configuration bits and delay settings vary with the model and compiler version, so we've shown only the register part here.

volatile: telling the compiler "this value may change on its own"

To speed code up, the compiler may read a variable once and keep it inside the processor. If the variable is changed by an interrupt function or by hardware, the main loop may never see the change:

#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t buton_basildi = 0;

ISR(INT0_vect) {                  // butona basilinca calisir
    buton_basildi = 1;
}

int main(void) {
    DDRB |= (1 << DDB5);
    EICRA |= (1 << ISC01);        // dusen kenarda kesme
    EIMSK |= (1 << INT0);         // INT0 kesmesini ac
    sei();                        // kesmelere genel izin

    while (1) {
        if (buton_basildi) {
            buton_basildi = 0;
            PORTB ^= (1 << PORTB5);
        }
    }
}

Without volatile, with optimisation turned on, the compiler may decide "nobody writes this variable inside the loop", move the check out of the loop, and the LED never changes. The rule: variables shared with interrupts, and hardware registers, must be volatile.

Fixed-width types and the 16-bit int trap

On AVR, int is 16 bits. When converting a 10-bit ADC value to millivolts, the product adc * 5000 comes to 2 560 000 for 512 and doesn't fit in 32767; the result is corrupted. Because int is 32 bits on a computer, this bug is invisible there and only shows up once you flash the board. The fix is to make the intermediate result explicitly 32 bits:

#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint16_t ornekler[3] = {0, 512, 1023};

    for (int i = 0; i < 3; i++) {
        uint32_t mv = (uint32_t)ornekler[i] * 5000u / 1023u;
        printf("ADC %4u -> %4lu mV\n", (unsigned)ornekler[i], (unsigned long)mv);
    }
    return 0;
}
ADC    0 ->    0 mV
ADC  512 -> 2502 mV
ADC 1023 -> 5000 mV

We used integers on purpose: AVR has no hardware floating-point unit; float operations are done in software, which is slow and takes up flash space.

Common mistakes

Writing = instead of |=: PORTB = (1 << 5); sets bit 5 but clears the other seven bits; other LEDs and relays on the same port switch off without warning.

  • Forgetting the ~ when clearing: reg &= (1 << n); clears everything except bit n; the exact opposite of what you wanted.

Exercise

In an 8-bit sensor control register, bits 4-6 hold the "gain" setting (0-7). Write kazanc_oku to read this field and kazanc_yaz to write it, without touching the other bits. With the register at 0xA3, read the gain, set it to 5 and read it again.

Hint: the field mask is 0x07 << 4 = 0x70. When writing, first clear the field with the mask, then shift the new value into place and OR it in.

Solution

#include <stdio.h>
#include <stdint.h>

#define KAZANC_KAYMA 4
#define KAZANC_MASKE (0x07u << KAZANC_KAYMA)

uint8_t kazanc_oku(uint8_t reg) {
    return (uint8_t)((reg & KAZANC_MASKE) >> KAZANC_KAYMA);
}

uint8_t kazanc_yaz(uint8_t reg, uint8_t deger) {
    reg &= (uint8_t)~KAZANC_MASKE;
    reg |= (uint8_t)((deger << KAZANC_KAYMA) & KAZANC_MASKE);
    return reg;
}

int main(void) {
    uint8_t kontrol = 0xA3;
    printf("Once : 0x%02X, kazanc=%u\n", kontrol, kazanc_oku(kontrol));
    kontrol = kazanc_yaz(kontrol, 5);
    printf("Sonra: 0x%02X, kazanc=%u\n", kontrol, kazanc_oku(kontrol));
    return 0;
}
Once : 0xA3, kazanc=2
Sonra: 0xD3, kazanc=5

What's next? The Proteus course

Even without a board there's a way to try this code. In the Proteus course on this site you'll draw the circuit on your computer, load the .hex file produced by avr-gcc or XC8 into a virtual ATmega328P or PIC, and watch the LED blink and the button interrupt work on screen.

Congratulations: from printf to register masks, you've completed the foundations of C. Next stop: the Proteus course.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. Which expression clears only bit 3 of a register without touching the other bits?
2. Why should a global variable changed inside an interrupt function (ISR) be declared volatile?
3. How many bits wide is the int type on the ATmega328P (Arduino Uno)?

Mark it when you finish: your progress is saved and you earn +20 XP.

// Final exam and certificate

20 random questions from the lessons, 30 minutes, pass mark 70%. If you pass, you get a verifiable certificate of achievement (with a QR code).

Take the final exam

Tip: ← → keys let you move between lessons.