Skip to content

Commit 4fd3801

Browse files
committed
Improve reading ADC result
7.3.0-atmel3.6.1-arduino7 gcc fails to optimize separate reading from ADCL and ADCH. It produces additionally three eor commands or in some cases two mov commands in the assembly code (see discussion arduino#344). These commands swap register contents before store them to data area. So they are completely unnecessary. Reading ADC result with ADC macro fixes it and gcc generates the right code..
1 parent 58081c0 commit 4fd3801

File tree

1 file changed

+5
-13
lines changed

1 file changed

+5
-13
lines changed

cores/arduino/wiring_analog.c

Lines changed: 5 additions & 13 deletions
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)