#include <avr/io.h>
#include <util/delay.h>
// Define the button pin
#define BUTTON_PIN 2
// Define the LED pin
#define LED_PIN 5 // Corresponds to pin D5 on Arduino Uno
// Initialize UART communication at 9600 baud rate
void uart_init() {
UBRR0H = 0;
UBRR0L = 103; // Baud rate 9600 at 16MHz
UCSR0B |= (1 << TXEN0); // Enable transmitter
UCSR0C |= (1 << UCSZ01) | (1 << UCSZ00); // 8-bit data format
}
// Transmit a character via UART
void uart_transmit(unsigned char data) {
while (!(UCSR0A & (1 << UDRE0))); // Wait for the transmit buffer to be empty
UDR0 = data; // Put data into buffer, sends the data
}
// Setup function
void setup() {
// Set D2 pin as input
DDRD &= ~(1 << DDD2);
// Enable pull-up resistor for D2 pin
PORTD |= (1 << PORTD2);
// Initialize UART
uart_init();
}
// Main function
int main(void) {
// Setup function
setup();
// Variable to store the previous state of the button
int previousState = 1;
// Loop forever
while (1)
{
// Read the current state of the button
int currentState = (PIND & (1 << PIND2)) ? 1 : 0;
// Check if the button state has changed since the last time it was read
if (currentState != previousState) {
// If the button state has changed
_delay_ms(10); // Delay for debounce
if (currentState == (PIND & (1 << PIND2))) { // Check if the button state is stable
// If the button is pressed (current state is LOW)
if (currentState == 0) {
// Toggle the LED state
//PORTD ^= (1 << PORTD5);
// Transmit message over UART
uart_transmit('1');
}
}
}
// Update the previous state to the current state
previousState = currentState;
//uart_transmit('0');
}
return 0;
}