I’ve been playing around with ChatGPT a lot recently and thought this would be a powerful tool for programmers when leveraged properly. You can ask it virtually anything and it will spit out a pretty good answer (though it is not always right).
For fun, I asked it to write a PID loop in C++, here’s what it spit out:
The actual code:
#include <iostream>
#include <cmath>
using namespace std;
const double kP = 0.2;
const double kI = 0.01;
const double kD = 0.1;
double setPoint = 10.0;
double currentPoint = 0.0;
double error = 0.0;
double lastError = 0.0;
double integral = 0.0;
double derivative = 0.0;
double output = 0.0;
int main()
{
while (true) // loop indefinitely
{
// calculate error
error = setPoint - currentPoint;
// calculate integral
integral += error;
// calculate derivative
derivative = error - lastError;
// calculate output
output = kP * error + kI * integral + kD * derivative;
// remember error for next iteration
lastError = error;
// set the output (e.g. control a motor)
// ...
// update current point (e.g. read from a sensor)
// ...
}
return 0;
}
It even added a lot of important context as to how the code operates after it wrote the code without me asking it to
"This code will continuously calculate and update the output of the PID control loop based on the current error between the set point and the current point. The constants kP, kI, and kD are the gain constants for the proportional, integral, and derivative terms, respectively. You can adjust these constants to tune the behavior of the control loop.
Note that this is just sample code, and you will need to modify it to suit your specific use case. For example, you will need to provide code to set the output (e.g. control a motor) and update the current point (e.g. read from a sensor).
I hope this helps! Let me know if you have any questions."
Mind you, this isn’t a copy-paste solution. You still have to implement it correctly and tune it (for example, this is missing integral bounds to prevent integral windup) but it was able to provide a very solid foundation. I think this is a powerful tool and I’m curious to see what other examples other people come up with
Here’s the link for the tool