Arduino Uno analogRead with ADC register

  adc, arduino, avr, c++

I’m trying to read to calculate the capacitance with the Arduino Uno. I did this successfully with the Arduino function.

unsigned long starttime = 0;
unsigned long endtime = 0;
double C = 0;
float n = 3.0;  //time constant
float resistor = n * 998000.0;
int analogValue = 0;

void setup() {
  Serial.begin(9600);
  pinMode(5, OUTPUT);
  pinMode(A0, INPUT);
}

void loop() {
  digitalWrite(5, HIGH);
  starttime = micros();
  do {
    analogValue = analogRead(A0);
    Serial.println(analogValue);
  } while (analogValue < 972);

  endtime = micros() - starttime;
  C = ((double)endtime / resistor);
  Serial.println(C, 9);

  digitalWrite(5, LOW);
  do {
    analogValue = analogRead(A0);
  } while (analogValue > 0);
} 

The output of this code is the following:

969
969
969
969
970
970
970
971
972
1.097339038 Capacitance

As you can see it takes quit a long time to through the threshold value, which is good. Due to the slow analogRead function I want to rewrite this code with the corresponding registers. This looks like this.

unsigned long starttime = 0;
unsigned long endtime = 0;
double C = 0;
float n = 3.0;  //Zeitkonstante
float resistor = n*998000.0;
int value = 0;

void setup() {
  Serial.begin(9600);
  //setup up Pin5 aus Output Pin
  DDRD = B00100000;
  PORTD = B00000000; 
  
  sei();
  ADMUX &= B00000000; //clear all bits
  ADMUX |= B10000000; //internal Rev, no left Adjust, A0 output
  ADCSRA |= B10000110;
}

void loop() {
  starttime = micros();
  PORTD = (1<<5) | PORTD;
  do{
    ADCSRA |= (1 << ADSC);
    value = ADCL | (ADCH << 8);
    Serial.println(value);
  }while(value<972);

  endtime = (micros() - starttime);
  C = ((double)endtime/resistor);
  Serial.println(C, 9);

  PORTD &= B00000100;
  do{
    ADCSRA |= (1 << ADSC);
    value = ADCL | (ADCH << 8);
  }while(value > 0);
}

The Problem is the output of this code:

830
849
869
887
906
925
943
961
980
0.083389453 Capacitance

As you can see the values reaches the threshold value so much faster which ended in a wrong capacitance value.

I’m not sure why this happening and could not came up with a solution for this.

I really hope you can help me there.

Source: Windows Questions C++

LEAVE A COMMENT