ADC readout Problem

Hey, I'm encountering a weird problem regarding the readout of the ADC. Im reading a bunch of Faders which are connected to the Analog Ins of the Arduino. Im mapping the ADC range of the Arduino to 127 because im planning to send the values via MIDI. Now I've wrote a simple function which should only send out the values of each Fader when they have changed. The function looks like this:

void sendMIDI() {
  for (int i = 0; i < faderCount; i++) {  // faderCount is set to 1 in the setup for testing
    faderValues[i] = readFader(i);
    if (faderValues[i] != faderValuesOld[i]) {
      Serial.println(faderValues[i]);
      }
    faderValuesOld[i] = faderValues[i];
    }
}

The called readFader Function looks like this:

int readFader(int faderNumber) {
 return map(analogRead(faderPotPins[faderNumber]), 0, 1023, 0, 127); // faderPotPins declares the Pin to read from, in this case always A0
  }

My problem is if I use the function above as described the values of the ADC fluctuate by +/- 3. But the curiosity is; when I remove

if (faderValues[i] != faderValuesOld[I])

and setup the code to just print out the current mapped ADC reading then the values are not fluctuating. If I replace faderValuesOld with any other comparison like < 10 but leave the if statement there it also works perfectly.

Does anyone have an idea what is causing the problems here?

Hi,
How many faders are you scanning?

What model Arduino are you using?

Can I suggest you try this edit to your code.

void sendMIDI() {
  for (int i = 0; i < faderCount; i++) {  // faderCount is set to 1 in the setup for testing
    faderValues[i] = readFader(i);
    faderValues[i] = readFader(i);
    if (faderValues[i] != faderValuesOld[i]) {
      Serial.println(faderValues[i]);
      }
    faderValuesOld[i] = faderValues[i];
    }
}

That is read each fader input twice, this because you only have ONE ADC and it is multiplexed.
On the input of the ADC is a capacitor that charges up to the input voltage, this takes time.
By reading once then reading again, you give the capacitor time to completely charge to the new input voltage.

Tom.. :smiley: :+1: :coffee: :australia:

Fluctuations are normal
also if you switch channels quickly, you might want to perform 2 reads and throw away the first one.

int readFader(int faderNumber) {
  analogRead(faderPotPins[faderNumber]); // stabilise  input
  return map(analogRead(faderPotPins[faderNumber]), 0, 1023, 0, 127); // faderPotPins declares the Pin to read from, in this case always A0
}

Thank you guys so much! That was quick!

I have used similar function a dozen times but never got this problem. So I thought it might be some user error while coding. Ive implemented the suggested change of reading twice and also added 2ms of delay which got rid of the fluctuation completely.