Back to Hobby Projects

2023

PID Controller

An implementation of a PID controller in C. A PID controller, short for Proportional-Integral-Derivative controller, is a closed-loop control system that is widely used in engineering applications to control dynamic systems. It works by continuously comparing a desired target value, also called the setpoint, with the current output of a system. The difference between these two values is used to calculate a correction signal that helps move the system toward the target.

This project provides a simple and readable implementation of the PID control concept. It is mainly intended as a practice project and learning resource for anyone who wants to understand how PID controllers work at a software level. The code demonstrates how the proportional, integral, and derivative terms are calculated and combined to produce a control output.

The proportional term reacts to the current error between the target and measured value. The integral term considers accumulated error over time, which helps reduce long-term steady-state error. The derivative term estimates how quickly the error is changing, which can help reduce overshoot and improve stability. By tuning the three gain values, kP, kI, and kD, the controller response can be adjusted for different systems.

The implementation is written in C and organized into separate source and header files. The controller stores values such as the PID gains, sampling time, goal value, and previous error data. A ring buffer is used to store past error values, allowing the controller to calculate accumulated error and observe recent changes in system behavior.

The project also makes use of function pointers for flexibility. Users can provide their own input function and transfer function. The transfer function represents the behavior of the system being controlled, or “plant,” by describing how a given control input affects the system output. In the example program, this allows the PID controller to be tested against a simple simulated system without requiring real hardware.

Although this is not intended to be a production-ready control library, it is useful as an educational example. It can help students, hobbyists, and developers connect basic control theory with practical C programming. It may also serve as a starting point for more advanced PID implementations, such as adding output limits, anti-windup protection, realtime sampling, or embedded system integration.

Overall, this project is a compact learning exercise that introduces the core ideas behind PID control while keeping the implementation simple enough to read, modify, and experiment with.

PID Controller preview image