 
     while (niter < MAX_ITER) {
         midpoint = (a + b)/2;
-        cur_diff = get_voltage(midpoint) - voltage_target;
+        cur_diff = (get_voltage(midpoint) - voltage_target)*1000;
 
         Serial.print(niter, DEC); Serial.print(",\t");
         Serial.print(a, DEC); Serial.print(",\t");
         Serial.print(b, DEC); Serial.print(",\t");
         Serial.print(midpoint, DEC); Serial.print(",\t\t");
-        Serial.println(cur_diff*1000, 2);
+        Serial.println(cur_diff, 2);
 
         if (abs(cur_diff) <= TOL || b-a < 1) {
             return midpoint;

void setup() {
    Serial.begin(9600);

    adc->setAveraging(32);
    adc->setResolution(16);
    adc->setConversionSpeed(ADC_CONVERSION_SPEED::VERY_LOW_SPEED);
    adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_LOW_SPEED);

    delay(2000);


*   change voltage_target accordingly and run the program. The optimum trim value is printed at the end.
*   The bisection algorithm prints some diagnostics while running.
*   Additionally, the bandgap voltage is printed too, it should lie between 0.97 V and 1.03 V, with 1.00 V being the typical value.
*   Because of noise, the trim value is not accurate to 1 step, it fluctuates +- 1 or 2 steps.
*/

#include <ADC.h>
