Skip to content

Commit 87236bc

Browse files
authored
Merge pull request #345 from Vitve4/pr_344
Improve reading ADC result
2 parents 6ec8015 + 4fd3801 commit 87236bc

File tree

1 file changed

+5
-13
lines changed

1 file changed

+5
-13
lines changed

cores/arduino/wiring_analog.c

+5-13
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ void analogReference(uint8_t mode)
3737

3838
int analogRead(uint8_t pin)
3939
{
40-
uint8_t low, high;
4140

4241
#if defined(analogPinToChannel)
4342
#if defined(__AVR_ATmega32U4__)
@@ -74,27 +73,20 @@ int analogRead(uint8_t pin)
7473
// without a delay, we seem to read from the wrong channel
7574
//delay(1);
7675

77-
#if defined(ADCSRA) && defined(ADCL)
76+
#if defined(ADCSRA) && defined(ADC)
7877
// start the conversion
7978
sbi(ADCSRA, ADSC);
8079

8180
// ADSC is cleared when the conversion finishes
8281
while (bit_is_set(ADCSRA, ADSC));
8382

84-
// we have to read ADCL first; doing so locks both ADCL
85-
// and ADCH until ADCH is read. reading ADCL second would
86-
// cause the results of each conversion to be discarded,
87-
// as ADCL and ADCH would be locked when it completed.
88-
low = ADCL;
89-
high = ADCH;
83+
// ADC macro takes care of reading ADC register.
84+
// avr-gcc implements the proper reading order: ADCL is read first.
85+
return ADC;
9086
#else
9187
// we dont have an ADC, return 0
92-
low = 0;
93-
high = 0;
88+
return 0;
9489
#endif
95-
96-
// combine the two bytes
97-
return (high << 8) | low;
9890
}
9991

10092
// Right now, PWM output only works on the pins with

0 commit comments

Comments
 (0)