#include <avr/interrupt.h>
#include <avr/io.h>
//from https://github.com/Devilbinder/ATMEGA328P_C/blob/master/examples/uart/uart/main.c
#include <util/delay.h>
#include <stdio.h>
#include <stdint.h>
#define RX_BUFFER_SIZE 128
volatile static uint8_t rx_buffer[RX_BUFFER_SIZE] = {0};
volatile static uint16_t rx_count = 0;
volatile static uint8_t uart_tx_busy = 1;
ISR(USART_RX_vect){
volatile static uint16_t rx_write_pos = 0;
rx_buffer[rx_write_pos] = UDR0;
rx_count++;
rx_write_pos++;
if(rx_write_pos >= RX_BUFFER_SIZE){
rx_write_pos = 0;
}
}
ISR(USART_TX_vect){
uart_tx_busy = 1;
}
int sputc(unsigned char c, FILE *file) //stderr and stdout are same
{
while(uart_tx_busy == 0);
uart_tx_busy = 0;
UDR0 = c;
return c;
}
void init_serial(uint32_t baud, uint8_t high_speed)
{
uint8_t speed = 16;
if(high_speed != 0){
speed = 8;
UCSR0A |= 1 << U2X0;
}
baud = (F_CPU/(speed*baud)) - 1;
UBRR0H = (baud & 0x0F00) >> 8;
UBRR0L = (baud & 0x00FF);
UCSR0B |= (1 << TXEN0) | (1 << RXEN0) | (1 << TXCIE0) | (1 << RXCIE0);
fdevopen(&sputc, 0); //for print only
sei();
}
int main()
{
init_serial(9600, 0);
DDRD |= _BV(6);
printf("%s","Hello, World!\n\0");
while(1)
{
PORTD |= _BV(6);
printf("%s","LED ON!\n\0");
_delay_ms(1000);
PORTD &= ~_BV(6);
printf("%s","LED OFF!\n\0");
_delay_ms(1000);
}
}