Wheel encoder PID

Hello all,

I am working on a robot that needs both wheels to drive straight and at the same speed. I have encoders on the back of each of my two motors. I have been online looking for something that will help me understand how to do it, but came up empty handed, or I just missed the point due to my lack of Arduino knowledge.
Anyhow. Does anyone have a code that I could play around with?
Thanks

First you need to learn how to read the encoders and then to calculate wheel rotational velocity and distance traveled. One place to start is here Arduino Playground - RotaryEncoders but Google will find many more.

I wrote this for syncing a motor with 1 oulse/revolution to an external pulse input. I worked satisfactory. Of course all values must be adjusted for the physics of the surrent setup.

const int MotorPWM = 10;//motor PWM output
const int MotorPulse = 2;//Pulse input from motor
const int ExtPulse = 3;//Pulse input external pulse
const double Gain =0.8;//regulator gain
const double offset =33.3;//regulator offset

int Counter=1;//initial value for quick start
unsigned long Timer;
int MotorState;//for edge detection 
int ExtState;//for edge detection

void setup(){
  Serial.begin(115200);
  pinMode(MotorPWM, OUTPUT);
  Counter = 37;
  Timer = millis();
}//setup()

void loop(){
  MotorState = ((MotorState<<1)|digitalRead(MotorPulse))&3;//detect rising edge on motor pulse
  if(MotorState == 1) --Counter;//decrement Counter on leading edge of motor pulse
  ExtState = ((ExtState<<1)|digitalRead(ExtPulse))&3;//detect rising edge on external pulse
  if(ExtState == 1) ++Counter;//increment Counter on leading edge of external pulse
  analogWrite(MotorPWM, offset + Counter*Gain);
  if(millis()-Timer > 2000){
    Serial.println(Counter);
    Timer = millis();
  }//if
}//loop()
1 Like

Thanks guys for your input. I am looking for a code with a PID loop in it. I want my right wheel to keep up with my left. Again thank you for the advice.