diff options
Diffstat (limited to 'quantum/analog.c')
| -rw-r--r-- | quantum/analog.c | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/quantum/analog.c b/quantum/analog.c new file mode 100644 index 000000000..49b84ee0e --- /dev/null +++ b/quantum/analog.c | |||
| @@ -0,0 +1,53 @@ | |||
| 1 | // Simple analog to digitial conversion | ||
| 2 | |||
| 3 | #include <avr/io.h> | ||
| 4 | #include <avr/pgmspace.h> | ||
| 5 | #include <stdint.h> | ||
| 6 | #include "analog.h" | ||
| 7 | |||
| 8 | |||
| 9 | static uint8_t aref = (1<<REFS0); // default to AREF = Vcc | ||
| 10 | |||
| 11 | |||
| 12 | void analogReference(uint8_t mode) | ||
| 13 | { | ||
| 14 | aref = mode & 0xC0; | ||
| 15 | } | ||
| 16 | |||
| 17 | |||
| 18 | // Arduino compatible pin input | ||
| 19 | int16_t analogRead(uint8_t pin) | ||
| 20 | { | ||
| 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; | ||
| 29 | return adc_read(pin); | ||
| 30 | #else | ||
| 31 | return 0; | ||
| 32 | #endif | ||
| 33 | } | ||
| 34 | |||
| 35 | // Mux input | ||
| 36 | int16_t adc_read(uint8_t mux) | ||
| 37 | { | ||
| 38 | #if defined(__AVR_AT90USB162__) | ||
| 39 | return 0; | ||
| 40 | #else | ||
| 41 | uint8_t low; | ||
| 42 | |||
| 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! | ||
| 50 | #endif | ||
| 51 | } | ||
| 52 | |||
| 53 | |||
