/********
* This file is part of Tooltron.
*
* Tooltron is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Tooltron is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Lesser GNU General Public License for more details.
* You should have received a copy of the Lesser GNU General Public License
* along with Tooltron. If not, see .
*
* Copyright 2009 Kevin Woo
*
********/
/** @file uart.c
*
* @brief Implements UART functionality in hardware
*
* @author Kevin Woo (kwoo)
*/
#include "uart.h"
#include
#include
uint8_t received_byte; //Byte received
uint8_t byte_ready; //New byte has been received
void init_uart(uint16_t baud) {
// Set baud rate
UBRRH = (uint8_t)(baud>>8);
UBRRL = (uint8_t)baud;
// Enable RX/TX and RX/TX Interrupt
UCSRB = _BV(RXCIE) | _BV(RXEN) | _BV(TXCIE) | _BV(TXEN);
// Enable the TXEN pin as output
DDRD |= TX_EN;
// Initialize receive variables
byte_ready = 0;
received_byte = 0x0;
}
int8_t uart_get_byte(uint8_t *output_byte) {
if (byte_ready) {
byte_ready = 0;
*output_byte = received_byte;
return 0;
} else {
return -1;
}
}
void uart_send_byte(uint8_t data) {
//Waits until current transmit is done
while (!(UCSRA & _BV(UDRE)));
// Enable writes and send
uart_toggle_transmit(UART_TX_ON);
UDR = data;
return;
}
void uart_toggle_transmit(uint8_t state) {
if (state == UART_TX_ON) {
PORTD |= TX_EN;
} else {
PORTD &= ~TX_EN;
}
}
ISR(USART_RX_vect) {
received_byte = UDR;
byte_ready = 1;
}
ISR(USART_TX_vect) {
// Re-enable reads
uart_toggle_transmit(UART_TX_OFF);
}