# Making a robot move straight between two maze walls

Using a PID with encoders, I can make the robot move straight but there is a 0.5 degrees drift and it eventually hits a wall so I need to adjust to center it between the two walls. I have a sensor on each side that gives me the distance from the wall, so What's the best approach to make the robot adjust when it comes to close to one wall?

Just make the error term in your pid the difference between the sensors you have.

i.e. $$Error = d_{left} - d_{right}$$ Where a positive error means you are too far right and you need to turn left and a negative error means you are too far to the left and need to turn right.

You might then feed the output of the PID as a delta speed (or power or whatever) into your motors. So say the output of your PID was -8 (you are too far to the left) and your nominal motor power is 50%, you might feed 50+8=58% into your left motor and 50-8=42% into your right motor. Putting you back on track.

Just beware for openings in your maze!

• Hmm, I tried this approach but it ended being either too slow or not fast or sometimes oscillate too much instead of going straight. You think that can be fixed with PID turnings? Apr 5, 2017 at 22:50

You need to do some basic trig/geometry to calculate your robots x position and it's heading. Then you can use PID to correct for both. In the past I have just added the output of two PID loops to correct for heading and distance offset. You will probably have to play with constants to get it tuned properly. This should work better than just trying to get the two sensors to the same reading because the difference in sensor and your motor speeds don't form a Linear Time Invariant (LTI) system. The more nonlinear the system the worst standard PID will work.

For constructing a Finite State Machien the first step is to analyze your problem on a linguistic level. According to the OP, there are two walls and two sensor measurements. So the robot can be in state:

1. left_from_center
2. right_from_center

The next step is is to determine the center of the wall. This can be done also with a state:

1. calculate_center

And last but not least the robot can drive to:

1. drive_left
2. drive_right

So we have a list of 5 states which are well named and can be implemented in the programming language of your choice. Than a little bit testing is necessary for the "calculate_center" state which uses a absolute value for the width of the path and perhaps some other optimization are needed for the action of the robot, e.g. how much drive the robot to left?

It is not as easy as to program a simple PID Controller which consists of only one equation, but a finite state machine give us a nice opportunity for program debugging if the system is working suboptimal. Thanks for the nice question and good luck.