summaryrefslogtreecommitdiff
path: root/quantum/analog.c
diff options
context:
space:
mode:
authorJack Humbert <jack.humb@gmail.com>2015-10-26 14:49:46 -0400
committerJack Humbert <jack.humb@gmail.com>2015-10-26 14:49:46 -0400
commit46e7fb2d3ccd699c0a1b1fd9d02860b1f2a44141 (patch)
treef0b00f664ecdaf83e30f27baf20780eb5d91c39a /quantum/analog.c
parentff8d8a50dfbb8502003a5181878c54a71b8c57d5 (diff)
downloadqmk_firmware-46e7fb2d3ccd699c0a1b1fd9d02860b1f2a44141.tar.gz
qmk_firmware-46e7fb2d3ccd699c0a1b1fd9d02860b1f2a44141.zip
quantum separated
Diffstat (limited to 'quantum/analog.c')
-rw-r--r--quantum/analog.c53
1 files changed, 53 insertions, 0 deletions
diff --git a/quantum/analog.c b/quantum/analog.c
new file mode 100644
index 0000000000..49b84ee0e8
--- /dev/null
+++ b/quantum/analog.c
@@ -0,0 +1,53 @@
+// Simple analog to digitial conversion
+
+#include <avr/io.h>
+#include <avr/pgmspace.h>
+#include <stdint.h>
+#include "analog.h"
+
+
+static uint8_t aref = (1<<REFS0); // default to AREF = Vcc
+
+
+void analogReference(uint8_t mode)
+{
+ aref = mode & 0xC0;
+}
+
+
+// Arduino compatible pin input
+int16_t analogRead(uint8_t pin)
+{
+#if defined(__AVR_ATmega32U4__)
+ static const uint8_t PROGMEM pin_to_mux[] = {
+ 0x00, 0x01, 0x04, 0x05, 0x06, 0x07,
+ 0x25, 0x24, 0x23, 0x22, 0x21, 0x20};
+ if (pin >= 12) return 0;
+ return adc_read(pgm_read_byte(pin_to_mux + pin));
+#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
+ if (pin >= 8) return 0;
+ return adc_read(pin);
+#else
+ return 0;
+#endif
+}
+
+// Mux input
+int16_t adc_read(uint8_t mux)
+{
+#if defined(__AVR_AT90USB162__)
+ return 0;
+#else
+ uint8_t low;
+
+ ADCSRA = (1<<ADEN) | ADC_PRESCALER; // enable ADC
+ ADCSRB = (1<<ADHSM) | (mux & 0x20); // high speed mode
+ ADMUX = aref | (mux & 0x1F); // configure mux input
+ ADCSRA = (1<<ADEN) | ADC_PRESCALER | (1<<ADSC); // start the conversion
+ while (ADCSRA & (1<<ADSC)) ; // wait for result
+ low = ADCL; // must read LSB first
+ return (ADCH << 8) | low; // must read MSB only once!
+#endif
+}
+
+