akhilrb

analogRead8bit

Jan 3rd, 2018
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.77 KB | None | 0 0
  1. // This code is modified from the original analogRead function provided in Arduino's source code (wiring_analog.c)
  2. // This function can be appended directly to the stock file wiring_analog.c
  3.  
  4. uint8_t analogRead8bit(uint8_t pin)
  5. {
  6.     uint8_t result;
  7. #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  8.     if (pin >= 54) pin -= 54; // allow for channel or pin numbers
  9. #elif defined(__AVR_ATmega32U4__)
  10.     if (pin >= 18) pin -= 18; // allow for channel or pin numbers
  11. #elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__)
  12.     if (pin >= 24) pin -= 24; // allow for channel or pin numbers
  13. #elif defined(analogPinToChannel) && (defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__))
  14.     pin = analogPinToChannel(pin);
  15. #else
  16.     if (pin >= 14) pin -= 14; // allow for channel or pin numbers
  17. #endif
  18.    
  19. #if defined(__AVR_ATmega32U4__)
  20.     pin = analogPinToChannel(pin);
  21.     ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5);
  22. #elif defined(ADCSRB) && defined(MUX5)
  23.     // the MUX5 bit of ADCSRB selects whether we're reading from channels
  24.     // 0 to 7 (MUX5 low) or 8 to 15 (MUX5 high).
  25.     ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5);
  26. #endif
  27.  
  28. #if defined(ADMUX)
  29.     ADMUX = (analog_reference << 6) | (pin & 0x07);
  30. #endif
  31.  
  32.     // without a delay, we seem to read from the wrong channel
  33.     // delay(1);
  34.  
  35. #if defined(ADCSRA)
  36.     // start the conversion
  37.     sbi(ADCSRA, ADSC);
  38.  
  39.     // ADSC is cleared when the conversion finishes
  40.     while (bit_is_set(ADCSRA, ADSC));
  41.  
  42.     //read only ADCH, 8 bits
  43.     result = ADCH;
  44. #else
  45.     // we don't have an ADC, return 0
  46.     result = 0;
  47. #endif
  48.  
  49.     // combine the two bytes
  50.     return result;
  51. }
Add Comment
Please, Sign In to add comment