Clear Filters
Clear Filters

Trouble writing PWM signal from PID controller

9 views (last 30 days)
I am working on a project to use an Arduino Uno with MATLAB PID control, a moisture sensor, and water pump to keep a plant at a specified moisture level. I've posted my code below, everything works perfect until the if/ifelse statements where I can't seem to get an output of anything but 0 or 1 duty cycle even when I confirmed that PID was outputting a value between 0 and 1. Any help would be greatly appreciated, thank you.
End_time_CS= 10;
moisture_Threshold= 20;
Kp = .05;
Ki = 0.01;
Kd = 0.01;
dt = 0.25;
while toc <= End_time_CS
rec_temp_CS(i+1) = moisture_f;
rec_time_CS(i+1) = toc;
Error(i+1) = moisture_Threshold - rec_temp_CS(i);
Prop(i+1) = Error(i+1);
Der(i+1) = (Error(i+1) - Error(i))/dt;
Int(i+1) = (Error(i+1) + Error(i))*dt/2;
I(i+1) = sum(Int);
PID(i+1) = Kp*Prop(i) + Ki*I(i+1)+ Kd*Der(i);
%this is where the problem is I can only get it to output 0 or 1 duty
%cycle, not the PID value even when PID is between 0 and 1
if PID(i) > 1
elseif PID(i) < 0
elseif 0 < PID(i) < 1
display('Control System has stopped')
Chris Hubbard
Chris Hubbard on 4 Dec 2019
Edited: Chris Hubbard on 4 Dec 2019
It is never getting to the third option, I had it log the PID(i) values and its output was between 0 and 1 (the condition for the third option) for most of the run time, but my duty cycle was only ever 0 or 1 (the first two if/ifelse options). Unless the way I wrote my loops was incorrect to have PID(i) in the third option equal my PID equation.
Nikhil Rajkumar
Nikhil Rajkumar on 29 Jul 2020
Hey! I am working on a similar project that requires a PID controllor to operate LED brightness. I was wondering if you explain what Error(i+1)/Error(i), Prop(i+1), Der(i+1), Int(i+1) and PID(i+1) do. Are they functions that you have defined? If so, please briefly explain what each of them do. I would really appreciate some help as I am new to MATLAB. Thank you so much!

Sign in to comment.

Answers (1)

Pranav Murali
Pranav Murali on 16 Mar 2020
Hi Chris,
I understand that you are receiving the correct value of PID but you are unable to control the output duty cycle of your system. The problem here is MATLAB does not support testing whether PID(i) is in between 0 and 1 with this syntax. Instead, MATLAB interprets 0 < PID(i) < 1 as (0 < PID(i)) < 1, comparing the logical result of 0 < PID(i) (either 0 or 1) to the value 1.
I would suggest you rather try with the syntax below:
elseif ((0 < PID(i)) && (PID(i) < 1))
That should solve your problem.




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!