ATtiny85 Template Code
Code snippets for the ATtiny85
 All Files Functions Variables Typedefs Enumerations Enumerator Macros
analog.c
Go to the documentation of this file.
1 /*--------------------------------------------------------------------------*
2 * Analog input helpers
3 *---------------------------------------------------------------------------*
4 * 15-Apr-2014 ShaneG
5 *
6 * These functions provide simple and accurate analog value reading.
7 *--------------------------------------------------------------------------*/
8 #include <avr/io.h>
9 #include "iohelp.h"
10 
20 void adcInit(ANALOG adc) {
21  // Make sure the ADC convertor is setup
22  ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
23  // Switch off digital for the appropriate pin
24  uint8_t mask, didr;
25  if(adc==ADC0) {
26  mask = 1 << PINB5;
27  didr = 1 << ADC0D;
28  }
29  else if(adc==ADC1) {
30  mask = 1 << PINB2;
31  didr = 1 << ADC1D;
32  }
33  else if(adc==ADC2) {
34  mask = 1 << PINB4;
35  didr = 1 << ADC2D;
36  }
37  else if(adc==ADC3) {
38  mask = 1 << PINB5;
39  didr = 1 << ADC3D;
40  }
41  else // ADC4 or invalid pin, just ignore it
42  return;
43  // Make sure the pin is an input and pull up is disabled
44  PORTB &= ~mask;
45  DDRB &= ~mask;
46  // Disable digital input for the pin
47  DIDR0 |= didr;
48  }
49 
61 uint16_t adcRead(ANALOG adc, uint8_t skip, uint8_t average) {
62  // Change the reference voltage and select input
63  uint8_t muxval = adc;
64  if(adc==ADC4) // Need 1.1V reference
65  muxval = 0x80 | adc;
66  ADMUX = muxval;
67  // Start the conversion
68  uint8_t count = skip + average;
69  uint16_t value, total = 0;
70  while(count) {
71  // Start the conversion, then wait for it to finish
72  ADCSRA |= (1 << ADSC);
73  while(ADCSRA & (1 << ADSC));
74  if(count<=average) {
75  // Read the current value and add it to the running total
76  value = ADCL;
77  value = value | (ADCH << 8);
78  total += value;
79  }
80  count--;
81  }
82  return (total / average);
83  }
84 
void adcInit(ANALOG adc)
Definition: analog.c:20
ADC1, PB2.
Definition: iohelp.h:66
ADC2, PB4.
Definition: iohelp.h:67
ADC3, PB3.
Definition: iohelp.h:68
ADC4 - internal temperature sensor.
Definition: iohelp.h:69
uint16_t adcRead(ANALOG adc, uint8_t skip, uint8_t average)
Definition: analog.c:61
ADC0, PB5.
Definition: iohelp.h:65
enum _ANALOG ANALOG