/* * uart.c * * Code for UART initalization and printf() setup using avr-libc. * See uart.h for additional information pertaining to the interface for this module. * * Last modified 2010-09-02 22:26 */ #include #include #include #include "uart.h" /* * This function waits for the UART's FIFO transmit buffer to become * empty (ready to accept another character), and then stuffs the character * to be sent into the output FIFO. * * In a perfect world, this function would not spin forever waiting for the * buffer to be ready, but would give up after the "correct" amount of time * and return an error instead. */ int put_uart_char(char c, FILE *fd) { while (!(UCSRA & _BV(UDRE))) ; UDR = c; // put character into UART's output buffer return 0; } /* * To initialize the UART for use with avr-libc's printf functions, * the UART's line and speed options must be set, then fdevopen() must be used to * establish put_uart_char() as the character output routine. The second parameter * to fdevopen() is for providing an input function, and is unsued here. */ void uart_init(void) { UCSRB |= _BV(TXEN) | _BV(RXEN) | _BV(RXCIE); // enable xmit, recv & recv interrupt UCSRC |= _BV(UCSZ1) | _BV(UCSZ0); // use 8-bit character size UBRRH = 0; UBRRL = 51; // set 9600 baud with a 8MHz clock fdevopen(&put_uart_char, NULL); SREG |= _BV(SREG_I); // enable global interrupts }