ATmega8a direct port register-2 led blink

Here’s an example code for blinking an LED using the direct port registers of the ATmega8A microcontroller:

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

#define LED_PIN 5 // define the pin number for the LED

int main(void)
{
  DDRB |= (1 << LED_PIN); // configure the LED pin as an output

  while (1)
  {
    PORTB |= (1 << LED_PIN); // turn on the LED
    _delay_ms(500); // wait for 500 milliseconds
    PORTB &= ~(1 << LED_PIN); // turn off the LED
    _delay_ms(500); // wait for 500 milliseconds
  }
}

In this code, we first define the LED pin as LED_PIN and set it to 5, assuming that the LED is connected to pin 5 of PORTB.

Next, we configure the LED pin as an output by setting bit 5 of the DDRB register to 1 using the direct port register access method we discussed earlier.

Then, we enter an infinite loop that toggles the state of the LED every 500 milliseconds using the PORTB register. First, we turn on the LED by setting bit 5 of the PORTB register to 1, and then we wait for 500 milliseconds using the _delay_ms() function from the util/delay.h library. After that, we turn off the LED by clearing bit 5 of the PORTB register to 0, and wait for another 500 milliseconds before repeating the process.

Note that the _delay_ms() function takes the delay time in milliseconds as an argument and is used to create a delay between the LED on and off states. Also, don’t forget to include the avr/io.h and util/delay.h header files in your program for the I/O and delay functions to work.

Leave a Reply