While trying to figure out how to use the ADC on my AVR microcontrollers (not Arduino, raw AVRs!), I kept finding a variety of tutorials with examples that just didn’t work for me. I eventually got it working, so thought I would share, hoping it would help someone else eventually!
I am using an ATmega32U4 (awesome chip!), but these steps should be appropriate for most AVRs. Note that my clock is running at 8 MHz. If you change the clock speed, make sure to change the prescalar value.
ADCSRA |= (1 << ADPS2) | (1 << ADPS1); // prescalar = 64 ADMUX |= (1 << REFS0); // reference voltage from internal source ADMUX |= (1 << ADLAR); // 8 bits, instead of 10 ADCSRA |= (1 << ADATE); // free running ADCSRA |= (1 << ADEN); // enable ADC ADCSRA |= (1 << ADSC); // start A2D conversions
Note that this code works for a continuously running, non-interrupt driven ADC program. If you want to use single shot conversions or interrupt driven ADC, you will need to change these lines appropriately. I might add that as another post eventually.