led-controller/src/uart.c

42 lines
1.1 KiB
C

#include <stdint.h> /* Standard Integer Types */
#include <stdio.h> /* Standard IO facilities */
#include <stdlib.h> /* General utilities */
#include <avr/io.h> /* AVR device-specific IO definitions */
#include "uart.h"
#include <util/setbaud.h> /* Helper macros for baud rate calculations */
FILE uart_output = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);
FILE uart_input = FDEV_SETUP_STREAM(NULL, uart_getchar, _FDEV_SETUP_READ);
FILE uart_io = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
/* configure serial port */
void uart_init(void)
{
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
#if USE_2X
UCSR0A |= (1<<U2X0);
#else
UCSR0A &= ~(1<<U2X0);
#endif
UCSR0C = (1<<UCSZ01)|(1<<UCSZ00); /* 8N1 bit data */
UCSR0B = (1<<RXEN0)|(1<<TXEN0); /* enable RX and TX */
UCSR0B |= (1<<RXCIE0); /* enable RX complete interrupt */
}
void uart_putchar(char c, FILE *stream)
{
if (c == '\n') {
uart_putchar('\r', stream);
}
loop_until_bit_is_set(UCSR0A, UDRE0);
UDR0 = c;
}
char uart_getchar(FILE *stream)
{
loop_until_bit_is_set(UCSR0A, RXC0); /* Wait until data exists. */
return UDR0;
}