Skip to content

Instantly share code, notes, and snippets.

@arn-ob
Created February 20, 2018 07:54
Show Gist options
  • Select an option

  • Save arn-ob/3f09e438823ea8b74405daeb9571035a to your computer and use it in GitHub Desktop.

Select an option

Save arn-ob/3f09e438823ea8b74405daeb9571035a to your computer and use it in GitHub Desktop.
Working ADC Code atmega8
/*
* ADC_TEST1.cpp
*
* Created: 2/20/2018 01:02:14 PM
* Author : Arnob
*/
#define F_CPU 12000000UL
#include <avr/io.h>
int adc_value; //Variable used to store the value read from the ADC converter
void adc_init(void){
ADCSRA |= ((1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0)); //16Mhz/128 = 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
}
int main(void){
DDRB |= (1<<PB0); //PB5/digital 13 is an output
adc_init();
while(1){ //The infinite loop
adc_value = read_adc(5); //Read the ADC value, really that's just it
if(adc_value > 500 && adc_value < 650) {
PORTB = 0xff; //If ADC value is above 512 turn led on
}
else if(adc_value > 700 && adc_value < 800) {
PORTB = 0xff; //If ADC value is above 512 turn led on
}
else {
PORTB = 0x00; //Else turn led off
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment