In this project, a simulator is giving us the state of the car with respect to a predefined path around the circuit in terms of:

- cross track error: how far the car is from the circuit

- orientation error: the angle between the car’s orientation and the tangent to the path.

The mission for our controller is to give steering and throttle commands to drive safely and as fast as possible around the circuit.

Implementing the PID controller is straightforward, tuning its gains however is not and can get very tedious.

I programmed the twiddle algorithm to tune the gains for me. Twiddle is an algorithm that alters the parameter by a small amount each iteration, and checks if the error is smaller. If that is the case, it will change the parameter by a bigger amount the next time. If not, it will reduce the amount of change. It will iterate over the parameters making a couple trials for each of them, ad infinitum. This is easy to program and can find a local optimum.

Since the controller behaves differently depending on the speed, I first trained it on a speed function which set low speeds, and then gradually increased the speed.

The speed function is basically an on-off controller coupled to a “desired speed” function. The “desired speed” is selected in linear dependence of the cross track error like this:

The speed stays constant for CTE greater than 2, so that the car keeps moving even when it has deviated from the path.

The algorithm to train the PID is like this:

The resulting controller in action:

The code for my project is hosted in github:

https://github.com/hectorratia/CarND-PID-Control-Project