ADC to USART

Thread Starter

crazyengineer

Joined Dec 29, 2010
156
Okay, so I'm trying to transmit my ADC values to my computer using USART using an atmega48. However, when I used my serial monitoring program, I keep getting this output



Here's my code
Rich (BB code):
//	Includes and Defines

#define F_CPU 8000000UL
#define BAUD 9600
#define MUBRR (F_CPU/16/BAUD)-1
#include <avr/io.h>
#include <util/delay.h>







//	ADC Init

void ADC_INIT(void)
{
	ADMUX=(1<<REFS0); 
	ADCSRA=(1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); 
}










//	ADC Read

unsigned int ADC_READ(int channel)
{
	ADMUX=channel;
	ADCSRA |= (1<<ADSC);
	while(!(ADCSRA & (1<<ADIF)));
	ADCSRA|=(1<<ADIF);
   return(ADC);
}









//	Usart Init

void USART_INIT(unsigned int ubrr)
{
	UBRR0H = (unsigned char)(ubrr>>8);
	UBRR0L = (unsigned char)ubrr;
	/*Enable receiver and transmitter */
	UCSR0B = (1<<RXEN0)|(1<<TXEN0);
	/* Set frame format: 8data, 2stop bit */
	UCSR0C = (1<<USBS0)|(3<<UCSZ00);
}









//	Usart Transmit

void USART_Transmit( unsigned int data )
{
	while ( !( UCSR0A & (1<<UDRE0)));
	UDR0 = data;
	return;
}









//	Main

int main(void)
{
	ADC_INIT();
	USART_INIT(MUBRR);
	while(1)
	{
		USART_Transmit(ADC_READ(0));
		_delay_ms(1000);
	}
	
	return 0;
}
 
Last edited:

Markd77

Joined Sep 7, 2009
2,806
The serial terminal program will just display the ASCII character that the number corresponds to.
Try Realterm, it can display the actual number instead. It's a little buggy in places but full of features.
Or write a program like mine to display it:
 

Attachments

spinnaker

Joined Oct 29, 2009
7,830
I thought I don't need to since the function argument has an unsigned int .
You thought wrong. It is an integer number that you get from the analog port not BCD.

The easy but less efficient way is to use sprintf with the %d format. assuming your compiler supports it.

The more efficient but more difficult way is to turn it into BCD. Your compiler may or may not have a BCD function.

You could also display as hex characters. I think someone posted such a function in this forum not too long ago.


Also remember you are displaying some number that is just a representation of voltage. You are going to have to calculate the actual voltage based on the number of bits your analog input supports and the values in your voltage divider.
 
Top