Advertisement
Guest User

Untitled

a guest
May 3rd, 2016
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. int analogRead(uint8_t pin)
  2. {
  3. uint8_t low, high;
  4.  
  5. #if defined(analogPinToChannel)
  6. #if defined(__AVR_ATmega32U4__)
  7. if (pin >= 18) pin -= 18; // allow for channel or pin numbers
  8. #endif
  9. pin = analogPinToChannel(pin);
  10. #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  11. if (pin >= 54) pin -= 54; // allow for channel or pin numbers
  12. #elif defined(__AVR_ATmega32U4__)
  13. if (pin >= 18) pin -= 18; // allow for channel or pin numbers
  14. #elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__)
  15. if (pin >= 24) pin -= 24; // allow for channel or pin numbers
  16. #else
  17. if (pin >= 14) pin -= 14; // allow for channel or pin numbers
  18. #endif
  19.  
  20. #if defined(ADCSRB) && defined(MUX5)
  21. // the MUX5 bit of ADCSRB selects whether we're reading from channels
  22. // 0 to 7 (MUX5 low) or 8 to 15 (MUX5 high).
  23. ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5);
  24. #endif
  25.  
  26. // set the analog reference (high two bits of ADMUX) and select the
  27. // channel (low 4 bits). this also sets ADLAR (left-adjust result)
  28. // to 0 (the default).
  29. #if defined(ADMUX)
  30. ADMUX = (analog_reference << 6) | (pin & 0x07);
  31. #endif
  32.  
  33. // without a delay, we seem to read from the wrong channel
  34. //delay(1);
  35.  
  36. #if defined(ADCSRA) && defined(ADCL)
  37. // start the conversion
  38. sbi(ADCSRA, ADSC);
  39.  
  40. // ADSC is cleared when the conversion finishes
  41. while (bit_is_set(ADCSRA, ADSC));
  42.  
  43. // we have to read ADCL first; doing so locks both ADCL
  44. // and ADCH until ADCH is read. reading ADCL second would
  45. // cause the results of each conversion to be discarded,
  46. // as ADCL and ADCH would be locked when it completed.
  47. low = ADCL;
  48. high = ADCH;
  49. #else
  50. // we dont have an ADC, return 0
  51. low = 0;
  52. high = 0;
  53. #endif
  54.  
  55. // combine the two bytes
  56. return (high << 8) | low;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement