0
0
Embedded Cprogramming~5 mins

First embedded program (LED blink) in Embedded C

Choose your learning style9 modes available
Introduction

This program shows how to make an LED blink on and off. It helps you learn how to control hardware using code.

You want to test if your microcontroller board is working.
You want to learn how to control pins on a microcontroller.
You want to create a simple signal or indicator using an LED.
You want to understand timing and delays in embedded systems.
Syntax
Embedded C
#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    DDRB |= (1 << PB0); // Set pin PB0 as output
    while (1) {
        PORTB |= (1 << PB0);  // Turn LED on
        _delay_ms(500);       // Wait 500 milliseconds
        PORTB &= ~(1 << PB0); // Turn LED off
        _delay_ms(500);       // Wait 500 milliseconds
    }
    return 0;
}

DDRB sets the direction of pins on port B (output or input).

PORTB controls the voltage level on pins (high or low).

Examples
This sets pin PB0 as an output pin.
Embedded C
DDRB |= (1 << PB0);
This sets pin PB0 to high voltage, turning the LED on.
Embedded C
PORTB |= (1 << PB0);
This clears pin PB0 to low voltage, turning the LED off.
Embedded C
PORTB &= ~(1 << PB0);
This pauses the program for 500 milliseconds (half a second).
Embedded C
_delay_ms(500);
Sample Program

This program makes the LED connected to pin PB0 blink on and off every half second.

Embedded C
#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    DDRB |= (1 << PB0); // Set PB0 as output
    while (1) {
        PORTB |= (1 << PB0);  // LED on
        _delay_ms(500);       // Wait 500 ms
        PORTB &= ~(1 << PB0); // LED off
        _delay_ms(500);       // Wait 500 ms
    }
    return 0;
}
OutputSuccess
Important Notes

Make sure the LED is connected to the correct pin (PB0) with a resistor to avoid damage.

The _delay_ms() function needs the util/delay.h library.

This code runs forever because of the while(1) loop.

Summary

You learned how to set a pin as output and control it to blink an LED.

Delays help create visible blinking by pausing the program.

This is the first step to controlling hardware with embedded C.