upload
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

analog.c 1.2KB

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