1 // Simple analog to digitial conversion
4 #include <avr/pgmspace.h>
9 static uint8_t aref = (1<<REFS0); // default to AREF = Vcc
12 void analogReference(uint8_t mode)
18 // Arduino compatible pin input
19 int16_t analogRead(uint8_t pin)
21 #if defined(__AVR_ATmega32U4__)
22 static const uint8_t PROGMEM pin_to_mux[] = {
23 0x00, 0x01, 0x04, 0x05, 0x06, 0x07,
24 0x25, 0x24, 0x23, 0x22, 0x21, 0x20};
25 if (pin >= 12) return 0;
26 return adc_read(pgm_read_byte(pin_to_mux + pin));
27 #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
28 if (pin >= 8) return 0;
36 int16_t adc_read(uint8_t mux)
38 #if defined(__AVR_AT90USB162__)
43 ADCSRA = (1<<ADEN) | ADC_PRESCALER; // enable ADC
44 ADCSRB = (1<<ADHSM) | (mux & 0x20); // high speed mode
45 ADMUX = aref | (mux & 0x1F); // configure mux input
46 ADCSRA = (1<<ADEN) | ADC_PRESCALER | (1<<ADSC); // start the conversion
47 while (ADCSRA & (1<<ADSC)) ; // wait for result
48 low = ADCL; // must read LSB first
49 return (ADCH << 8) | low; // must read MSB only once!