Download as pdf or txt
Download as pdf or txt
You are on page 1of 109

LabVIEW

MathScript

Hans-Petter Halvorsen, M.Sc.


LabVIEW Installation
Note! You get the Serial Number from your Teacher,
but the software can be used for 30 days before you
Download the software here: 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 custom-
made 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 add-
on 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;
Students: Try these examples
>> X=6;
>> x+X >> x=3
x =
ans = 3
11
>> 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

The “clear” command deletes all


existing variables” from the memory
>> clear
>> clc
The “clc” command removes everything
from the Command Window
clc – clear command window

Students: Try these commands


MathScript Basics
Built-in constants
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=2;
>> z1=3+3i; >> b=0;
>> z2=3+5i;
A =
>> z = z1+z2 >> a/b
78.5398
z =
6.0000 + 8.0000i
Students: Try these examples
MathScript Basics Matematical Expressions

Students: Try this example MATLAB


log(x)
log10(x)
>> x=2;

Which are correct?


>> y=3*x+2/2 sqrt(x)
y =
7 exp(x)
>> y=(3*x+2)/2
y = x^2
4

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 x = 3;
y = 2*x + 4;
y(3) = ?
Vectors: 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] >> x*y
>> y*x
>> y = [4; 5; 6] Students: Define these
vectors in MATLAB. Try >> x*z
>> z = [8, 9, 10]' also to multiply the >> y*z
different vectors like this: ...

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 2
3 4

or:
Try these examples
>> A = [1, 2; 3, 4]
>> B+C
>> B-C
A = 1 2
>> B/C
3 4 >> B*C
>> B.*C
>> B'*C
...
Matrices
Given the following matrices:

Define the matrices and try these examples

>> rank(A)
>> det(A)
>> inv(A)
>> inv(B)
>> eig(A)
>> A*B >> A*(B*C) >> inv(A)
>> B*A >> (A*B)*C >> inv(B)
>> A+B >> (A+B)*C >> diag(A)
>> B' >> A*C + C*B >> inv(A)*A
>> B'*C >> (A+inv(B))*C >> A*inv(A)
>> A*B'
>> A'*B’ ... ...
>> A.*B
...
Creating Scripts

Hans-Petter Halvorsen, M.Sc.


Scripts (m-files)
MATLAB Scrips are saved as socalled
.m files (file extension is .m)

Script Editor 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)

%plotting cos(x)
Run the Script subplot(2,2,2)
plot(x,y2)

%plotting tan(x)
subplot(2,2,3)
plot(x,y3)

%plotting atan(x)
Students: Try this example subplot(2,2,4)
plot(x,y4)
Plotting

Hans-Petter Halvorsen, M.Sc.


Plotting in MathScript interval on x axis

x = 0:5;
Example:

y(t) = 2x + 4 y = 2*x + 4;

plot(x,y)

Useful MathScript functions


Students: Try this
for plotting:

xlabel
grid ylabel
axis
title text
Students: Try these functions

How does they work?


Type help <function name> in Command window

How do you get another color? or line type?


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
Students: Try this example
plot Create a Plot >> x=0:0.1:2*pi;
figure Define a new Figure/Plot window
>> y=sin(x);
>> plot(x,y)
grid Create Grid lines in a plot
on/off >> title('Plot Example')
title Add Title to current plot >> xlabel('x')
>> ylabel('y=sin(x)')
xlabel Add a Label on the x-axis
>> grid on
ylabel Add a Label on the x-axis >> axis([0,2*pi,-1,1])
>> legend(’Temperature')
axis Set xmin,xmax,ymin,ymax

hold Add several plots in the same Figure


on/off Students: Try also to change
legend Create a legend in the corner (or at some of the commands and see
a specified position) of the plot
what happens with the plot
subplot Divide a Figure into several Subplots
Plotting Subplot
>>
>>
>>
x=0:0.1:2*pi;
y=sin(x);
y2=cos(x);
Students: Try these >> y3=tan(x);
examples
>> subplot(3,1,1)
>> x=0:0.1:2*pi; >> plot(x,y)
>> y=sin(x);
>> subplot(3,1,2)
>> y2=cos(x); >> plot(x,y2)

>> subplot(2,1,1) >> subplot(3,1,3)


>> plot(x,y3)
>> plot(x,y)
>> x=0:0.1:2*pi;
>> subplot(2,1,2) >> y=sin(x);
>> y2=cos(x);
>> plot(x,y2) >> 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

You Create the


Return value 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
Return value input

function Tf = fahrenheit(Tc) Tc = 23;


Tf = fahrenheit(Tc)
Tf = (9/5)*Tc + 32;
Dette kan enten gjøres fra Command
window eller Script window
The function body
Return value

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) plot(t,Tc, t,Tf)


