Skip to content

Instantly share code, notes, and snippets.

@Jacajack
Created October 6, 2016 16:39
Show Gist options
  • Save Jacajack/047d0d00de401678729b0d19c8505e38 to your computer and use it in GitHub Desktop.
Save Jacajack/047d0d00de401678729b0d19c8505e38 to your computer and use it in GitHub Desktop.
UART snippet for atmega328p
#include <avr/io.h>
#include <stdlib.h>
#include <util/delay.h>
#include <inttypes.h>
#include "comm328p.h"
//Version for atmega328
uint8_t computc( uint8_t c )
{
//Send single byte through UART
//c - character to send
while ( !( UCSR0A & ( 1 << UDRE0 ) ) );
return UDR0 = c;
}
uint8_t comgetc( )
{
//Receive and return single byte
//Returned value: received character
unsigned int i = 0;
for ( i = 0; i < UART_TIMEOUT; i++ )
{
if ( UCSR0A & ( 1 << RXC0 ) )
return UDR0;
_delay_us( 1000000 / UART_BAUD * 10 );
}
return 0;
}
uint16_t computs( const char *s )
{
//Send character word through UART
//s - pointer to string
uint16_t i = 0;
while ( s[i] )
computc( s[i++] );
return i;
}
uint16_t comwrite( uint8_t *buff, uint16_t len )
{
//Send character word through UART
//s - pointer to string
size_t i = 0;
for ( i = 0; i < len; i++ )
computc( buff[i] );
return i;
}
uint16_t comread( char *buff, uint16_t bufflen )
{
uint16_t i = 0, j = 0;
for ( j = 0; j < UART_TIMEOUT; j++ )
{
if ( UCSR0A & ( 1 << RXC0 ) )
{
buff[i] = UDR0;
j = 0;
i += i + 1 >= bufflen ? 0 : 1;
}
_delay_us( 1000000 / UART_BAUD * 10 );
}
buff[i] = 0;
return i;
}
uint8_t comstatus( )
{
//Is uart input buffer empty?
return ( UCSR0A & ( 1 << RXC0 ) ) != 0;
}
void cominit( )
{
//Init UART with given BAUD rate
unsigned int baud = UART_BAUD;
baud = F_CPU / 16 / baud - 1;
UBRR0H = (unsigned char) ( baud >> 8 ); //Set BAUD rate
UBRR0L = (unsigned char) baud;
UCSR0B = ( 1 << RXEN0 ) | ( 1 << TXEN0 ); //Enable RX and TX
UCSR0C = ( 0 << USBS0 ) | ( 3 << UCSZ00 ); //Set data format
}
#ifndef UART_H
#define UART_H
#include <inttypes.h>
#ifndef UART_BAUD
#define UART_BAUD 9600
#warning Please define UART_BAUD value
#endif
#ifndef UART_TIMEOUT
#define UART_TIMEOUT 4
#warning Default UART_TIMEOUT value is 4
#endif
extern uint8_t computc( uint8_t c );
extern uint8_t comgetc( );
extern uint16_t computs( const char *s );
extern uint16_t comwrite( uint8_t *buff, uint16_t len );
extern uint16_t comread( char *buff, uint16_t bufflen );
extern uint8_t comstatus( );
extern void cominit( );
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment