Last active
July 17, 2016 22:26
-
-
Save Jacajack/f08863a0dfbf3714ef6794f2f456ab91 to your computer and use it in GitHub Desktop.
UART snippet for ATmega 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <avr/io.h> | |
#include <stdlib.h> | |
#include "../include/uart.h" | |
//Version for atmega8 | |
//Not used by default, just declared for user | |
char *uartBuffer; | |
void uartSendChar( char c ) | |
{ | |
//Send single byte through UART | |
//c - character to send | |
while ( !( UCSRA & ( 1 << UDRE ) ) ); | |
UDR = c; | |
} | |
char uartReadChar( ) | |
{ | |
//Receive and return single byte | |
//Returned value: received character | |
while ( !( UCSRA & ( 1 << RXC ) ) ); | |
return UDR; | |
} | |
void uartSend( const char *s ) | |
{ | |
//Send character word through UART | |
//s - pointer to string | |
size_t i = 0; | |
while ( s[i] ) | |
uartSendChar( s[i++] ); | |
} | |
void uartRead( char *buff, size_t bufferSize ) | |
{ | |
//Receive 10/13/0 terminated string and store it in buffer | |
size_t i = 0; | |
char c = 0; | |
for ( i = 0; i < bufferSize; i++ ) | |
{ | |
c = uartReadChar( ); | |
if ( c == 13 || c == 10 || c == 0 ) | |
{ | |
buff[i] = 0; | |
break; | |
} | |
buff[i] = c; | |
} | |
} | |
char uartBufferStatus( ) | |
{ | |
//Is uart input buffer empty? | |
return UCSRA & ( 1 << RXC ); | |
} | |
void uartInit( unsigned int baud ) | |
{ | |
//Init UART with given BAUD rate | |
//baud - baud rate | |
baud = F_CPU / 16 / baud - 1; | |
UBRRH = (unsigned char) ( baud >> 8 ); //Set BAUD rate | |
UBRRL = (unsigned char) baud; | |
UCSRB = ( 1 << RXEN ) | ( 1 << TXEN ); //Enable RX and TX | |
UCSRC = ( 1 << URSEL ) | ( 0 << USBS ) | ( 3 << UCSZ0 ); //Set data format | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef UART_H | |
#define UART_H | |
#include <stdlib.h> | |
extern void uartInit( unsigned int baud ); | |
extern void uartSendChar( char c ); | |
extern void uartSend( const char *s ); | |
extern char uartReadChar( ); | |
extern void uartRead( char *buff, size_t bufferSize ); | |
extern char uartStatus( ); | |
extern char *uartBuffer; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment