
|
Just a simple few notes to familiarise you with using the USART on the AVR. The USART of the AVR is simply the serial port. With a line driver chip, such as the MAX232, you can connect your AVR to any standard RS232 port, and have it chatting away with computers, modems, mobile phones, serial mice, etc. You could even get the UB232R module from FTDI, and have your AVR plugged into a USB port.
Code tested with AVR studio 4. Written in C You will need to ensure that you have included the AVR IO library: #include <avr/io.h>
First of all, you need to define your CPU speed at the top of your code (I here have defined my CPU speed as 8Mhz): #define F_CPU 8000000UL
Next, add in the following procedure. Don't forget to add the prototype. This chunk of code will set up the USART for 8 data bits, 1 stop bit. void init_usart(unsigned int baud)
{
// Setup serial I/O for communication
UBRRH = (unsigned char)(baud>>8);
UBRRL = (unsigned char)baud;
UCSRB = (1<<RXEN)|(1<<TXEN);
UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
}
Next, call the procedure from your code (ideally the beginning of your main procedure). You will need to pass the UBBR value as a parameter. The UBBR value is based on the baud rate you require, but also involves the CPU speed. The UBBR value can be calculated using this handy tool I made: http://www.josephn.net/app/avr_ubbr/ init_usart(23);
Now you can add the following two functions/procedures in, which allow you to send and receive data. Remember to declare them in your prototype section: void txbyte(unsigned char data)
{
while ( !( UCSRA & (1<<UDRE)) ); //Wait for empty slot to send data
UDR = data; //Send it
}
unsigned char rxbyte (void)
{
while ( !(UCSRA & (1<<RXC)) ); //Wait until there is a byte to be read from RX buffer
return UDR; //Get it
}
And that's it really. To wrap up, here is the entire lot: #include <avr/io.h>
#define F_CPU 8000000UL //Define crystal/RC osc frequency
void init_usart(unsigned int baud);
void txbyte(unsigned char data);
unsigned char rxbyte(void);
int main(void)
{
init_usart(15);
txbyte(rxbyte()); //Send back whatever we receive
}
void txbyte(unsigned char data)
{
while ( !( UCSRA & (1<<UDRE)) ); //Wait for empty slot to send data
UDR = data; //Send it
}
unsigned char rxbyte (void)
{
while ( !(UCSRA & (1<<RXC)) ); //Wait until there is a byte to be read from RX buffer
return UDR; //Get it
}
void init_usart(unsigned int baud)
{
// Setup serial I/O for communication
UBRRH = (unsigned char)(baud>>8);
UBRRL = (unsigned char)baud;
UCSRB = (1<<RXEN)|(1<<TXEN);
UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
}
|
Online SoundCloud Downloader, NEW!Download tracks posted on SoundCloud for free in high-quality MP3! SoundScrape.netUseful eBay Links |