Home > Reflections | โฎ๏ธ โญ๏ธ
2024-05-18 | ๐น๏ธ PID ๐ซ Pod ๐ Racer
โจ๏ธ๐น๏ธ CodinGame: Mad Pod Racing
- ๐ Exciting!
- ๐ก I was very interested when I learned about PID controllers in college, but Iโve never gotten around to implementing one.
- ๐ Iโve finally found an application thatโs literally asking for it!
- ๐ค I wrote a simple, intuitive control algorithm to drive my bot last night.
- ๐ Iโm impressed with the performance of such a similar algorithm!
- ๐ง But Iโm excited to apply some rigor and see how much juice we can squeeze from theory.
- ๐บ I revisit one of my favorites YouTube channels for a refresher on PID application
- โ๏ธ PID controllers are nice because they are simple and effective.
- ๐ We just need to determine a couple of modeling assumptions to get started.
- ๐ฏ A PID controller aims to minimize an error signal by manipulating a control variable.
- ๐ช For this application, a good initial choice for the control variable is obvious: thrust!
- ๐ค Deciding on an error signal to minimize is more nuanced.
- ๐ In my intuitive control algorithm, I used the angle between my popโs aim and the next checkpoint as a sort of error signal.
- ๐ I reduce the thrust proportionally to this angle.
- โก๏ธ If the angle is zero, weโre pointed at the target, so itโs full speed ahead!
- ๐ข If thereโs a big angle between our podโs aim and the checkpoint, weโre not headed in the right direction, so we may want to slow down.
- ๐ญ That was my thinking anyway.
- ๐ I suspect there may be better choices for error signals, as the point of a race isnโt just to point in the right direction.
- โ But I think this will serve as a good enough starting point while we implement our first PID controller!
- ๐ We can always iterate and tune when we have the infrastructure in place.
- โก๏ธ Also, I suspect that my intuitive algorithm is basically a propotional controller (the P in PID) and it works pretty well already.
- ๐ Letโs see how much it improves with the addition of integral and derivative signals (I and D, respectively).
๐ A Google search led me to a nice, simple reference implementation to get started.
def PID(Kp, Ki, Kd, setpoint, measurement):
global time, integral, time_prev, e_prev
# Value of offset - when the error is equal zero
offset = 320
# PID calculations
e = setpoint - measurement
P = Kp*e
integral = integral + Ki*e*(time - time_prev)
D = Kd*(e - e_prev)/(time - time_prev)
# calculate manipulated variable - MV
MV = offset + P + integral + D
# update stored data for next iteration
e_prev = e
time_prev = time
return MV
- ๐ An easy read at 11 lines of Python!
- โฑ๏ธ This should only take a few minutes to translate, and maybe a โณ a half hour or so to get up and running in our ๐๏ธ pod racer.