% This function converts a temperature from celsius to
fahrenheit
title('Temperature Simulation')
xlabel('t')
Tf = (9/5)*Tc + 32; ylabel('Temperature')
grid on
axis([0,24, 0, 120]);
legend('Celcius', 'Fahrenheit')
Tips & Tricks

Hans-Petter Halvorsen, M.Sc.


Tips & Tricks
Use Comments (%) Tips & Tricks
% This is a comment
x=2; % Comment2 DO NOT use ”spaces” in Filename or names that
y=3*x % Comment3 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

Yes:
Use english names on variables, functions, files, etc. This is No:
common practice in programming! a=2;
Use always variables – Do not use numbers directly in the b=4; y=2+4
expressions! y=a+b
Always include these
lines in your Script
Functions: clear
• Only ONE function in each File! clc
• The Filename (.m) AND the Name of the Function MUST be close all
the same! …
Tips & Tricks Use help in order to find out
how to use a function in
Greek!letters:!In!maths!and!control!theory!it!is!common!to!use!greek! MATLAB. In order to get help
letters!in!formulas,!etc.!These!cannot!be!used!directly!in!MATLAB,!so! for the tf function, type the
you!need!to!find!other!good!alternatives.!Examples:! following in the Command
window:
!! ! –!w0!
help tf
!! –!zeta!or!just!z!

etc.!
Mathematical expressions:
The following applies in MATLAB
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))
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/learn-
labview/
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
Discrete Systems

Discret Signal A computer can only deal


with discrete signals

Note!
Different Ts = Sampling Time
books use
different When Ts -> 0, we have a continuous signal,
notations 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 of discrete model
Simulation clear, clc

Example % 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

% Plot the Simulation Results


Students: Create and test the k=0:Ts:Tstop;
MathScript code. 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 Paralell Feedback

MathScript code: MathScript code: MathScript code:


… … …
H = series(h1,h2) H = parallel(h1,h2) H = feedback(h1,h2)

Example: num=[1];
den=[1, 1];
H1= tf(num, den);

num=[1];
Students: Try this Example
den=[1, 1, 1];
H2 = tf(num, den);

H = series(H1,H2)
Transfer functions
MathScript code:
% Transfer Function
MathScript code: num = [2, 3];
% Transfer Function den = [1, 4, 3];
num = [4]; H = tf(num, den)
den = [2, 1];
H = tf(num, den) Try these % Step Response
examples step(H)
% Step Response
step(H)

U=1 -> unit step


State-space Models

Hans-Petter Halvorsen, M.Sc.


State-space models

MathScript:
A = [1, 2; 3, 4]; Step Response:
Note! The system is
B = [0; 1];
unstable
C = [1, 0];
D = [0];

model = ss(A, B, C, D)

step(model) Yes!
Can we find the transfer
Students: Try these Examples 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 = [0, -1/A_tank; 0, 0];


B = [Kp/A_tank; 0];
C = [1, 0];
D = [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=... num=...
den=… den=…
H = tf(num,den) H = tf(num,den)
or:
zero(H) roots(num) %Zeros
pole(H) 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; Solutions
num = [Kp];
den = [1, 2, 1, Kp];
H = tf(num, den);
Asymptotisk stabilt
step(H)
More advanced solution:
clc
clear

K = [1, 2, 4];
Marginalt stabilt
N = length(K);

for i= 1:N
Kp = K(i);
num = [Kp];
den = [1, 2, 1, Kp];
H = tf(num, den);
figure(i)
Ustabilt
step(H)
end
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

% Define variables
Prøv ulike verdier av zeta slik m = 1;
at vi kan gjenskape de ulike d = 1;
responsene som er typisk for k = 1;
et 2.ordens system 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<z<1 -> Stabilt (Underdempet) m=1, k=1, d=-1 -> z=-0.5
dvs z<0 -> Ustabilt

m=1, k=1, d=2 -> z=1 m=1, k=1, d=0 -> z=0
-> Stabilt (Kritisk dempet) -> Marginalt stabilt
Poles
Eksempel:

Systemets poler finner man ved å sette


nevneren i transferfunksjonen lik 0

MathScript:
num = [3];
den = [0.5, 1];
Stabilt H = tf(num, den)
Ustabilt
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) figure(1)
til utgangen (y). Systemet blir regulert av en step(H)
P regulator (proporsjonalregulator).
poles(H)

