ATmega8a direct port register-3 led blink with button
Here is an example code for blinking two LEDs connected to pins 5 and 6 of PORTB and toggling their state using a button connected to pin 2 of PORTD using direct port registers on the ATmega8A microcontroller:
#include <avr/io.h>
#include <util/delay.h>
#define LED1_PIN 5 // define the pin number for the first LED
#define LED2_PIN 6 // define the pin number for the second LED
#define BUTTON_PIN 2 // define the pin number for the button
int main(void)
{
DDRB |= (1 << LED1_PIN) | (1 << LED2_PIN); // set LED pins as outputs
DDRD &= ~(1 << BUTTON_PIN); // set button pin as input
while(1) {
if(PIND & (1 << BUTTON_PIN)) { // check if the button is pressed
PORTB ^= (1 << LED1_PIN) | (1 << LED2_PIN); // toggle the state of both LEDs
_delay_ms(100); // wait for 100ms to debounce the button
}
}
return 0;
}
In this code, we first define the pin numbers for the two LEDs and the button using the #define
preprocessor directive. Then, we configure the LED pins and the button pin as outputs and inputs, respectively, using the DDRB and DDRD registers and the direct port register access method.
Next, we enter an infinite loop where we check if the button is pressed by reading the state of the PIND register and the button pin. If the button is pressed, we toggle the state of both LEDs using the XOR operator on the PORTB register and the LED pin numbers, which flips the value of the bits corresponding to the LED pins. We also add a short delay of 100ms to debounce the button and prevent false triggering due to mechanical bouncing.
Note that the PIND
is a predefined macro that represents the value of the PIND register, and ^=
is a shorthand operator that performs a bitwise XOR operation and updates the value of the variable. Also, you may need to add a pull-up resistor to the button pin to ensure that it is at a defined state when the button is not pressed.