Solved: Temperature reading through ADC

Go To Last Post
2 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi,

 

I'm working on a project where I have connected the temperature sensor(LM35) to ADC0(23rd PIN) of ATMEGA168.  I get the ADC value and push it through UART. I use coolterm to view the data. The relevant code and an image of serial terminal  is below. I have set the correct baud rate but do not know why I get the value 80 in the terminal inspite of varying temperature.

#define F_CPU 8000000

#include <avr/io.h>
#include <stdlib.h>
#include <util/delay.h>

#define BAUDRATE 9600
#define BAUD_PRESCALLER F_CPU/16/BAUDRATE-1

uint16_t adc_value; //Variable used to store the value read from the ADC
char buffer[5]; //Output of the itoa function

void adc_init(void); //Function to initialize/configure the ADC
uint16_t read_adc(uint8_t channel); //Function to read an arbitrary analog channel/pin
void USART_init(unsigned int ubrr);//Function to initialize and configure the USART/serial
void USART_send( unsigned char data);   //Function that sends a char over the serial port
void USART_putstring(char* StringPtr);   //Function that sends a string over the serial port

int main(void){
 adc_init(); //Setup the ADC
 USART_init(BAUD_PRESCALLER); //Setup the USART

 while(1) //Our infinite loop
 {
 USART_putstring("Reading channel 0: ");
 adc_value = read_adc(0);
 itoa(adc_value, buffer, 10);
 USART_putstring(buffer);
 USART_putstring("  ");
 _delay_ms(500);
 USART_send('\r');
 USART_send('\n');                //This two lines are to tell to the terminal to change line
 }
 return 0;
}

void adc_init(void){
 ADCSRA |= ((1<<ADPS2)|(1<<ADPS1)|(0<<ADPS0));   // 8Mhz/64 = 125Khz the ADC reference clock
 ADMUX |= (1<<REFS0); // Voltage reference from Avcc (5v)
 ADCSRA |= (1<<ADEN); // Turn on ADC
 ADCSRA |= (1<<ADSC); // Do an initial conversion because this one is the slowest and to ensure that everything is up and running
}

uint16_t read_adc(uint8_t channel){
 ADMUX &= 0xF0; // Clear the older channel that was read
 ADMUX |= channel; // Defines the new ADC channel to be read
 ADCSRA |= (1<<ADSC); // Starts a new conversion
 while(ADCSRA & (1<<ADSC)); // Wait until the conversion is done
 return ADCW; // Returns the ADC value of the chosen channel
}

void USART_init(unsigned int ubrr){

    /* Set baud rate */
     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 = 3<<UCSZ00;
}

void USART_send( unsigned char data){

 while(!(UCSR0A & (1<<UDRE0)));
 UDR0 = data;

}

void USART_putstring(char* StringPtr){

 while(*StringPtr != 0x00){
 USART_send(*StringPtr);
 StringPtr++;}

}

Last Edited: Wed. Dec 19, 2018 - 12:52 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The problem was with the controller that I was using. After I changed the controller I got the output.