Being able to read values other than 0 or 1 can come in handy!
Here I am using the Attiny84 along with a 10K potentiometer. The two ends of the potentiometer are attached to GND and VCC and the middle pin is going to PA1 (ADC1). I have PA0, the ADC reference voltage pin I selected, connected to 5V. I have an LED on PB1 to display the treshold being crossed. I am running the microchip at 8MHz.
/*
* Attiny84 analog read.c
*
* Created: 19/01/28 2:20:06 PM
* Author : marrs
*/
#define F_CPU 8000000
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
ADMUX |= (1 << REFS0); // PA0 ref voltage
ADMUX = (0b11110000 & ADMUX) | PA1; // PA1 input select
ADCSRA |= (1 << ADPS2) | (1 << ADPS0); // set clock to 32 divisions for 8MHz
ADCSRA |= (1 << ADEN); /* enable ADC */
uint16_t adcValue; //16 bit variable because the ADC on the Attiny84 is 10 bits.
DDRB = 0b00000001; //LED on PB0
while (1)
{
ADCSRA |= (1 << ADSC); /* start conversion */
_delay_ms(1); //instead of waiting for ready flag
adcValue = ADC; /* store high byte into adcValue */
if (adcValue > 200)
{
PORTB = 0b00000001;
}
else
{
PORTB = 0b00000000;
}
_delay_ms(50);
}
return(0);
}
The only tricky part here for me (being a C newb!) was storing just the high byte of the ADC and understanding the size of data types relative to what is being stored inside of them. I couldn’t manage to read just ADCH or ADCL
Elliot Williams’ Make: AVR Programming came in handy for this project.
The result (the analog value from the potentiometer is in yellow, the green LED which is triggered is in green):