AnalogRead Innaccurate

Hey there,

Here's my code:

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int A0_read = analogRead(A0);
  delay(100);
  int A1_read = analogRead(A1);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float A0_volts = A0_read * (5.0 / 1023.0);
  float A1_volts = A1_read * (5.0 / 1023.0);
  // print out the value you read:
  Serial.println(A0_volts);
  Serial.println(A1_volts);
  if(A0_volts == 5)
  {
    digitalWrite(13, HIGH);
  }
  if(A0_volts != 5)
  {
    digitalWrite(13, LOW);
  }
  if(A1_volts == 5)
  {
  digitalWrite(12, HIGH);
  }
  if(A1_volts != 5)
  {
    digitalWrite(12, LOW);
  }
  delay(1000);
}

I'm just tinkering with a SPDT toggle switch. The Power is drawn from the arduino 5V and is either going to A0 and A1. I'm getting readings from the serial like this:

5.00
4.04
5.00
4.20
5.00
4.22
5.00
4.23
5.00
4.25
5.00
4.29
5.00
4.28

I tested the SPDT with a multimeter, so it is definitely not bleeding signal into A1 while A0 is actually toggled to receive the signal. Can anyone see any flaws in my code or is this a known problem?

Thanks in advance!

Floating input -try a 10K resistor to Gnd on both pins..

Cool, that fixed it! Thx.

Except your calculation is also wrong…

ADC Sample = Vin x 1024 / Vref

I.e.

Vin = ADC * Vref / 1024

This is one of the most repeated incorrect calculations I keep seeing and it really bugs me.

People seem to think that 1023 represents 5V (or Vref). But it doesn’t, it represents (Vref - 1LSB). There are 1024 levels of which 0 = 0V and 1023 = 1023 * Vlsb. You can’t actually measure up to the reference voltage - to do so would require an extra bit.