Skip to content

Commit abc536c

Browse files
committed
Fixed bad first read from analogRead() after changing references by using a dummy read.
1 parent c9a02ad commit abc536c

File tree

1 file changed

+5
-0
lines changed

1 file changed

+5
-0
lines changed

cores/arduino/wiring_analog.c

+5
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,8 @@ void analogReference(eAnalogReference mode)
437437
syncADC();
438438

439439
// Start conversion, since The first conversion after the reference is changed must not be used.
440+
uint32_t valueRead __attribute__((unused));
441+
440442
#if (SAMC21 || SAMD51)
441443
ADC0->CTRLA.bit.ENABLE = 0x01; // Enable ADC
442444
ADC1->CTRLA.bit.ENABLE = 0x01; // Enable ADC
@@ -445,6 +447,8 @@ void analogReference(eAnalogReference mode)
445447
ADC1->SWTRIG.bit.START = 1;
446448
syncADC();
447449
while ((ADC0->INTFLAG.bit.RESRDY == 0) || (ADC1->INTFLAG.bit.RESRDY == 0)); // Waiting for conversion to complete
450+
valueRead = ADC0->RESULT.reg; // Dummy read (will also clear the Data Ready flag)
451+
valueRead = ADC1->RESULT.reg; // Dummy read (will also clear the Data Ready flag)
448452
ADC0->CTRLA.bit.ENABLE = 0x00; // Disable ADC
449453
ADC1->CTRLA.bit.ENABLE = 0x00; // Disable ADC
450454
#else
@@ -453,6 +457,7 @@ void analogReference(eAnalogReference mode)
453457
ADC->SWTRIG.bit.START = 1;
454458
syncADC();
455459
while (ADC->INTFLAG.bit.RESRDY == 0); // Waiting for conversion to complete
460+
valueRead = ADC->RESULT.reg; // Dummy read (will also clear the Data Ready flag)
456461
ADC->CTRLA.bit.ENABLE = 0x00; // Disable ADC
457462
#endif
458463
syncADC();

0 commit comments

Comments
 (0)