You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.8 KiB

8 years ago
  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. // Simple analog to digitial conversion
  17. #include <avr/io.h>
  18. #include <avr/pgmspace.h>
  19. #include <stdint.h>
  20. #include "analog.h"
  21. static uint8_t aref = (1<<REFS0); // default to AREF = Vcc
  22. void analogReference(uint8_t mode)
  23. {
  24. aref = mode & 0xC0;
  25. }
  26. // Arduino compatible pin input
  27. int16_t analogRead(uint8_t pin)
  28. {
  29. #if defined(__AVR_ATmega32U4__)
  30. static const uint8_t PROGMEM pin_to_mux[] = {
  31. 0x00, 0x01, 0x04, 0x05, 0x06, 0x07,
  32. 0x25, 0x24, 0x23, 0x22, 0x21, 0x20};
  33. if (pin >= 12) return 0;
  34. return adc_read(pgm_read_byte(pin_to_mux + pin));
  35. #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
  36. if (pin >= 8) return 0;
  37. return adc_read(pin);
  38. #else
  39. return 0;
  40. #endif
  41. }
  42. // Mux input
  43. int16_t adc_read(uint8_t mux)
  44. {
  45. #if defined(__AVR_AT90USB162__)
  46. return 0;
  47. #else
  48. uint8_t low;
  49. ADCSRA = (1<<ADEN) | ADC_PRESCALER; // enable ADC
  50. ADCSRB = (1<<ADHSM) | (mux & 0x20); // high speed mode
  51. ADMUX = aref | (mux & 0x1F); // configure mux input
  52. ADCSRA = (1<<ADEN) | ADC_PRESCALER | (1<<ADSC); // start the conversion
  53. while (ADCSRA & (1<<ADSC)) ; // wait for result
  54. low = ADCL; // must read LSB first
  55. return (ADCH << 8) | low; // must read MSB only once!
  56. #endif
  57. }