Victoria Ideas Back to catalog
an image of a computer screen with the symbols and functions in windows 7 0 1
Aug 28, 2026 Victoria

PID Controller MATLAB Code: Tuning & Implementation

Mastering control systems often requires expertise in designing controllers, and Proportional-Integral-Derivative (PID) controllers are a staple in the industry...

Mastering control systems often requires expertise in designing controllers, and Proportional-Integral-Derivative (PID) controllers are a staple in the industry. If you're working with MATLAB, crafting efficient PID controllers becomes an integral part of your daily tasks. Let's delve into the process of implementing PID controllers using MATLAB code.

an image of a computer screen with the symbols and functions in windows 7 0 1

Before we dive into the code, it's essential to understand the basic concept of a PID controller. PID controllers continuously calculate the error value as the difference between the desired setpoint and the actual process variable. They apply a correction based on proportional, integral, and derivative terms, aiming to minimize the error and achieve the desired outcome.

PID Controller Design using Simulink MATLAB: Tutorial 3

Creating the PID Controller Function

The core of implementing a PID controller in MATLAB involves defining a function that calculates the PID terms and outputs the control variable. Let's create a function named 'PID_Controller' that takes the setpoint, process variable, sample time, and PID tuning parameters (Kp, Ki, Kd) as inputs.

The PID Controller — Part 1

Function Definition

First, we'll define the function with its input arguments and output. To maintain a clear structure, we'll define two local variables: 'error' for the real-time error and 'accumError' to keep track of the integral term.

Controlador PID - Control de sistemas

Here's the initial function definition:

function [controlSignal] = PID_Controller(setpoint, processVar, sampleTime, Kp, Ki, Kd) persistent error accumError prevError if isempty(error) error = setpoint - processVar; accumError = 0; prevError = error; end controlSignal = -Kp * error - Ki * accumError * sampleTime - Kd / sampleTime * (error - prevError); accumError = accumError + error * sampleTime; prevError = error; end

Function Optimization

To improve the function's performance, we can preallocate memory for the persistent variables. This reduction in dynamic memory allocation can enhance the function's speed, especially when running simulations over long time horizons.

Controlador PID

Let's optimize the function by preallocating memory for the persistent variables as follows:

function [controlSignal] = PID_Controller_optimized(setpoint, processVar, sampleTime, Kp, Ki, Kd) persistent error accumError prevError if isempty(error) error = setpoint - processVar; accumError = 0; prevError = Error; error = zeros(size(setpoint)); accumError = zeros(size(setpoint)); prevError = zeros(size(setpoint)); end controlSignal = -Kp * error - Ki * accumError * sampleTime - Kd / sampleTime * (error - prevError); accumError = accumError + error * sampleTime; prevError = error; end

Implementing the PID Controller in a System

Now that we have defined our PID controller function, let's implement it in a closed-loop system to control a process. For this example, we'll use a simple tank system where the goal is to maintain a specific water level.

MATLAB - A Fundamental Tool for Scientific Computing and Engineering Applications - Volume 1 | IntechOpen

Define System Parameters

To begin, let's define the system parameters such as the tank's cross-sectional area, the feed water flow rate, and the outlet flow coefficient. We'll also set the desired water level (setpoint) and initialize the water level (process variable) at some arbitrary value.

a blackboard with text that reads tuning a pid controller ziegler - nicholas method
an image of a plot with the same slope as it is shown in this diagram
General PID loop in the most general form
P PI PD and PID controllers
an image of a plot with different amplitudes and the same area for it to be observed
Abdul Wahab Junaid's Shop | Buy Me a Coffee
a shiny metal object sitting on top of a black table next to a white wall
Arduino PID Controller Temperature PID Controller
PID CONTROLLER

We'll use the following parameters for this example:

  • Tank cross-sectional area (A) = 1 [m^2]
  • Feed water flow rate (Qin) = 0.1 [m^3/s]
  • Outlet flow coefficient (K) = 0.01 [1/sqrt(m)]
  • Desired water level (setpoint) = 0.5 [m]
  • Initial water level (processVar) = 0.3 [m]

System Dynamics and Simulation

The water level in the tank can be modeled using the following differential equation:

&dif;`h`/`t` = (Qin - K * sqrt(`h`) ) / A

Let's create a simple simulation to demonstrate how our PID controller can maintain the desired water level. We'll use the 'ode45' function to solve the differential equation and integrate our PID controller function.

The following code snippet implements the closed-loop system and simulates the response for a given time horizon:

Code Snippet: Closed-Loop System with PID Controller Simulation

% System parameters A = 1; % m^2 Qin = 0.1; % m^3/s K = 0.01; % 1/sqrt(m) setpoint = 0.5; % m processVar = 0.3; % m % PID tuning parameters Kp = 1; Ki = 0.1; Kd = 0.01; % Time horizon tFinal = 100; time = 0:0.01:tFinal; % Initial conditions IC = {0, processVar}; % ODE function function dy = Tank_dynamics(t, y) h = y(1); Qin = PID_Controller_optimized(setpoint, h, 0.01, Kp, Ki, Kd); dy = (Qin - K * sqrt(h)) / A; end % Solve ODE and integrate PID controller sol = ode45(@Tank_dynamics, time, IC); % Plot water level vs time plot(sol.x, sol.y(1,:)) xlabel('Time (s)') ylabel('Water Level (m)') title('Closed-Loop System with PID Controller: Water Level vs Time')

The resulting plot demonstrates how the PID controller successfully regulates the water level in the tank, maintaining it close to the desired setpoint (0.5 m) within a short period.

In conclusion, implementing a PID controller in MATLAB enables you to design efficient control systems for various processes. By understanding and adapting the provided PID controller function, you can maintain and stabilize systems with diverse dynamics. Familiarizing yourself with MATLAB's powerful toolbox for control systems provides you with an invaluable skill set for your career in process control and automation.

Ready to dive deeper into the world of control systems? Explore other types of controllers and optimization techniques in MATLAB to enhance your skill set and unlock new opportunities.

More shots

an image of a computer screen with the symbols and functions in windows 7 0 1
an image of a computer screen with the symbols and functions in windows 7 0 1
PID Controller Design using Simulink MATLAB: Tutorial 3
PID Controller Design using Simulink MATLAB: Tutorial 3
The PID Controller — Part 1
The PID Controller — Part 1
Controlador PID - Control de sistemas
Controlador PID - Control de sistemas
Controlador PID
Controlador PID
MATLAB - A Fundamental Tool for Scientific Computing and Engineering Applications - Volume 1 | IntechOpen
MATLAB - A Fundamental Tool for Scientific Computing and Engineering Applications - Volume 1 | IntechOpen
a blackboard with text that reads tuning a pid controller ziegler - nicholas method
a blackboard with text that reads tuning a pid controller ziegler - nicholas method
an image of a plot with the same slope as it is shown in this diagram
an image of a plot with the same slope as it is shown in this diagram

Related topics