Skip to content

Instantly share code, notes, and snippets.

@lrvdijk
Created February 3, 2011 13:34
Show Gist options
  • Save lrvdijk/809467 to your computer and use it in GitHub Desktop.
Save lrvdijk/809467 to your computer and use it in GitHub Desktop.
USART non interrupt driven example
/**
* Voltmeter based on atmega168, sends Analog2Digital conversion
* results over RS232 to the connected computer
*
* Created by Lucas van Dijk
* http://www.return1.net
*/
#ifndef F_CPU
#define F_CPU 3686400
#endif
#define BAUDRATE 9600
#define UBRR (F_CPU/(BAUDRATE*16UL))-1
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#include <stdint.h>
void usart_init(uint16_t ubrr_value)
{
UBRRH = (unsigned char) (ubrr_value >> 8);
UBRRL = (unsigned char) ubrr_value;
// 9600-8-E-1
// That is, baudrate of 9600bps
// 8 databits
// Even parity
// 1 stopbit
UCSRB = (1 << TXEN) | (1 << RXEN);
UCSRC = (1 << URSEL) | (1 << UPM1) | (1 << UCSZ1) | (1 << UCSZ0);
}
void adc_init()
{
// Setup ADC
// Enable the ADC unit, and use a prescaler
// of 32 which gives us a fadc of 115kHz
ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS0);
}
char usart_receive()
{
// Wait until receive is complete
while(!(UCSRA & (1 << RXC)));
return UDR;
}
void usart_send(char data)
{
// Wait until receive is complete
while(!(UCSRA & (1 << UDRE)));
UDR = data;
}
void usart_send_string(char * str)
{
char current;
do
{
current = *str;
usart_send(current);
str++;
}
while(current != '\0');
}
int main()
{
// Setup USART
usart_init(UBRR);
// Setup ADC
adc_init();
// Enable interrupts
sei();
char data;
usart_send_string("Started");
while(1)
{
data = usart_receive();
usart_send(data); // echo commands
if(data == 'r')
{
// Start ADC Conversion
ADCSRA |= (1 << ADSC);
// Wait untill conversion is completed
while(!(ADCSRA & (1 << ADIF)));
// Convert ADC result to ASCII
// And send it through USART
char result[5];
uint16_t adc_value = ADC;
itoa(adc_value, result, 10);
// Reset ADC Flag
ADCSRA |= (1 << ADIF);
usart_send_string(result);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment