Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Last updated: Friday 13 November 2026 @ 17:29:40

Blink — from Arduino to Embedded C

Programming for Engineers

Blink with AVR-GCC

In this practical you will take the familiar Arduino Blink sketch and implement it directly in C using the ATmega328P's hardware registers. You will inspect the intermediate build files, upload firmware to the board and automate the workflow with a Makefile.

ATmega328PAVR-GCCRegistersIntel HEXAVRDUDEMake
Practical Checklist
Chapter checklist 0 / 6 completed

The standard Arduino sketch is concise because the Arduino core hides many hardware details.

void setup() {
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
}

Arduino's functions select and manipulate hardware registers on your behalf. With direct AVR C, you must explicitly select the appropriate pin, configure its direction, and set or clear its output state.

On a standard Arduino Uno, the built-in LED is connected to digital pin 13, which corresponds to PB5 (bit 5 of Port B) on the ATmega328P.

2. Create the embedded C project

  1. In Git Bash, create the project folder and move into it:

    mkdir -p ~/embeddedC/blink
    cd ~/embeddedC/blink
    pwd
  2. Create blink.c and open it in your editor:

    touch blink.c
    code blink.c
  3. Enter the following programme and save the file:

    #define F_CPU 16000000UL
    #include <avr/io.h>
    #include <util/delay.h>
    
    #define BLINK_DELAY_MS 2000
    
    int main(void) {
        // Configure PB5 (Arduino Uno D13) as an output.
        DDRB |= (1 << DDB5);
    
        while (1) {
            PORTB |= (1 << PORTB5);   // Set PB5: LED on.
            _delay_ms(BLINK_DELAY_MS);
    
            PORTB &= ~(1 << PORTB5);  // Clear PB5: LED off.
            _delay_ms(BLINK_DELAY_MS);
        }
    }
  4. Examine the two register operations used above:

    uint8_t value = 0b00000000;
    value |= (1 << 2);
    // Result: 0b00000100

    The |= operator combines the current value with a mask using bitwise OR. Only the targeted bit is set; other bits retain their values.

    uint8_t value = 0b00000100;
    value &= ~(1 << 2);
    // Result: 0b00000000

    The ~ operator inverts the mask; bitwise AND then clears only the selected bit. The initial value must have that bit set for the change to be visible.

3. Compile to an object file (.o)

The build process starts by compiling blink.c into machine code stored in a relocatable ELF object file. This is not yet the final firmware image.

  1. Compile the source for an ATmega328P:

    avr-gcc -Os -g -Wall -Wextra -mmcu=atmega328p -c blink.c -o blink.o
  2. Confirm that the object file was created:

    ls -lh blink.o
  3. Examine the generated instructions:

    avr-objdump -d -S blink.o
    Reading the AVR instructions

    The precise assembly and addresses depend on the compiler version and optimisation settings. Look for instructions such as:

    InstructionMeaning
    sbiSet a bit in an I/O register
    cbiClear a bit in an I/O register
    ldiLoad an immediate value into a register
    subi / sbciSubtract an immediate value, with or without carry
    brneBranch if the zero flag is clear (result not equal to zero)
    rjmpPerform a relative jump, often back to a loop
    nopExecute an instruction that performs no operation

    For the ATmega328P, DDRB is at I/O address 0x04 and PORTB at I/O address 0x05. Depending on optimisation, you may see sbi 0x04, 5 to configure the pin and sbi 0x05, 5 / cbi 0x05, 5 to switch the LED.

    A brne is a conditional branch; rjmp is an unconditional relative jump. Neither instruction is inherently an infinite delay. Together with arithmetic instructions, they may implement loop control or a busy-wait delay.

    For additional details, consult the Microchip AVR Instruction Set Manual.

Linking combines compiled objects with the required runtime/start-up code, resolves symbols and assigns final memory addresses. The result is an Executable and Linkable Format (ELF) file.

  1. Link the object into an executable:

    avr-gcc -Os -mmcu=atmega328p blink.o -o blink.elf
  2. Inspect the ELF sections and disassembly:

    avr-objdump -h blink.elf
    avr-objdump -d blink.elf
  3. Inspect the memory usage:

    avr-size -C --mcu=atmega328p blink.elf

5. Convert the ELF to Intel HEX (.hex)

Intel HEX is a text-based format describing bytes and their target addresses. It is commonly used when transferring firmware to AVR bootloaders or programmers.

  1. Generate the firmware file:

    avr-objcopy -O ihex -R .eeprom blink.elf blink.hex
  2. Inspect the start of the HEX file:

    head -n 10 blink.hex
  3. Optionally examine the programmed data with avr-objdump:

    avr-objdump -h -s blink.hex
    How an Intel HEX record is structured

    An Intel HEX line begins with : and uses hexadecimal fields of the form:

    :llaaaatt[dd...]cc
    FieldMeaning
    llNumber of data bytes
    aaaa16-bit address field
    ttRecord type (for example, 00 data or 01 end-of-file)
    ddData bytes
    ccChecksum

    Higher address ranges may be specified using additional record types. The byte values will vary across compiler and linker versions. In particular, do not assume that every four-byte grouping represents a complete AVR instruction: AVR instructions can be 16 or 32 bits long.

6. Upload firmware with avrdude

  1. Identify the USB serial port.

    Get-CimInstance Win32_SerialPort | Select-Object Name, DeviceID, Description

    Alternatively, check Device Manager → Ports (COM & LPT). Some USB-to-serial devices may not appear in the query above but are visible in Device Manager.

    ls /dev/ttyACM* /dev/ttyUSB* 2>/dev/null

    Check which device appears when the board is connected. Depending on your Linux distribution, serial-device permissions may also need configuration.

  2. Choose the appropriate avrdude.conf path and update the port:

    avrdude -C 'C:/ProgramData/arduino-ide-v2/Local/Arduino15/packages/arduino/tools/avrdude/8.0.0-arduino1/etc/avrdude.conf' -c arduino -p atmega328p -P COM6 -b 115200 -U flash:w:blink.hex:i
    avrdude -C 'C:/Users/YOURUSERNAME/AppData/Local/Arduino15/packages/arduino/tools/avrdude/8.0.0-arduino1/etc/avrdude.conf' -c arduino -p atmega328p -P COM6 -b 115200 -U flash:w:blink.hex:i

    Replace YOURUSERNAME and COM6 with values for your computer. These paths match the AVRDUDE version used in the preceding setup practical; confirm the directory if you have a different installed version.

    AVRDUDE arguments
    ArgumentPurpose
    -CConfiguration file for AVRDUDE
    -c arduinoArduino-compatible serial bootloader protocol
    -p atmega328pTarget microcontroller
    -P COM6Serial port (replace with your port)
    -b 115200Serial communication baud rate
    -U flash:w:blink.hex:iWrite Intel HEX data to programme flash

    The -U operation specifies memory:operation:file:format. Here flash is the memory, w means write and i selects Intel HEX input.

  3. Observe the upload and confirm that the built-in LED turns on for two seconds and off for two seconds, repeatedly.

    Manual firmware upload demonstration

7. Automate the build with a Makefile

Repeating three build commands manually becomes inconvenient. make reads a file named Makefile, applies dependency rules and rebuilds targets when their prerequisites have changed.

  1. Create a new file named exactly Makefile inside ~/embeddedC/blink:

    code Makefile
  2. Paste the following content. Recipe lines must begin with a real Tab character, not spaces:

    MCU := atmega328p
    CC := avr-gcc
    OBJCOPY := avr-objcopy
    AVRDUDE := avrdude
    CFLAGS := -Os -g -Wall -Wextra -mmcu=$(MCU)
    
    # University computer; replace this path on a personal machine.
    AVRDUDE_CONFIG := C:/ProgramData/arduino-ide-v2/Local/Arduino15/packages/arduino/tools/avrdude/8.0.0-arduino1/etc/avrdude.conf
    PORT := COM6
    BAUD := 115200
    
    .PHONY: all upload clean
    all: blink.hex
    
    blink.o: blink.c
    	$(CC) $(CFLAGS) -c $< -o $@
    
    blink.elf: blink.o
    	$(CC) $(CFLAGS) $< -o $@
    
    blink.hex: blink.elf
    	$(OBJCOPY) -O ihex -R .eeprom $< $@
    
    upload: blink.hex
    	$(AVRDUDE) -C "$(AVRDUDE_CONFIG)" -c arduino -p $(MCU) -P $(PORT) -b $(BAUD) -U flash:w:$<:i
    
    clean:
    	rm -f blink.o blink.elf blink.hex
  3. Build the firmware:

    make
  4. Upload the firmware:

    make upload
  5. Clean generated build files, then rebuild:

    make clean
    make

    Building Blink using Make

8. Review your build pipeline

1. Source

blink.c : readable C source code using AVR registers.

2. Object

blink.o : compiled, relocatable machine code.

3. Executable

blink.elf : linked code with assigned memory addresses.

4. Firmware

blink.hex : Intel HEX image uploaded to programme flash.