Here's a nice library to enable easy access to the UART subsystem. For extra information, check out serialwisdom.

/**
Allows the use of the UART subsystem.
Author: hufw@msoe.edu
*/
#include <inttypes.h>		// Contains C99 data types
 
#include <avr/io.h>			// Contains port name definitions, etc.
#include "uart.h"
/**
Initialize the UART system
param:
	baud_rate - How fast of a baud rate to initialize with
*/
void uart_init(const uint16_t baud_rate)
{
	// enable receive and transmit
	UCSRB=1<<RXEN|1<<TXEN;
 
	// calculate baudrate stuff
	uint16_t timer = (F_CPU/(16L*baud_rate))-1;
	UBRRH = timer>>8;
	UBRRL = timer&0xff;
}
 
/**
Receive a byte through the UART
Blocks until a byte is received
returns: The byte that was received
*/
unsigned char uart_get()
{
	while(!(UCSRA&(1<<RXC)));
	return UDR;
}
 
/**
Send a byte through the UART
Blocks until the byte is send
param:
	data - The byte of data to send
*/
void uart_put(const unsigned char data)
{
	while(!(UCSRA&(1<<UDRE)));
	UDR=data;
}
 
void uart_put_uint8(const uint8_t num)
{
	if (num>=100)
		uart_put(num/100+0x30);
	if (num>=10)
		uart_put(num%100/10+0x30);
	uart_put(num%10+0x30);
}
 
/**
Send a string trough the uart
param:
	data - A null-terminated string to send
*/
void uart_put_string(const char data[])
{
	char* curchar=data;
	while (*curchar)
	{
		uart_put(*(curchar++));
	}
}
 
/**
Send a string, followed by a newline sequence, through the uart
param:
	data - A null-terminated string to send
*/
void uart_put_line(const char data[])
{
	char* curchar=data;
	while (*curchar)
	{
		uart_put(*(curchar++));
	}
	uart_put(13);	// CR
	uart_put(10);	// LF
}
ce2810/serial.txt · Last modified: 2010/03/09 20:55 (external edit)
 

This website is not owned or managed by the Milwaukee School of Engineering.

© 2003-2010 Dr. Christopher C. Taylor, et. al. • Office: L-343 • Phone: 277-7339 • npǝ˙ǝosɯ@ɹolʎɐʇ • -> RSS <-