diff options
Diffstat (limited to 'drivers/avr/analog.c')
| -rw-r--r-- | drivers/avr/analog.c | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/drivers/avr/analog.c b/drivers/avr/analog.c new file mode 100644 index 000000000..1ec38df75 --- /dev/null +++ b/drivers/avr/analog.c | |||
| @@ -0,0 +1,69 @@ | |||
| 1 | /* Copyright 2015 Jack Humbert | ||
| 2 | * | ||
| 3 | * This program is free software: you can redistribute it and/or modify | ||
| 4 | * it under the terms of the GNU General Public License as published by | ||
| 5 | * the Free Software Foundation, either version 2 of the License, or | ||
| 6 | * (at your option) any later version. | ||
| 7 | * | ||
| 8 | * This program is distributed in the hope that it will be useful, | ||
| 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| 11 | * GNU General Public License for more details. | ||
| 12 | * | ||
| 13 | * You should have received a copy of the GNU General Public License | ||
| 14 | * along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| 15 | */ | ||
| 16 | |||
| 17 | // Simple analog to digitial conversion | ||
| 18 | |||
| 19 | #include <avr/io.h> | ||
| 20 | #include <avr/pgmspace.h> | ||
| 21 | #include <stdint.h> | ||
| 22 | #include "analog.h" | ||
| 23 | |||
| 24 | |||
| 25 | static uint8_t aref = (1<<REFS0); // default to AREF = Vcc | ||
| 26 | |||
| 27 | |||
| 28 | void analogReference(uint8_t mode) | ||
| 29 | { | ||
| 30 | aref = mode & 0xC0; | ||
| 31 | } | ||
| 32 | |||
| 33 | |||
| 34 | // Arduino compatible pin input | ||
| 35 | int16_t analogRead(uint8_t pin) | ||
| 36 | { | ||
| 37 | #if defined(__AVR_ATmega32U4__) | ||
| 38 | static const uint8_t PROGMEM pin_to_mux[] = { | ||
| 39 | 0x00, 0x01, 0x04, 0x05, 0x06, 0x07, | ||
| 40 | 0x25, 0x24, 0x23, 0x22, 0x21, 0x20}; | ||
| 41 | if (pin >= 12) return 0; | ||
| 42 | return adc_read(pgm_read_byte(pin_to_mux + pin)); | ||
| 43 | #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) | ||
| 44 | if (pin >= 8) return 0; | ||
| 45 | return adc_read(pin); | ||
| 46 | #else | ||
| 47 | return 0; | ||
| 48 | #endif | ||
| 49 | } | ||
| 50 | |||
| 51 | // Mux input | ||
| 52 | int16_t adc_read(uint8_t mux) | ||
| 53 | { | ||
| 54 | #if defined(__AVR_AT90USB162__) | ||
| 55 | return 0; | ||
| 56 | #else | ||
| 57 | uint8_t low; | ||
| 58 | |||
| 59 | ADCSRA = (1<<ADEN) | ADC_PRESCALER; // enable ADC | ||
| 60 | ADCSRB = (1<<ADHSM) | (mux & 0x20); // high speed mode | ||
| 61 | ADMUX = aref | (mux & 0x1F); // configure mux input | ||
| 62 | ADCSRA = (1<<ADEN) | ADC_PRESCALER | (1<<ADSC); // start the conversion | ||
| 63 | while (ADCSRA & (1<<ADSC)) ; // wait for result | ||
| 64 | low = ADCL; // must read LSB first | ||
| 65 | return (ADCH << 8) | low; // must read MSB only once! | ||
| 66 | #endif | ||
| 67 | } | ||
| 68 | |||
| 69 | |||
