Electronic – arduino – Rotary encoders to ensure 2 wheel robot goes straight!

arduinoencoderroboticsspeedwheel

I have successfully counted the rotary encoders on the wheel of my robot so this is not a problem.

My problem is what to do with this number.

Basically, the bigger problem is that I need my robot to go straight and I want to do it using only two encoders (one on every wheel).

Even if I send the same amount of power to both motors the robot does not go straight. This is why I decided to use encoders, so no matter the power on the batteries, or the conditions of the motors; the robot will go straight.

So, now that I have successfully counted the "clicks" on the encoder I need to know what to do with the number to make sure the tow wheels are synchronized.

This is the code I am using (Arduino):

  digitalWrite(dirMotO, HIGH);
  digitalWrite(dirMotE, HIGH);
  //digitalWrite(motO, HIGH);
  analogWrite(motO, 150);
  //digitalWrite(motE, HIGH);
  analogWrite(motE, 150);

  PololuWheelEncoders::getCountsAndResetM1();
  PololuWheelEncoders::getCountsAndResetM2();

  while(PololuWheelEncoders::getCountsM1()<clicks && PololuWheelEncoders::getCountsM1()<clicks){
    if(PololuWheelEncoders::getCountsM1()>=clicks){
      digitalWrite(motO, LOW);
    }
    if(PololuWheelEncoders::getCountsM2()>=clicks){
      digitalWrite(motE, LOW);
    }
  }

I thought this code would make sure that if one wheel gets to counts before the other it would stop and wait for the other wheel but the robot does not go straight.

I would really appreciate some help on this.

Thank you!

Best Answer

Your while loop logic is incompatible with the conditions inside it.

Your while loop is saying:

as long as BOTH wheel encoders read less than clicks, execute the code inside

and your if statements are saying:

if any of the wheel encoders is greater or equal to clicks, stop the corresponding motor

This is generally false except for the rare condition where one of the encoders happen to increment between the arduino evaluating the while and the if statements. In order words just about never.

So the first thing you need to do is fix your logic. Then you need to investigate more sophisticated means of keeping the wheels in sync, such as computing an error term from the different in ticks, and employing a PID controller algorithm to adjust the speed of both motors via analogWrite.