Reading analog pin not consistent

Arduino Diecimila (ATmega168), IDE 1.6.1

I have a pot connected to 5 volts, ground, and analog pin 0. I read the pin each time through the loop and test the value to see if it’s changed. If outside +/-2, I print it to the computer screen.

As I turn the pot slowly I can’t get to value 0; it stops about 50. If I turn quickly I can get to 0, or close.

I measured the pin and it goes all the way to 0 volts with the pot turned all the way.

I modified the code to not test Speed value, only to print the value as I turn the pot. It prints full range all the way to 0.

It is the limits testing that is causing the problem with the full range of values of Speed.

Why?

Thanks for any help.

Cheers.

  int analogPin = 0;
  int Speed = 0;
  int OldSpeed = 0;

void setup()   {                
  analogReference(DEFAULT);
  Serial.begin(9600); // send and receive at 9600 baud
}
  
void loop()   {
  Speed = analogRead(analogPin); // fetch pot value
//  if (Speed != OldSpeed) {
  if ((Speed < OldSpeed-2) ||        // hysteresis
    ( Speed > OldSpeed+2)) {       // hysteresis
    Serial.print("Speed is ");          // if it's changed tell me
    Serial.println(Speed);              // send end of line ch
  }
  OldSpeed = Speed; 
}

You need to add this to your setup function.

pinMode(analogPin, INPUT);

Arduino pins can be declared as an input or output pin....

I might change the input name from analogPin to something more descriptive, say.. potInput

And for pins declarations, you could use

const byte potInput

Qdeathstar:
You need to add this to your setup function.

pinMode(analogPin, INPUT);

Arduino pins can be declared as an input or output pin....

You don't need to do this for using analogRead. You only need to do this if you intend to use it as a digital pin.

 analogReference(DEFAULT);

I would remove that line and see what happens. You shouldn't have to mess with that just to read a pot.

I fixed it. It's "operator error". Sort of.

If you move the pot slowly, the Speed value from the pot (pin A0) is always going to be within 2 points of the OldSpeed value. If you think about it:

Speed is 10.
OldSpeed is now 10.
Speed is 11.
Old Speed is now 11.

So if you keep turning it slowly you'll never get outside the +/- 2 point hysteresis brackets. So it will never get printed. If you move the pot quickly, the new Speed value will be quickly far away from OldSpeed value and will get printed.

I moved the OldSpeed = Speed statement inside the loop so it gets executed every time a new value is read. Now OldSpeed is updated every time and it works.

Cheers.