Determine speed from hollow shaft potentiometer

Hi,

I have a potentiometer connected to a DC motor shaft. From the potentiometer, i could get the position from analog input. I was wondering if i could get an accurate speed by running the code below. Please give me advice. XD.

int pot = A0;
unsigned long lastTime = 0;
int lastPotReading;
int newPotReading;
int sampleTime = 50;
long velocity;

void setup() {
  pinMode(pot,INPUT);
  Serial.begin(9600);
  getInitialPotReading();
}

void getInitialPotReading(){
  lastPotReading = analogRead(pot);
  lastPotReading = map(lastPotReading,0,1023,0,250);
}

void loop() {
  unsigned long now = millis();
  if (now - lastTime > sampleTime) {
    newPotReading = analogRead(pot);
    newPotReading = map(newPotReading,0,1023,0,250);
    velocity = 1000*(newPotReading-lastPotReading)/(sampleTime);

    Serial.print(velocity);
    Serial.println("degree per second");
    lastPotReading = newPotReading;
    lastTime = now;
  }
}

I don't think you considered the situation where you read a high value and the next you read a low value (the potentiometer wraps around) and you will get negative values. You want to say in your code that if your new value is less, then add a full turn worth of value to the new before calculating speed. Can you use optical rotary encoder instead of a potentiometer? Potentiometers are not built to survive rotations on a motor.

liudr: I don't think you considered the situation where you read a high value and the next you read a low value (the potentiometer wraps around) and you will get negative values. You want to say in your code that if your new value is less, then add a full turn worth of value to the new before calculating speed. Can you use optical rotary encoder instead of a potentiometer? Potentiometers are not built to survive rotations on a motor.

Hi liudr, thanks for ur reply. I noticed sign changes in the Serial monitor. In my application, I wont be using the motor to spin continuously but limit to certain angle.

That'll be good. There might be pots made specifically for that. At least simple servos have pots to sense the rotation and servos normally don't turn continuously. I would read several times and average.