ADC ATmega8 - LM35

Thread Starter

MohamedSaa3d

Joined Feb 16, 2014
13
Hii ..
i have a problem in my code below .. that i can't read the ADC value from the ADC ( or ADCW ) register but when i read the ADCH it works fine :(! ?

Rich (BB code):
//####### Prototype Area ######### 
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#define  F_CPU 1000000UL


//####### Functions###############

void InitADC() ; 
uint16_t ReadADC() ;

int main(void)
{
	char segment[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F}; //7-Segment Numbers Codes in hexadecimal
	DDRB=0xFF;//PORT B Output
	DDRD=0xFF;//PORT D Output
	
	sei();
	InitADC();
	
	while(1)
	{

		// Temperature Calculations 
		uint8_t temp=ReadADC(); 
		uint8_t first= temp/10;
		uint8_t second= temp-first*10;
		
		PORTB=segment[first];//first digit
		PORTD=segment[second];//last digit
		
		_delay_ms(250); //wait
		
		ADCSRA |= 1<<ADSC;
	}
}

void InitADC()  
{
	ADMUX=(1<<REFS0)|(1<<REFS1);// AREF=internal 2.56v
	
	ADCSRA=(1<<ADEN)|(1<<ADPS0)|(1<<ADPS1)|(1<<ADPS2);
} 

uint16_t ReadADC()
{
	//Select ADC Channel
	ADMUX = 0xE0;

	//Start Single conversion
	ADCSRA|=(1<<ADSC);

	//Wait for conversion to complete ADSC=0
	while(!(ADCSRA & (1<<ADIF)));

	//Clear ADIF by writing one to it
	ADCSRA|=(1<<ADIF);

	return(ADCH);
}


//   int (25/10) = 2  >> First
//   25-2*10= 5 >> Second
// 7-segment display >>  "First Second"
 

MrChips

Joined Oct 2, 2009
30,823
ADC and ADCW are probably not defined addresses.

If ADCH works, why worry?

Note that it is up to the compiler to generate the correct sequence of 8-bit access when trying to access 16-bit registers.

You could examine the disassembled code and see what asm code is generated. Post it here for my interest.
 
Last edited:

Shagas

Joined May 13, 2013
804
Try reading the ADC register before clearing the ADCSRA|=(1<<ADIF); flag

uint8_t value = ADC;
ADCSRA|=(1<<ADIF);

return value;
 
Top