Very unaccurate AnalogRead (with solution)

Hi there,

I'm using an Arduino Nano 33 IoT as a teaching tool. I had lots of problems with unaccurate and fluctuating analog input readings. This topic was most helpful: Extremely inconsistent analogRead() on Nano 33 IoT - Nano 33 IoT - Arduino Forum, along with the documentation of the SAMD21 Core https://www.microchip.com/wwwproducts/en/ATsamd21g18, choose 'view datasheet'.

Since I'm no fan of rewriting wiring.c I came up with a short piece of code that you can put in your setup(). For non-SAMD21 boards the code will not be executed. I think it speaks for itself.

Best,
David

  /*  !!! ADC SETTINGS FOR AN ARDUINO WITH A SAMD21 CORE !!!
   *  Resolution of 10 bits
   *  Clock prescaler div16 (Arduino default is div512,
   *      so this is 32 times faster)
   *  Average over 64 samples, with matching ADJRES factor
   *      from the documentation of the SAMD21. The averaging is
   *      necessary because the inputs are very noisy.
   */
  #ifdef _SAMD21_ADC_COMPONENT_
    ADC->CTRLB.bit.PRESCALER = ADC_CTRLB_PRESCALER_DIV16_Val;
    while (ADC->STATUS.bit.SYNCBUSY == 1);
    ADC->AVGCTRL.reg = ADC_AVGCTRL_SAMPLENUM_64 |
        ADC_AVGCTRL_ADJRES(4);
    while (ADC->STATUS.bit.SYNCBUSY == 1);
  #endif
2 Likes