Saturday, July 9, 2016

INTERFACING ADC OF AVR MICROCONTROLLER

The following is the code for using the internal 10 bit ADC of AVR microcontroller.
The code is written for ATMEGA328 with system clock of 16MHZ.
The code uses standard c header files for using printf function and then print the content in serial uart of the microcontroller.



By default %f will not work on work, following things should be adjusted for this in project properties.
You just have to check the last option (use vprintf library) in your project properties.



#define F_CPU 16000000

#include <avr/io.h>
#include <stdint.h>
#include <stdio.h>
#include <util/delay.h>
#define USART_BAUDRATE 9600
#define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
#define ADC_PIN 5
#define LED_PIN PORTB5
#define ADC_THRESHOLD 512

void USART0Init(void){
UBRR0H = (uint8_t)(UBRR_VALUE>>8);
UBRR0L = (uint8_t)UBRR_VALUE;
UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
UCSR0B |= (1<<RXEN0)|(1<<TXEN0);
}

int USART0SendByte(char u8Data, FILE *stream){
if(u8Data == '\n') {
USART0SendByte('\r', stream);
}
while(!(UCSR0A&(1<<UDRE0))){};
UDR0 = u8Data;
return 0;
}

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

FILE usart0_str = FDEV_SETUP_STREAM(USART0SendByte, NULL, _FDEV_SETUP_WRITE);

uint16_t adc_read(uint8_t adcx) {
ADMUX &= 0xf0;
ADMUX |= adcx;
ADCSRA |= (1<<ADSC);
while ( (ADCSRA & (1<<ADSC)) );
return ADC;
}

int main(void) {
int a;
float v;
adc_init();
USART0Init();

DDRB  |= (1<<LED_PIN);
stdout=&usart0_str;

for (;;) {
a = adc_read(ADC_PIN);
v =( 5/1024.0 )*a;


printf("Digital value is %u\n",a);
printf("Voltage value = %f V\n",v);

if (a > ADC_THRESHOLD)
PORTB |= (1<<LED_PIN);
else
PORTB &= ~(1<<LED_PIN);
_delay_ms(1000);
    }


}

3 comments:


  1. Thanks for sharing this valuable information and we collected some information from this blog.
    Microcontroller Training in Noida

    ReplyDelete
  2. Data science is the analysis of where data comes from, what it signifies and how it very well may be turned into a valuable and important resource in the creation of business and IT strategies. Data science is a multidisciplinary blend of data inference, algorithm development, and technology so as to solve diagnostically complex problems. It is the field of Big Data which seeks to provide meaningful data from large measures of complex data.
    For More Info: Data Science Course in Gurgaon

    ReplyDelete