ATtiny84 ADC

From wikipost

Here's a snippet of code to use the ADC from an ATtiny84 microcontroller. In this example, the code was written for a t84 (Atmel AVR ATtiny84), but with minimal adjustments this code should work on microcontrollers from the same family (such as the ATtiny25, ATtiny45, ATtiny24, ATtiny44 and ATiny85) as well.


void initADC()
{
  /* this function initialises the ADC 

        ADC Notes
	
	Prescaler
	
	ADC Prescaler needs to be set so that the ADC input frequency is between 50 - 200kHz.
	
	Example prescaler values for various frequencies
	
	Clock   Available prescaler values
   ---------------------------------------
	 1 MHz   8 (125kHz), 16 (62.5kHz)
	 4 MHz   32 (125kHz), 64 (62.5kHz)
	 8 MHz   64 (125kHz), 128 (62.5kHz)
	16 MHz   128 (125kHz)

   below example set prescaler to 16 for mcu running at 1MHz


  */

   ADMUX =
            (0 << REFS1) |     // Sets ref. voltage to Vcc, bit 1   
            (0 << REFS0) |     // Sets ref. voltage to Vcc, bit 0
            (0 << MUX5)  |     // use ADC1 for input (PA1), MUX bit 5
            (0 << MUX4)  |     // use ADC1 for input (PA1), MUX bit 4
            (0 << MUX3)  |     // use ADC1 for input (PA1), MUX bit 3
            (0 << MUX2)  |     // use ADC1 for input (PA1), MUX bit 2
            (0 << MUX1)  |     // use ADC1 for input (PA1), MUX bit 1
            (1 << MUX0);       // use ADC1 for input (PA1), MUX bit 0

  ADCSRA = 
            (1 << ADEN)  |     // Enable ADC 
            (1 << ADPS2) |     // set prescaler to 16, bit 2 
            (0 << ADPS1) |     // set prescaler to 16, bit 1 
            (0 << ADPS0);      // set prescaler to 16, bit 0 
			
  ADCSRB = 
            (1 << ADLAR);      // left shift result (for 8-bit values)
	//        (0 << ADLAR);      // right shift result (for 10-bit values)
}


int main( void ) 
{
  
  initADC();

  while(1)
  {

    ADCSRA |= (1 << ADSC);         // start ADC measurement
    while (ADCSRA & (1 << ADSC) ); // wait till conversion complete 

    if (ADCH > 128)
    {
      // ADC input voltage is more than half of VCC

    } else {

      // ADC input voltage is less than half of VCC

    }

  }

  return 0;
}


See also: