Transcript
LabVIEW MathScript
Hans-Petter Halvorsen, M.Sc.
LabVIEW Installation Download the software here:
Note! You get the Serial Number from your Teacher, but the software can be used for 30 days before you need to enter a valid Serial Number.
http://home.hit.no/~hansha/?page=labview These are the main modules we use in the different courses at Telemark University College: • LabVIEW (LabVIEW Professional Development System 32-Bit: English) • LabVIEW Control Design and Simulation Module • LabVIEW MathScript RT Module • NI-DAQmx (Hardware Driver for NI USB-6008, NI TC-01, etc.) Note! These packages are separate downloads! Make sure to download and install all of them! All LabVIEW Software can be downloaded here: www.ni.com/download
Contents • Introduction to LabVIEW • Installation • Block Diagram Simulation based on differential Equations – Simulation Loop
• • • •
PID Control with built-in PID blocks/functions Creating and using Simulation Subsystems Simulations using a While Loop with Subsystems inside Discrete Simulation – Formula Node
• MathScript
Hardware
Air Heater
USB-6008
Wi-Fi DAQ Water Tank Pt-100 TC-01
Arduino
ZigBee
Vision System
cRIO NOx Sensor
LabVIEW This is the core LabVIEW installation that installs the LabVIEW Programming Environment.
LabVIEW MathScript RT Module This module is a text-based tool that is very similar to MATLAB. The syntax is similar to MATLAB, you can create and run so-called m files, etc. The module is available from the Tools menu inside LabVIEW.
LabVIEW Control Design and Simulation Module This module is used for creating Control and Simulation applications with LabVIEW. Here you will find PID controllers, etc. The module is available as a palette on your block diagram.
NI-DAQmx DAQmx is the Hardware Driver needed in order to use hardware devices like NI USB-6008, NI TC-01, etc. inside LabVIEW. The module is available as a palette on your block diagram.
What is LabVIEW MathScript?
Hans-Petter Halvorsen, M.Sc.
What is MathScript? • MathScript is a high-level, text- based programming language. MathScript includes more than 800 built-in functions and the syntax is similar to MATLAB. You may also create custommade m-file like you do in MATLAB. • MathScript is an add-on module to LabVIEW but you don’t need to know LabVIEW programming in order to use MathScript. • If you want to integrate MathScript functions (built-in or custom-made m-files) as part of a LabVIEW application and combine graphical and textual programming, you can work with the MathScript Node. • In addition to the MathScript built-in functions, different addon modules and toolkits installs additional functions. The LabVIEW Control Design and Simulation Module and LabVIEW Digital Filter Design Toolkit install lots of additional functions.
How do you start using MathScript? • You need to install LabVIEW and the LabVIEW MathScript RT Module. • When necessary software is installed, start MathScript by open LabVIEW • In the Getting Started window, select Tools -> MathScript Window...
MathScript LabVIEW MathScript RT Module
Add-on Module for LabVIEW where we can do text-based programming and simulations – very powerful!
MathScript Basics Command Window The Command Window is the main window in MATLAB. Use the Command Window to enter variables and to run functions and M-files scripts (more about m-files later). Its like an advanced calculator!
Hit “ENTER” in order to execute a command
Use “Arrow Up” in order to browse through old Commands (“Command History”)
MathScript Basics MATLAB is case sensitive! The variables x and X are not the same.
>> x=5; >> X=6; >> x+X ans = 11
Students: Try these examples
>> x=3 x = 3 >> y=4; >>
Unlike many other languages, where the semicolon is used to terminate commands, in MATLAB the semicolon serves to suppress the output of the line that it concludes.
MathScript Basics
>> clear >> clc
Students: Try these commands
The “clear” command deletes all existing variables” from the memory
The “clc” command removes everything from the Command Window clc – clear command window
Built-in constants
MathScript Basics
Name
Description
i, j
Used for complex numbers, e.g., z=2+4i
pi
π
inf
∞, Infinity
NaN
Not A Number. If you, e.g., divide by zero, you get NaN
>> r=5; >> A=pi*r^2 A = 78.5398
>> z1=3+3i; >> z2=3+5i; >> z = z1+z2 z = 6.0000 + 8.0000i
Students: Try these examples
>> a=2; >> b=0; >> a/b
MathScript Basics Students: Try this example
Which are correct?
>> x=2; >> y=3*x+2/2 y = 7 >> y=(3*x+2)/2 y = 4
Matematical Expressions
MATLAB log(x) log10(x) sqrt(x) exp(x) x^2
Students: Calculate this expression, try with different values for x and y
MathScript Basics Students: Calculate this expression, try with different values for x and y
Solutions: >> x=2;, y=2 >> z = 3*x^2 + sqrt(x^2 + y^2) + exp(log(x)) ans = 16.8284 ...
MathScript Basics Students: Use MATLAB in order to find the surface area of a cylinder based on the height (h) and the radius (r) of the cylinder
r=3
h=8
A=?
MathScript Basics Solutions:
>> h=8 >> r=3 >> A = 2*pi*r^2 +2*pi*r*h; A = 207.3451
Vectors & Matrices
Hans-Petter Halvorsen, M.Sc.
Math in MathScript
Mathematical Expressions:
Equations:
y(x) = 2x + 4 y(3) = ? Vectors:
x = 3; y = 2*x
+ 4;
Matrices:
Try these Examples x = [4, 3, 5]
A = [0, 1; -2, -3]
y = 1:10
C = [-1, 2, 0; 4, 10, -2; 1, 0, 6]
Vectors & Matrices • Matrices and vectors (Linear Algebra) are the basic elements in MATLAB and also the basic elements in control design theory, etc. • All variables in MATLAB is a matrix (but with different dimensions) • So it is important you know how to handle vectors and matrices in MATLAB and in general
Vectors Examples of different Rows and Columns vectors
>> x = [1, 2, 3] >> y = [4; 5; 6] >> z = [8, 9, 10]'
Students: Define these vectors in MATLAB. Try also to multiply the different vectors like this:
>> x*y >> y*x >> x*z >> y*z ...
Students: Try these examples >> a = [1:10] >> b = [1:2:10] >> b = [1:0.5:4]
Matrices Students: Define the following matrices in MATLAB >> A = [1 2; 3 4] A =
1 3
2 4
or: >> A = [1, 2; 3, 4] A =
1 3
2 4
Try these examples >> B+C >> B-C >> B/C >> B*C >> B.*C >> B'*C ...
Given the following matrices:
Matrices Define the matrices and try these examples
>> A*B >> B*A >> A+B >> B' >> B'*C >> A*B' >> A'*B’ >> A.*B ...
>> >> >> >> >> ...
A*(B*C) (A*B)*C (A+B)*C A*C + C*B (A+inv(B))*C
>> >> >> >> >> >> >> >> >> >> ...
rank(A) det(A) inv(A) inv(B) eig(A) inv(A) inv(B) diag(A) inv(A)*A A*inv(A)
Creating Scripts
Hans-Petter Halvorsen, M.Sc.
Scripts (m-files) Script Editor
MATLAB Scrips are saved as socalled .m files (file extension is .m)
When using the Script Editor, you may create several lines of code and execute all in one batch. You can easily do changes in your code, create comments, etc. clear clc x=0:0.1:2*pi; y=sin(x); y2=cos(x); y3=tan(x); y4=atan(x); %plotting sin(x) subplot(2,2,1) plot(x,y)
Run the Script
%plotting cos(x) subplot(2,2,2) plot(x,y2) %plotting tan(x) subplot(2,2,3) plot(x,y3)
Students: Try this example
%plotting atan(x) subplot(2,2,4) plot(x,y4)
Plotting
Hans-Petter Halvorsen, M.Sc.
Plotting in MathScript Example:
y(t) = 2x + 4
interval on x axis x = 0:5; y = 2*x
+ 4;
plot(x,y) Useful MathScript functions for plotting:
xlabel grid title
axis
ylabel text
Students: Try these functions How does they work? Type help
in Command window
How do you get another color? or line type?
Students: Try this
Plotting >> x = 0:0.1:2*pi; >> y = sin(x); >> plot(x,y) Students: Try this example Students: Try also these examples: >> >> >> >>
x = 0:0.1:2*pi; y = sin(x); y2 = cos(x); plot(x,y, x,y2)
... >> plot(x,y,'r*', x,y2,'g+')
Plotting Plotting functions: Name
Description
plot
Create a Plot
figure
Define a new Figure/Plot window
grid on/off
Create Grid lines in a plot
title
Add Title to current plot
xlabel
Add a Label on the x-axis
ylabel
Add a Label on the x-axis
axis
Set xmin,xmax,ymin,ymax
hold on/off
Add several plots in the same Figure
legend
Create a legend in the corner (or at a specified position) of the plot
subplot
Divide a Figure into several Subplots
Students: Try this example >> >> >> >> >> >> >> >> >>
x=0:0.1:2*pi; y=sin(x); plot(x,y) title('Plot Example') xlabel('x') ylabel('y=sin(x)') grid on axis([0,2*pi,-1,1]) legend(’Temperature')
Students: Try also to change some of the commands and see what happens with the plot
Plotting
Students: Try these examples >> x=0:0.1:2*pi; >> y=sin(x); >> y2=cos(x); >> subplot(2,1,1) >> plot(x,y) >> subplot(2,1,2) >> plot(x,y2)
Subplot
>> >> >> >>
x=0:0.1:2*pi; y=sin(x); y2=cos(x); y3=tan(x);
>> subplot(3,1,1) >> plot(x,y) >> subplot(3,1,2) >> plot(x,y2) >> subplot(3,1,3) >> plot(x,y3) >> >> >> >> >>
x=0:0.1:2*pi; y=sin(x); y2=cos(x); y3=tan(x); y4=atan(x);
>> subplot(2,2,1) >> plot(x,y) >> subplot(2,2,2) >> plot(x,y2) >> subplot(2,2,3) >> plot(x,y3) >> subplot(2,2,4) >> plot(x,y4)
User-defined Functions
Hans-Petter Halvorsen, M.Sc.
Egendefinerte Funksjoner i MathScript
function output = function_name(input)
User-defined Functions
MATLAB contains hundreds of built-in functions, but very often you need to create your own functions Input
Return value
You Create the Function in the Editor
You Use the Function in the Command Window or in a Script
Students: Try this example
Example Create the function
Execute the function
Function name input Return value function Tf = fahrenheit(Tc)
Tc = 23; Tf = fahrenheit(Tc)
Tf = (9/5)*Tc + 32;
Return value
The function body
Dette kan enten gjøres fra Command window eller Script window
Students: Try this The function needs to be saved as “fahrenheit.m” on your harddrive
User-defined Functions Example: Convert from Celsius to Fahrenheit Students: Create a User-defined Function that converts from Temperature in Celsius to Temperature in Fahrenheit Try the function in a Script like this: Try the function in the Command window like this:
>> Tc = 20; >> Tf = fahrenheit(Tc) Tf = 68
You need to create this function
User-defined Functions Solutions: Convert from Celsius to Fahrenheit
clear clc t = 0:0.1:24; Tc = (sin(t)+1)*20; Tf = fahrenheit(Tc);
function Tf = fahrenheit(Tc)
% This function converts a temperature from celsius to fahrenheit
Tf = (9/5)*Tc + 32;
plot(t,Tc, t,Tf) title('Temperature Simulation') xlabel('t') ylabel('Temperature') grid on axis([0,24, 0, 120]); legend('Celcius', 'Fahrenheit')
Tips & Tricks
Hans-Petter Halvorsen, M.Sc.
Tips & Tricks
Tips & Tricks
Use Comments (%) % This is a comment x=2; % Comment2 y=3*x % Comment3
DO NOT use ”spaces” in Filename or names that are similiar to built-in functions in MATLAB!
- but that have to make sense! Decimal sign: Use ”.”– NOT ”,” ! i.e. y=3.2 – not y=3,2 Use english names on variables, functions, files, etc. This is common practice in programming! Use always variables – Do not use numbers directly in the expressions!
Yes: a=2; b=4; y=a+b
No: y=2+4
Always include these lines in your Script Functions: • Only ONE function in each File! • The Filename (.m) AND the Name of the Function MUST be the same!
clear clc close all …
Tips & Tricks Greek!letters:!In!maths!and!control!theory!it!is!common!to!use!greek! letters!in!formulas,!etc.!These!cannot!be!used!directly!in!MATLAB,!so! you!need!to!find!other!good!alternatives.!Examples:! !! ! –!w0!
Use help in order to find out how to use a function in MATLAB. In order to get help for the tf function, type the following in the Command window: help tf
!! –!zeta!or!just!z! etc.!
A Golden Rule: One Task – one file, i.e. DONT put all the Tasks in one single file!!
x = 2; y = 2; z = 3*x^2 + sqrt(x^2 + y^2)+ exp(log(x))
Mathematical expressions: The following applies in MATLAB
Sorry! • There are no “Short-Cuts” if you want to learn LabVIEW!
(except the few shown on the previous page J)
• Practice, practice and practice!
LabVIEW Training: 1 - LabVIEW Training for Students (National Instruments):http://www.ni.com/academic/students/learnlabview/ 2 - LabVIEW Course: http://home.hit.no/~hansha/?training=labview
MathScript Node
Hans-Petter Halvorsen, M.Sc.
MathScript Node
MathScript Node The “MathScript Node” offers an intuitive means of combining graphical and textual code within LabVIEW. Students: Test some of your previous Scripts using the MathScript Node
Using “MathScript Nodes”, you can enter .m file script text directly or import it from a text file.
You can define named inputs and outputs on the MathScript Node border to specify the data to transfer between the graphical LabVIEW environment and the textual MathScript code.
Using MathScript for Simulations
Hans-Petter Halvorsen, M.Sc.
Continuous Signal
Discret Signal Note! Different books use different notations
Discrete Systems
A computer can only deal with discrete signals
Ts = Sampling Time When Ts -> 0, we have a continuous signal, but in a computer that is not possible. k = 0, 1, 2, 3, 4, ....
Example
Discretization
Given the following differential equation: In order to simulate this system in LabVIEW using the Formula Node we need to find the discrete differential equation. We can use e.g., the Euler Approximation:
Ts – Sampling Time
Then we get:
This gives the following discrete differential equation:
Students: Simulate and Plot the discrete system above using a Formula Node and a For Loop in LabVIEW Ts = 0.1 s
MathScript Simulation Example
% Simulation of discrete model clear, clc % Model Parameters a = 0.25;b = 2; % Simulation Parameters Ts = 0.1; %s Tstop = 20; %s uk = 1; x(1) = 0; % Simulation for k=1:(Tstop/Ts) x(k+1) = (1-a*Ts).*x(k) + Ts*b*uk; end
Students: Create and test the MathScript code.
% Plot the Simulation Results k=0:Ts:Tstop; plot (k, x) grid on
Simulation using MathScript Node Students: Try the same example inside LabVIEW using the MathScript Node Just copy and paste the code from the previous example
Control Theory with MathScript
Hans-Petter Halvorsen, M.Sc.
Tools:
LabVIEW
PC
Control System MathScript Frequency Response
Stability Analysis
Discretization
State-space models
Building blocks: Transfer functions
Differential equations
Transfer functions
Hans-Petter Halvorsen, M.Sc.
Block diagrams - MathScript Serial
MathScript code: … H = series(h1,h2)
Example:
Paralell
MathScript code: … H = parallel(h1,h2)
Feedback
MathScript code: … H = feedback(h1,h2)
num=[1]; den=[1, 1]; H1= tf(num, den); num=[1]; den=[1, 1, 1]; H2 = tf(num, den); H = series(H1,H2)
Students: Try this Example
Transfer functions MathScript code: MathScript code: % Transfer Function num = [4]; den = [2, 1]; H = tf(num, den) % Step Response step(H)
% Transfer Function num = [2, 3]; den = [1, 4, 3]; H = tf(num, den) Try these examples
U=1 -> unit step
% Step Response step(H)
State-space Models
Hans-Petter Halvorsen, M.Sc.
State-space models
MathScript: A B C D
= = = =
[1, 2; 3, 4]; [0; 1]; [1, 0]; [0];
Step Response:
Note! The system is unstable
model = ss(A, B, C, D) step(model) Students: Try these Examples
Yes! Can we find the transfer function from SS model?
H = tf(model)
Students: Implement this state-space model in MathScript What is the transfer function?
State-space models – Water Tank Example MathScript: clc, clear Kp = 16.5; A_tank = 78.5; A B C D
= = = =
[0, -1/A_tank; 0, 0]; [Kp/A_tank; 0]; [1, 0]; [0];
model = ss(A, B, C, D) step(model) We see this is a typical integrator Transfer function: H = tf(model)
Students: Try this Examples
Stability Analysis
Hans-Petter Halvorsen, M.Sc.
Loop Transfer Function
MathScript: Hr = ... Hp = ... Hm = ... L = series(series(Hr, Hp), Hm)
The Tracking Function
MathScript: L = ... T = feedback(L, 1)
Det karakteristiske polynom En transferfunksjon kan skrives på følgende generelle polynomform:
• Der telleren til transferfunksjonen beskriver nullpunktene til systemet, mens nevneren beskriver polene til systemet. • Røttene i tellerpolynomet b(s) kalles systemets eller transferfunksjonens nullpunkter
• Røttene i nevnerpolynomet a(s) kalles systemets eller transferfunksjonens poler
Nevnerpolynomet a(s) kalles for transferfunksjonens karakteristiske polynom
Poles and Zeros Given the following System:
Find Poles and Zeros
MathScript: num=... den=… H = tf(num,den) zero(H) pole(H)
num=... den=… H = tf(num,den) or:
roots(num) %Zeros roots(den) %Poles
Poles and Zeros - Solutions
MathScript: %Transfer Function num=[2,1]; den=[0.5, 2, 1]; H=tf(num,den) %Zeros z = zero(H) %roots(num) %Poles p = pole(H) %roots(den)
Impulse/Step Response
impulse(H) step(H)
Asymptotisk stabilt system:
Marginalt stabilt system:
Ustabilt system:
Example T(s)
Dette er den totale transferfunksjonen (“The Tracking transfer function”) fra referansen (r) til utgangen (y) for et gitt system. Systemet blir regulert av en P regulator (proporsjonalregulator).
Implementer (transferfunksjon) og simuler (sprangrespons) systemet i MathScript. Prøv forskjellige verdier av Kp Hva blir resultatet??
Kp=1; num = [Kp]; den = [1, 2, 1, Kp]; H = tf(num, den);
Solutions Asymptotisk stabilt
step(H) More advanced solution: clc clear K = [1, 2, 4]; N = length(K); for i= 1:N Kp = K(i); num = [Kp]; den = [1, 2, 1, Kp]; H = tf(num, den); figure(i) step(H) end
Marginalt stabilt
Ustabilt
Stability Analysis – 2.order systems Masse-Fjær-demper system
Implementer systemet i MathScript. Prøv ulike verdier av zeta slik at vi kan gjenskape de ulike responsene (sprangrespons) som er typisk for et 2.ordens system. Begynn med f.eks. m=1, k=1, d=1
Solutions % Mass-spring-damper clear clc clear all
Prøv ulike verdier av zeta slik at vi kan gjenskape de ulike responsene som er typisk for et 2.ordens system
% Define variables m = 1; d = 1; k = 1; zeta= d/(2*sqrt(m*k)) % Define Transfer function num = 1/m ; den = [1, (d/m), (k/m)]; H = tf(num, den); % Step Response step(H)
Solutions
m=1, k=1, d=1 -> z=0.5 dvs 0 Stabilt (Underdempet)
m=1, k=1, d=2 -> z=1 -> Stabilt (Kritisk dempet)
m=1, k=1, d=-1 -> z=-0.5 dvs z<0 -> Ustabilt
m=1, k=1, d=0 -> z=0 -> Marginalt stabilt
Poles Eksempel:
Systemets poler finner man ved å sette nevneren i transferfunksjonen lik 0
MathScript:
Stabilt
Ustabilt
num = [3]; den = [0.5, 1]; H = tf(num, den) p = poles(H) pzgraph(H) Studenter: Prøv ut dette scriptet!
Polplassering Asymptotisk stabilt system:
Marginalt stabilt system: En eller flere poler ligger på den imaginære akse (har realdelen lik 0), og alle polene er forskjellige/ikke sammenfallende. Dessuten, ingen poler i høyre halvplan
Alle polene ligger i venstre halvplan (negativ realdel). Ingen poler på den imaginære akse.
Ustabilt system: En eller flere poler ligger i høyre halvplan (har realdel større enn 0).
Eller: Det er multiple/sammenfallende poler på den imaginære akse.
Stabilitetsanalyse – Poler – MathScript - Eksempel
Dette er den totale transferfunksjonen (“The Tracking transfer function”) fra referansen (r) til utgangen (y). Systemet blir regulert av en P regulator (proporsjonalregulator).
Implementer (transferfunksjon) og finn polene til systemet vha MathScript. Prøv forskjellige verdier av Kp (Kp=1, Kp=2, Kp=3) Hva blir resultatet??
Stabilitetsanalyse – Poler – MathScript - Løsning MathScript: Kp=1 num = [Kp]; den = [1, 2, 1, Kp]; H = tf(num, den) Dette er den totale transferfunksjonen (“The Tracking transfer function”) fra referansen (r) til utgangen (y). Systemet blir regulert av en P regulator (proporsjonalregulator).
Poler:
figure(1) step(H) poles(H) figure(2) pzmap(H)
Masse-Fjær-demper system – Eksempel - MathScript kode % Mass-spring-damper system clear clc clear all Prøv ulike verdier av zeta slik at vi kan gjenskape de ulike responsene som er typisk for et 2.ordens system.
Metode 1 (Sprangrespons) Metode 2 (Polplassering) Students: Try this Example
% Define variables m = 1;d = 1; k = 1; zeta= d/(2*sqrt(m*k)) % Define Transfer function num = 1/m ; den = [1, (d/m), (k/m)]; H = tf(num, den); % Step Response figure(1), step(H) % Stability Analysis p = poles(H) figure(2), pzmap(H)
Discretization
Hans-Petter Halvorsen, M.Sc.
Discretization Example Given the following continuous system:
We will use the Euler forward method :
Students: Pen and paper: Find the difference equation (discrete differenitial equation) for this system.
Discretization Example - Solutions Given the following continuous system: We will use the Euler forward method :
Discretization in MathScript - Alt. 1 % Simulation of discrete model clear, clc % Model Parameters a = 0.25;b = 2; % Simulation Parameters Ts = 0.1; %s Tstop = 20; %s uk = 1; % Step in u x(1) = 0; % Initial value % Simulation for k=1:(Tstop/Ts) x(k+1) = (1-a*Ts).*x(k) + Ts*b*uk; end % Plot the Simulation Results k=0:Ts:Tstop; plot (k, x) grid on
Students: Implement and Simulate this system in MathScript
Discretization in MathScript - Alt. 2
% Find Discrete model clear clc % Model Parameters a = 0.25; b = 2; Ts = 0.1; %s % A B C D
State-space model = [-a]; = [b]; = [1]; = [0];
model = ss(A,B,C,D) model_discrete = c2d(model, Ts, 'forward') step(model_discrete)
We get the same answer as in previous example! Students: Implement and Simulate this system in MathScript
Discrete State-space Models Example in MathScript
Given the following continuous system:
MathScript
Try with different values for Ts!
% Properties Ts = 0.1; % Continuous System: A = [0, -Ts; 0, 0]; B = [2*Ts, 0]'; C = [1 0]; D = [0]; ssmodel = ss(A, B, C, D); figure(1) step(ssmodel) % Discrete System: ssmodel_discete = c2d(ssmodel, Ts, 'forward’)
figure(2) step(ssmodel_discete) Students: Implement the system above and find the step response using MathScript.
Frequency Response
Hans-Petter Halvorsen, M.Sc.
Frequency Response Example Outside Temperature frequency 1 (year) T = 1 year
frequency 2 (24 hours)
-> Only the gain and phase are different
T = 24 hours
Assume the outdoor temperature is varying like a sine function during a year (frequency 1) or during 24 hours (frequency 2). Then the indoor temperature will be a sine as well, but with different gain. In addition it will have a phase lag.
Inside Temperature frequency 1 (year)
frequency 2 (24 hours)
Frequency Response Example Air Heater
Imput Signal
Output Signal
Dynamic System Amplitude
Frequency
Gain (“forsterkning”)
Phase Lag (“faseforskyvning”)
The frequency response of a system expresses how a sinusoidal signal of a given frequency on the system input is transferred through the system.
Bode Diagram
The x-scale is logarithmic
Gain (“Forsterkningen”) The y-scale is in [dB]
Phase lag (“Faseforkyvningen”) The y-scale is in [degrees]
Vanligvis er enheten for frekvens Hertz [Hz], men i frekvensrespons/Bodediagram brukes radianer ω [rad/s]. Sammenhengen
Bode Diagram You can find the Bode diagram from experiments on the physical prosess or from the transfer function (the model of the system). A simple sketch of the Bode diagram for a given system:
𝜔𝑐 ∆𝐾
𝜑
𝜔180
𝐿𝑜𝑔 𝜔 ω [rad/s]
𝐿𝑜𝑔 𝜔 ω [rad/s]
è The Bode diagram gives a simple Graphical overview of the Frequency Response for a given system. A Tool for Analyzing the Stability properties of the Control System
Bode Diagram – MathScript Example Given the following transfer function:
We will use MathScript to find the Frequency Response/Bode Diagram:
% We define the transfer function: K = 1; T = 1; num = [K]; den = [T, 1]; H = tf(num, den) % We plot the Bode diagram: bode(H); % We add grid to the plot: subplot(2,1,1) grid on subplot(2,1,2) grid on
Students: Implement this example in MathScript
Cont. on bext page->
Bode Diagram – MathScript Example cont. Given the following transfer function:
Instead of Plotting the Bode Diagram we can also use the bode function for calculation and showing the data as well: ... wlist = [0.01, 0.1, 1, 100];[mag, phase, w] = magdB = 20*log10(mag); freq_data = [w, magdB,
2 ,3 ,5 ,10, bode(H, wlist); % Convert to dB phase]
MathScript gives the following results:
Students: Try this code also
Bode Diagram – MathScript Example cont.
w We see that the Calculated Data and the Bode Diagram gives the same values
A(w) [dB]
ϕ(w) [deg.]
Bode Diagram – MathScript Example Given the following transfer function:
Students: Plot the Bode Diagram for the given transfer function using MathScript
Bode Diagram – MathScript Example - Solutions or: clear, clc % Transfer function num=[1]; den1=[1,0]; den2=[1,1] den3=[1,1] den = conv(den1,conv(den2,den3)); H = tf(num, den) % Bode Diagram bode(H) subplot(2,1,1) grid on subplot(2,1,2) grid on
or:
clear, clc % Transfer function num=[1]; den=[1,2,1,0]; H = tf(num, den) % Bode Diagram bode(H) subplot(2,1,1) grid on subplot(2,1,2) grid on
Stability Analysis with Frequency Response
Hans-Petter Halvorsen, M.Sc.
Frequency Response and Stability Analysis Bode Diagram
ωc and ω180 are called the crossoverfrequencies (“kryssfrekvens”)
ΔK is the gain margin (GM) of the system (“Forsterkningsmargin”). How much the loop gain can increase before the system becomes unstable ϕ is the phase margin (PM) of the system (“Fasemargin”). Hvor mye fasedreining systemet tåler før det blir ustabilt. We have the following: Asymptotisk stabilt system Marginalt stabilt system Ustabilt system
Stability Analysis - Summary Tidsplanet Asymptotisk stabilt system
Frekvensrespons/Bodediagram
Marginalt stabilt system
Ustabilt system
Det komplekse plan Asymptotisk stabilt system Marginalt stabilt system Ustabilt system
Stability Analysis using Frequency Response within MathScript Hr = ... Hp = ... Hm = ... L = series(series(Hr, Hp), Hm) bode(L) margin(L) [gm, pm, w180, wc] = margin(H); gmdB = 20*log10(gm)
bode
margin
Stability Analysis – MathScript Example
Students: • Set Kp=0.5 (in this example Kp will be the loop gain). • Plot the Bode diagram. • Find ωc, ω180, ΔK, φ – both manually from the plot and compare with the results from MathScript (margin function).
Stability Analysis – MathScript Example - Solutions MathScript: clear, clc, clf %
Define Transfer functions
% The Process Transfer function Hp(s) num_p=[1]; den1=[1, 0]; den2=[1, 1]; den_p = conv(den1,den2); Hp = tf(num_p, den_p) % The Measurement Transfer function Hm(s) num_m=[1]; den_m=[3, 1]; Hm = tf(num_m, den_m) % The Controller Transfer function Hr(s) Kp = 0.5; Hr = tf(Kp) % The Loop Transfer function L = series(series(Hr, Hp), Hm)
% Bode Diagram figure(1) bode(L) subplot(2,1,1) grid on subplot(2,1,2) grid on figure(2) margin(L) [gm, pm, w180, wc] = margin(L); wc w180 gmdB = 20*log10(gm) pm
Cont. on next page ->
Stability Analysis – Example - Solutions Tip: Adjust the scale on the axes to make it easier to read the different values
Bode Diagram and Results:
GM
0.0 1
wc
0.1
PM 0.0
0.1
w180
Stability Analysis – Example cont. Results from previous page:
Kp=0.5 ΔK
Students: • How much can we increase Kp before the system becomes unstable? • Plot the Step Response and find the Poles for different Kp (asymtotically stable, marginally stable, unstable)
Stability Analysis – Example cont. - Solutions Kp=0.5 -> ΔK=2.67 (from previous page) Kp (marginalt stabilt) = Kp x ΔK = 0.5 x 2.67 = 1.34 Dette gir følgende: Kp = 0.5 -> Asymptotisk Stabilt System Kp = 1.34 -> Marginal Stabilt System Kp = 2 (f.eks.) -> Ustabilt System Kp = Kp > 2
MathScript Kode ...
... t = 0:0.1:50; figure(4) step(T, t) p = poles(T) figure(5) pzmap(T) See plots on next page ->
Kp = 0.5
Kp = 1.34
Kp = 2
“Golden rules” of Stability Margins for a Control System Gain Margin: (“Forsterkningsmargin”)
Phase Margin: (“Fasemargin”)
Merk! Siden (alt)for dårlig stabilitet må unngås, mens (alt)for god stabilitet kan aksepteres, er de nedre grensene for GM og PM kritiske, mens de øvre grensene er anbefalte, men ikke kritiske.
Frequency Response MathScript functions
Select one of the following Challenges
Hans-Petter Halvorsen, M.Sc.
Mass-Spring-Damper System
http://www.techteach.no/simview/mass_spring_damper/index.php Students: Simulate this system using MathScript. Plot the position, speed and the accelleration. Test with different values on m, k and d.
Air Heater
Students: Simulate this system using MathScript
Frequency Response Analysis Given the following system with time-delay:
Use the bode and margin functions in MathScript to plot the frequency response in a Bode diagram. Find the following: The crossover-frequencies ωc and ω180 The gain margin, GM (ΔK) The phase margin, PM (φ) Find the poles for the system. Draw the poles in the imaginary plane. Is the system stable? Discuss the results.
Hans-Petter Halvorsen, M.Sc. University College of Southeast Norway www.usn.no E-mail: [email protected] Blog: http://home.hit.no/~hansha/