How to use PID controller from Control System TB in Matlab function of Stateflow?
8 views (last 30 days)
Show older comments


I want to use PID controller in Stateflow. I made two options (above): Simulink function and Simulink state.
How to use Matlab function, PID from Control System toolbox? This PID is object like transfer function, and I need time series.
0 Comments
Answers (1)
Aravind
on 4 Feb 2025
I understand you are interested in implementing a PID controller within a Stateflow chart. While it is technically feasible, it is generally more efficient and maintainable to use Simulink's dedicated tools for control systems instead of adding a PID controller inside a Stateflow chart. However, if you need to use a PID controller in Stateflow, you can consider these two alternatives using MATLAB functions instead of Simulink blocks:
Using the “pid” Function:
You can create a PID controller object using the “pid” function from the Control System Toolbox in MATLAB. With the PID object, you can utilize the “lsim” function to simulate the PID controller's response to input signals over time. This allows you to incorporate the PID logic within the Stateflow chart by calling these MATLAB functions. More details on the “pid” function can be found here: https://www.mathworks.com/help/releases/R2021b/control/ref/pid.html, and for the “lsim” function, visit: https://www.mathworks.com/help/releases/R2021b/ident/ref/lti.lsim.html.
Manual PID Implementation:
Alternatively, you can manually implement the PID control logic using MATLAB code within the Stateflow chart. This involves calculating the control output with the standard PID formula: Kp * error + Ki * integral of error + Kd * derivative of error. Here is a simple PID implementation:
% Initialize persistent variables
persistent integral_error previous_error
if isempty(integral_error)
integral_error = 0;
previous_error = 0;
end
% PID parameters
Kp = 1.0; % Proportional gain
Ki = 0.1; % Integral gain
Kd = 0.01; % Derivative gain
% Calculate error
error = setpoint - measured_value;
% Update integral of error
integral_error = integral_error + error * dt;
% Calculate derivative of error
derivative_error = (error - previous_error) / dt;
% PID output
control_output = Kp * error + Ki * integral_error + Kd * derivative_error;
% Update previous error
previous_error = error;
This approach gives you complete control over the PID calculations but requires careful handling of time steps (dt) and state updates.
These two methods offer you flexibility in integrating PID control within Stateflow using MATLAB rather than Simulink. If you can provide more details about your use case, I can provide further assistance.
See Also
Categories
Find more on Gain Scheduling in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!