figure(2)
pzmap(H)
Poler:
Masse-Fjær-demper system – Eksempel - MathScript kode

% Mass-spring-damper system
clear
clc
clear all

% Define variables
Prøv ulike verdier av zeta slik at vi m = 1;d = 1; k = 1;
kan gjenskape de ulike responsene zeta= d/(2*sqrt(m*k))
som er typisk for et 2.ordens
system. % Define Transfer function
num = 1/m ;
den = [1, (d/m), (k/m)];
H = tf(num, den);

% Step Response
Metode 1 figure(1), step(H)
(Sprangrespons)
Metode 2 % Stability Analysis
(Polplassering) p = poles(H)
figure(2), pzmap(H)

Students: Try this Example


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
Students:
% Plot the Simulation Results Implement and Simulate
k=0:Ts:Tstop; this system in MathScript
plot (k, x)
grid on
Discretization in MathScript - Alt. 2

% Find Discrete model


clear
clc

% Model Parameters
a = 0.25;
b = 2;
Ts = 0.1; %s

% State-space model
A = [-a];
B = [b];
We get the same answer as in
C = [1];
D = [0];
previous example!
Students:
model = ss(A,B,C,D)
Implement and Simulate
model_discrete = c2d(model, Ts, 'forward')
this system in MathScript
step(model_discrete)
Discrete State-space Models Example
in MathScript
Given the following continuous system:
Try with different values for Ts!
MathScript
% 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

-> Only the gain and


frequency 2 (24 hours) phase are different

T = 24 hours

Inside Temperature
frequency 1 (year)
Assume the outdoor temperature is
varying like a sine function during a year
(frequency 1) or during 24 hours
(frequency 2).
frequency 2 (24 hours)
Then the indoor temperature will be a
sine as well, but with different gain. In
addition it will have a phase lag.
Frequency Response Example
Air Heater

Imput Signal Output Signal

Dynamic
System

Amplitude Frequency
Gain Phase Lag
(“forsterkning”) (“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:

𝜔𝑐
𝐿𝑜𝑔 𝜔 ω [rad/s]
∆𝐾

𝜑 𝜔180
𝐿𝑜𝑔 𝜔 ω [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 define the transfer function:


We will use MathScript to find the K = 1;
Frequency Response/Bode Diagram: 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, 2 ,3 ,5 ,10,
100];[mag, phase, w] = bode(H, wlist);
magdB = 20*log10(mag); % Convert to dB
freq_data = [w, magdB, phase]

MathScript gives the following results:

Students: Try this code also


Bode Diagram – MathScript Example cont.

w A(w) [dB] ϕ(w) [deg.]

We see that the Calculated Data and the


Bode Diagram gives the same values
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) clear, clc
subplot(2,1,1) % Transfer function
grid on num=[1];
subplot(2,1,2) den=[1,2,1,0];
H = tf(num, den)
grid on
% Bode Diagram
bode(H)
or: 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 crossover-
frequencies (“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]; % Bode Diagram
den1=[1, 0]; figure(1)
den2=[1, 1]; bode(L)
den_p = conv(den1,den2); subplot(2,1,1)
Hp = tf(num_p, den_p) grid on
subplot(2,1,2)
% The Measurement Transfer function Hm(s) grid on
num_m=[1];
den_m=[3, 1]; figure(2)
Hm = tf(num_m, den_m) margin(L)

% The Controller Transfer function Hr(s) [gm, pm, w180, wc] = margin(L);
Kp = 0.5;
Hr = tf(Kp) wc
w180
% The Loop Transfer function gmdB = 20*log10(gm)
L = series(series(Hr, Hp), Hm) pm

Cont. on next page ->


Stability Analysis – Example - Solutions
Bode Diagram and Results: Tip: Adjust the scale on the axes to make
it easier to read the different values

GM

wc
0.0 0.1
1

PM

0.1
w180
0.0
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 MathScript Kode
Kp = 2 (f.eks.) -> Ustabilt System Kp = ...
Kp > 2
...

t = 0:0.1:50;
figure(4)
step(T, t)
p = poles(T)
figure(5)
pzmap(T)

See plots on next page ->


Kp = 1.34
Kp = 0.5
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: hans.p.halvorsen@hit.no
Blog: http://home.hit.no/~hansha/

You might also like