ADC ATmega8 - LM35

Discussion in 'Programmer's Corner' started by MohamedSaa3d, May 13, 2014.

  1. MohamedSaa3d

    Thread Starter New Member

    Feb 16, 2014
    13
    0
    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 :(! ?

    Code ( (Unknown Language)):
    1.  
    2. //####### Prototype Area #########
    3. #include <avr/io.h>
    4. #include <avr/interrupt.h>
    5. #include <util/delay.h>
    6. #define  F_CPU 1000000UL
    7.  
    8.  
    9. //####### Functions###############
    10.  
    11. void InitADC() ;
    12. uint16_t ReadADC() ;
    13.  
    14. int main(void)
    15. {
    16.     char segment[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F}; //7-Segment Numbers Codes in hexadecimal
    17.     DDRB=0xFF;//PORT B Output
    18.     DDRD=0xFF;//PORT D Output
    19.    
    20.     sei();
    21.     InitADC();
    22.    
    23.     while(1)
    24.     {
    25.  
    26.         // Temperature Calculations
    27.         uint8_t temp=ReadADC();
    28.         uint8_t first= temp/10;
    29.         uint8_t second= temp-first*10;
    30.        
    31.         PORTB=segment[first];//first digit
    32.         PORTD=segment[second];//last digit
    33.        
    34.         _delay_ms(250); //wait
    35.        
    36.         ADCSRA |= 1<<ADSC;
    37.     }
    38. }
    39.  
    40. void InitADC()  
    41. {
    42.     ADMUX=(1<<REFS0)|(1<<REFS1);// AREF=internal 2.56v
    43.    
    44.     ADCSRA=(1<<ADEN)|(1<<ADPS0)|(1<<ADPS1)|(1<<ADPS2);
    45. }
    46.  
    47. uint16_t ReadADC()
    48. {
    49.     //Select ADC Channel
    50.     ADMUX = 0xE0;
    51.  
    52.     //Start Single conversion
    53.     ADCSRA|=(1<<ADSC);
    54.  
    55.     //Wait for conversion to complete ADSC=0
    56.     while(!(ADCSRA & (1<<ADIF)));
    57.  
    58.     //Clear ADIF by writing one to it
    59.     ADCSRA|=(1<<ADIF);
    60.  
    61.     return(ADCH);
    62. }
    63.  
    64.  
    65. //   int (25/10) = 2  >> First
    66. //   25-2*10= 5 >> Second
    67. // 7-segment display >>  "First Second"
    68.  
     
  2. MrChips

    Moderator

    Oct 2, 2009
    12,449
    3,365
    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: May 13, 2014
  3. Shagas

    Active Member

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

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

    return value;
     
Loading...