That way it’s not so jittery!
It’ll still be a bang-bang control loop though… you might eventually want to move to a P or PID controller which would look more like:
int Error = SensorValue[RightEncoder] - SensorValue[LeftEncoder];
int TargetPower = 50;
int PropConst = .1;
RDrivePower = TargetPower - PropConst * Error;
LDrivePower = TargetPower + PropConst * Error;
I haven’t tested that code, but that should be the basic principle behind it.
I hope you get your straight drive figured out and working!
Yes; the easy solution would be to just average the left and right encoder.
However, if either encoder fails or is off (which can happen), then your robot will be driving straight for a lot longer than you intended.
Another option would be to say, “If either encoder’s value is greater than the value of the target point then stop”, and that might work a bit better.
Ideally though, you might think of a way to combine these two approaches into one. Something like, “If the average of the left and right encoders’ values is greater than the target value OR if either encoder’s value plus fudge constant X is greater than the target value then stop.”
Your code segment also does not appear to apply the motor power to the motors,
nor does it stop the motors when the while() loop is complete.
Perhaps those are in the code elsewhere?
If you don’t know how your own code works then don’t post it. PropConst is presumably the proportional constant and should be defined as a float if you want to initialize it to 0.1.
Thanks jpearman!
Yes, PropConst would stand for Proportional Constant (I’ve also seen Kp used)
And “int PropConst = .1;” should be “float PropConst = .1”
That part doesn’t need to be in the loop, because it’s only declared once, so your program might look something more like:
//Initialization stuff happens here
float PropConst = .1;
//Function Declaration
void DriveStraight(int Distance, int Power)
{
clearDriveEncoders();
while(((SensorValue[RightEncoder] + SensorValue[LeftEncoder]) / 2) < Distance)
{
Error = SensorValue[RightEncoder] - SensorValue[LeftEncoder];
RDrivePower = Power - PropConst * Error;
LDrivePower = Power + PropConst * Error;
//Drive motor commands go here
}
//Stop motor commands go here
}
This is only written from memory, so it may contain bugs. Your mileage may vary.