powered by

CONTROLLER FOR AN INVERTED PENDULUM
This Scilab tutorial is dedicated to the study of a linear quadratic regulator for an
inverted pendulum based on optimal control theory. In this tutorial the reader willlearn how to develop a controller for an inverted pendulum starting from theequations of motion and how to use the animated plots in Scilab/Xcos.
Level

This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

www.openeering.com

Step 1: Problem description
In this tutorial we use Scilab to develop a controller that maintains a rod in
its vertical position (unstable position). In our example, the rod is hinged
on a support that allows only one type of lateral movement.

As reported in the figure on the right, the inverted pendulum is composedby a vertical rod (homogeneous rod with lengthand mass) hingedon a support rod (homogeneous rod with lengthand mass). Thevertical rod is in an orthogonal plane with respect to the moving base(rotational joint).

In our experiment, we suppose to know (at each time step) the support
angle
of the moving base and the angleof the vertical rod.
Moreover, the angle
is the only parameter in which we can act tocontrol the entire system by using a DC motor.

A schematic drawing of an inverted pendulum with a moving base.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 2/32

Step 2: Roadmap
This tutorial is particularly challenging and is the first Openeering tutorial
with five puffins.
Since the comprehension of this tutorial is demanding and some conceptsof Scilab programming are taken for granted, we highly recommend thereader to download the entire source code and Xcos schemes from theregistered user area.

Unlike the previous tutorials, in this case the source code should be used
as a support documentation material. Source codes and Xcos schemes
should be read together with these pages.

In this tutorial the following topics are covered:
Problem description and system equations;Non-linear system solution;

Descriptions
Problem description and System equations
Non-linear system solution
Linear-quadratic regulator
Solving self-erecting problem
Plotting animations in Scilab and Xcos
Conclusions and exercises

Steps
3-7
8 - 1213 - 20
21 – 24
25 - 27
28 - 31

Linear-quadratic regulator;
Solving the self-erecting problem
Plotting animations in Scilab and Xcos
References and exercises

Note: All the simulations are done using Scilab 5.4.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 3/32

Step 3: Problem data
The problem is described in term of the angles data
angular velocities and .

andand their

For real applications, it is assumed that it is possible to have the absolute
position of the angle dataandat each time step, while the angularvelocities andare recovered with an interpolation procedure.

Problem measure variables:
Absolute angle position of the first rod [rad];Angular velocity of the first rod[rad/s];Absolute angle position of the second rod[rad];
Angular velocity of the second rod[rad/s];Voltage control[V].

Problem data:
The control variable is the Voltage
motor.

which can be applied to theMoment of inertia of the first rod
Length of the first rod
Mass of the second
Length of the second rod

On the right, we report data and notations used throughout the text.

[m];
[kg];
[m];

Moment of inertia of the second rod
Motor torqueGear ratio;
Internal motor resistor

In this tutorial we use some shortcuts (reported on the right) in order tosimplify some equations. These shortcuts are used when managing theequations using symbolic computations.

2[kg m ];

2[kg m ];;[Ohm].

Shortcuts:
In this tutorial, all the symbolic computations are done using Maxima
which is an open source project for symbolic computations (seeReferences at Step 28).

;
;
;
;
;
;
;

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 4/32

Step 4: System equations
To obtain the system equations we use the Euler-Lagrange approach. It isnecessary to define the kinetic energy and the potential energy withrespect to the generalized free coordinates of the system that, in ourcase, are the angles and their derivatives.
In particular for the support rod we have:Potential energy:;

Kinetic energy:;

while for the vertical rod we have:Potential energy:;

Kinetic energy:.

The kinetic energy
can be obtained in an easy way using the Koenig’s
theorem since the rod is homogeneous, which gives

whereis the inertia with respect to the center of mass,and
. The can be express in terms ofusing the theoremof Huygens-Steiner which gives.

The kinetic energy
can also be obtained using integration procedure
over infinitesimal segments, i.e.

Some adopted conventions
where

is the density andis the section area.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 5/32

Step 5: System equations
The Lagrangian of the system can be written as
The nonlinear system of equations is:in the generalized coordinates
and .

and

and generalized velocities

The equations of motion are obtained using the Euler-Lagrange equation:

This expresses the equations starting from the system kinetic energy andsystem potential energy.

where:The equations of motion are reported on the right (further details will bepresented in the following steps).

is the applied torque to the support rod;is the momentum of inertia of the first rod;is the momentum of inertia of the second rod.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 6/32

Step 6: System equations (details of derivation)
Details of the derivation of equations are reported here, while the Maxima
script we used for the symbolic computation is reported on the right.
Maxima script used to obtain the system equations:/* Equations of motion */theta1: theta1(t);theta2: theta2(t);For the first equations we have:omega1: diff(theta1,t);omega2: diff(theta2,t);That corresponds exactly to the eq1_a and eq1_b of the Maxima script.
The sum of eq1_a and eq1_b gives the equation of motion where the freevariable is .
For the second equations we have:/* Lagrangian of the system */T1: 1/2*J1*omega1^2;
U1: 0;
T2: 1/2*J2*omega2^2 + 1/2*M2*(l1*omega1)^2 +1/2*M2*l1*l2*omega1*omega2*cos(theta2);
U2: M2*g*l2/2*cos(theta2);
L: (T1+T2) -(U1+U2);/* Lagrangian derivation */eq1_a: expand(diff(diff(L,omega1),t));eq1_b: diff(L,theta1);
eq1: eq1_a + eq1_b;
eq2_a: diff(diff(L,omega2),t);eq2_b: expand(diff(L,theta2));eq2: eq2_a + eq2_b;

That corresponds exactly to the eq2_a and eq2_b of the Maxima script.
The sum of eq2_a and eq2_b gives the equation of motion where the freevariable is .

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 7/32

Step 7: System equations
The applied torque is given by a DC motor which is controlled in voltage. This relation is typically written as:
The nonlinear complete model is:

where

where
represents the gear ratio;is the torque constant that depends on the motor geometry;is the current of the motor;
is the voltage used to control the motor;
represents the counter electromotive force;is the resistor of the rotor winding.

We now use the following notations for the nonlinear system

where shortcuts notations are explained at step 3.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 8/32

Step 8: Nonlinear system solution
In order to solve the nonlinear system it is necessary to state the problem
in the form
. This can be easy done since the system islinear inand .

We obtain the following expressions using the Maxima script on the right.
The expressions forandare:Maxima script used to obtain the expressions forand:/* Non-linear system formulation */eqnl1 : a*theta1_pp + b*theta2_pp*cos(theta2) b*theta2_p^2*sin(theta2) = (e*V - f*theta1_p);
eqnl2 : b*theta1_pp*cos(theta2) + c*theta2_pp d*sin(theta2) = 0;
sol: linsolve([eqnl1,eqnl2],[theta1_pp,theta2_pp]);which leads the following state representation of the system:
display(sol[1]);display(sol[2]);Note: We always have

A Scilab Tutorial On An Inverted Pendulum.

www.openeering.com

page 9/32

Step 9: Free evolution in Scilab// Inverted pendulum parameters
J1 = 0.05; l1 = 0.2; M2 = 0.15; l2 = 0.5;
J2 = M2*l2^2/3; Kphi = 0.008; N = 15; R = 2.5; g = 9.8;

We now use previous equations to write our Scilab code. In this example
we study the free evolution () of the nonlinear system. The solution
is implemented in Scilab language where the numerical solution is
obtained using the ode Scilab function*.

// Derived dataa = J1 + M2*l1^2; b = 1/2*M2*l1*l2; c = J2;
d = 1/2*M2*g*l2; e = N*Kphi/R; f = N^2*Kphi^2/R;
delta = a*c-b^2;function ydot=inv_nl_pend(t, y)// The non-linear system inverted pendulum// get variable
theta1 = y(1); theta2 = y(2);theta1p = y(3); theta2p = y(4);s2 = sin(theta2); c2 = cos(theta2);
den = b^2*c2^2 - a*c;
Vt = 0;ydot = zeros(4,1);
ydot(1) = theta1p;ydot(2) = theta2p;ydot(3) = -(c*e*Vt + b*c*s2*theta2p^2-b*d*c2*s2c*f*theta1p)/den;ydot(4) = (b*e*c2*Vt + b^2*c2*s2*theta2p^2-a*d*s2b*f*theta1p*c2)/den;
endfunction

We study the problem using the initial conditions:

The obtained results are reported on the figure below.

// Initial conditiony0 = [0;90*%pi/180;0;0];t = linspace(0,5000,2001)/1000;
t0 = 0;// Solving the system
sol = ode(y0, t0, t, inv_nl_pend);

Figure 1: Free evolution plot
* Refer to the tutorial “Modeling in Scilab: pay attention to the right approach - Part1” for more information on how to model a physical system described by ODE
using Scilab standard programming language.

A Scilab Tutorial On An Inverted Pendulum// Plotting of model dataplot(t, sol(1:2,:)/%pi*180);
p = get("hdl");p.children.mark_mode = "on";p.children.thickness = 3;
xlabel("t [s]"); ylabel("[°]");
legend(["$\theta_1$";"$\theta_2$"]);

www.openeering.com

page 10/32

Step 10: Free evolution using Xcos
The Xcos scheme that implements the previous system is available in the
Xcos file inv_pend.zcos (see figure) and it uses the following blocks:

A “CONST_m” constant for modeling thesignal (equal to zeroin this case);

A superblock that models the nonlinear system (see step 11);
A “MUX” block to split signals;
A “TOWS_c” block for saving data to workspace that gives thevalues of the angles to a variable named sol;Figure 3: The Xcos scheme for free evolution

Figure 2: data to Scilab workspace configuration

All files are available for download in the Openeering registered users’area. Again, we highly recommend downloading the source codes for abetter understanding of this tutorial.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 11/32

Step 11: Nonlinear system block
The modeling of the nonlinear system block is reported on the right andit uses the following basic blocks:
Four integration blocks for recovering the angles starting from theangular accelerations;Two expression blocks that model nonlinearities. The two
expressions are exactly the two differential equations described instep 8.

Figure 4: The nonlinear system block

Step 12: Plot the results
Since the variable sol contains the results of the Xcos simulation, we canplot the two angles andusing the command:plot(sol.time, sol.values*180/%pi)

Figure 5: Angles positions at time steps

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 12/32

Step 13: Linearized model
It is possible to linearize the model around the point

using small angle displacements and small velocity displacements having
the following approximations:andMaxima script used to obtain the state model representation:/* Maxima script for obtaining state representation of an
inverted pendulum in V*/
e : N*Kt/R;
f : N^2*Kt^2/R;.

This gives:/* System *//* tau = e*V - f*theta1_p */eq1 : a*theta1_pp + b*theta2_pp = e*V - f*theta1_p;
eq2 : c*theta2_pp + b*theta1_pp - d*theta2 = 0;Hence we use the Maxima script on the right to obtain the state model
representation of the system:

sol: linsolve([eq1,eq2],[theta1_pp,theta2_pp]);/* Theta1_pp processing */res1 : expand(rhs(sol[1]));eq1_theta2 : factor(part(res1,2));
eq1_theta1_p : factor(part(res1,3));
eq1_V : factor(part(res1,1));/* Theta2_pp processing */res2 : expand(rhs(sol[2]));eq2_theta2 : factor(part(res2,2));eq2_theta1_p : factor(part(res2,3));
eq2_V : factor(part(res2,1));

In system theory, this system is typically written in the from.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 13/32

Step 14: Transfer functions and stability analysis
If we apply a Laplace transformation*, it is possible to obtain the transfer
function (in terms of control variable )and.

Hence, from the relations

Maxima script used to obtain the transfer functions:
we have/* Maxima script for transfer functions */eq1 : a*s^2*theta1_s + b*s^2*theta2_s = tau_s;
eq2 : b*s^2*theta1_s + c*s^2*theta2_s - d*theta2_s = 0;
sol: linsolve([eq1,eq2],[theta1_s,theta2_s]);

and

W1_s : rhs(sol[1])/tau_s;
W2_s : rhs(sol[2])/tau_s;

Since
the poles of the transfer function
are both reals and so
the system are unstable.
Note: It is left as an exercise to prove the same fact when the controller isexpressed in term of Voltage instead of torque applied.

*Refer to the tutorial “Introduction to Control Systems in Scilab” for more
information on state-space, transfer function representation and converting
methods.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 14/32

Step 15: Using the Scilab control toolbox
Here, in the right, we report the computation (in ) using the Scilab control
toolbox CACSD.

The state equation iswith// Derived dataa = J1 + M2*l1^2;
b = 1/2*M2*l1*l2;
c = J2;
d = 1/2*M2*g*l2;
e = N*Kphi/R;
f = N^2*Kphi^2/R;
delta = a*c-b^2;

andwhile the observer equation is

where
and

// Inverted pendulum parameters
J1 = 0.05;
l1 = 0.2;
M2 = 0.15;
l2 = 0.5;
J2 = M2*l2^2/3;
Kphi = 0.008;
N = 15;R = 2.5;
g = 9.8;// Define system matrix (in tau)A = [0 0 1 0; 0 0 0 1; 0 -b*d/delta 0 0; 0 a*d/delta 00];
B = [0; 0; c/delta; -b/delta]
C = [1 0 0 0; 0 1 0 0];
D = [0;0];.

// State space
sl = syslin('c',A,B,C,D)
h = ss2tf(sl)Note: It is left as an exercise to prove the same fact when the controller isexpressed in term of Voltage instead of torque applied.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 15/32

The Scilab function used to compute the controller is LQR:

Step 16: Optimal control
In optimal control theory, a linear-quadratic (LQ) regulator consists offeedback controller of the form

[K, X] = lqr(PSys)
that minimizes the following index of quality

where:

K : is the Kalman gain such thatwhere
is a positive semi-definitive matrix andis a positive definite
matrix. The matrix represents the weight associated with the state while
represents the weight associated with the input.

is stable;

P: is the stabilizing solution of the Riccati equation.

Under these assumptions it is possible to find that:
The P system is obtained using the following commands:
whereis the solution of the Riccati equation

In order to develop this kind of controller it is necessary to check its
controllability. The controllability means that for any
and for any
statesandthere exists an input
such that the system is takenfrom initial state
to the final. This allows the system toconverge towards the desire state since it is possible to place the poles ofthe system everywhere in the complex plane.

A Scilab Tutorial On An Inverted Pendulum

Q = diag([100,100,1,1]); // (4 states, 1 input)
R = 1;
nstates = 4;
Big = sysdiag(Q,R);// Now we calculate C1 and D12[w,wp] = fullrf(Big);
C1=wp(:,1:nstate);
D12=wp(:,nstate:$);//[C1,D12]'*[C1,D12]=Big
PSys = syslin('c',A,B,C1,D12); // The sys (cont-time)[K,P] = lqr(PSys)
spec(A+B*K)// check stability

where nstate denotes the number of state variables.

www.openeering.com

page 16/32

Step 17: Controllability proof

Scilab script to detect controllability:

In order to develop a LQ regulator it is necessary to prove the system
controllability and hence the possibility to allocate the eigenvalues to yourpreference.

// Check controllability
AB = [B, A*B, A*A*B, A*A*A*B]
rank(AB)
spec(AB)

Hence, it is necessary to check that

where
Maxima script used to check the controllability of the system:
and.

Using the Scilab and Maxima codes on the right, it easy to prove, that therank is 4.

Note: It is left as an exercise to prove the same fact when the controller isexpressed in term of torque applied instead of Voltage control.

A Scilab Tutorial On An Inverted Pendulum/* Controllability check */a0 : Kphi*N;
a1 : b*d/delta;
a2 : a*d/delta;
a5 : c/delta*Kphi*N/R
a3 : a5 * a0;
a6 : b/delta*Kphi*N/R;
a4 : a6 * a0;
A : matrix([0, 0, 1, 0], [0, 0, 0, 1], [0, -a1, -a5*a0,0], [0, a2, a6*a0, 0]);B : matrix([0], [0], [a5], [-a6]);
R : addcol(B,A.B,A.(A.B),A.(A.(A.B)));
detR : factor(expand(determinant(R)));

www.openeering.com

page 17/32

Step 18: LQ regulator summary
To put everything together, the development of a LQ regulator requires
computing the Kalman gain matrix. The complete Scilab code for the LQ
regulator is reported on the right.

// Inverted pendulum data
J1 = 0.005; l1 = 0.2;
M2 = 0.15; l2 = 0.5; J2 = M2*l2^2/3;
Kphi = 0.008; N = 15; R = 2.5;
g = 9.8;

The LQ regulator is computed using the Scilab function lqr which requires
as input the state space representation of the system.

// Derived dataa = J1 + M2*l1^2; b = 1/2*M2*l1*l2;
c = J2; d = 1/2*M2*g*l2;
e = N*Kphi/R; f = N^2*Kphi^2/R;
delta = a*c-b^2;

The lqr function computes the regulator associated to the L2 norm of(cost function) where

and// Check contollability
AB = [B, A*B, A*A*B, A*A*A*B]
rank(AB)
spec(AB).
The computation ofandare done using the full rank factorization
using the Scilab command fullrf.

A Scilab Tutorial On An Inverted Pendulum// Define system matrix (in tau)A = [0 0 1 0; 0 0 0 1; 0 -b*d/delta -c/delta*f 0; 0
a*d/delta b/delta*f 0];
B = [0; 0; c/delta*e; -b/delta*e]
C = [1 0 0 0; 0 1 0 0];
D = [0;0];// LQ projectQ = diag([100,100,10,10]);// Usual notations
x'Qx + u'Ru (4 states, 1 input)
R = 1;
Big = sysdiag(Q,R);// Now we calculate C1
and D12
nstates = 4;
[w,wp] = fullrf(Big);C1=wp(:,1:nstates);D12=wp(:,$:$);//[C1,D12]'*[C1,D12]=BigP = syslin('c',A,B,C1,D12);// The plant(continuous-time)[K,X] = lqr(P)
spec(A+B*K)// check stability

www.openeering.com

page 18/32

Step 19: LQ regulator in Xcos
The LQ regulator is here described using an Xcos scheme. The values of
K1, K2, K3 and K4 are given from the previous step.
In this configuration it is possible to study the system under noise
perturbation.

The context configuration parameters are:// Inverted pendulum parameters
J1 = 0.005;
l1 = 0.2;
M2 = 0.15;
l2 = 0.5; J2 = M2*l2^2/3;
Kphi = 0.008; N = 15;
R = 2.5; g = 9.8;// Derived dataa = J1 + M2*l1^2;
d = 1/2*M2*g*l2;
delta = a*c-b^2;

b = 1/2*M2*l1*l2;
e = N*Kphi/R;// Initial conditions
theta1 = 90*%pi/180;
theta2 = 3*%pi/180;
theta1_p = 0;
theta2_p = 0;

Figure 6: the LQ regulator in an Xcos schemec = J2;
f = N^2*Kphi^2/R;// init. position// init. position// init. ang. vel.
// init. ang. vel.

maxang = 0*%pi/180;
maxvel = 0;
initnoise = 100;
K = [10.

120.55385

7.5116657

21.523317];

K1 = K(1);K2 = K(2);K3 = K(3);K4 = K(4);Figure 7: the entire Xcos scheme. With respect to step 10, the LQ
regulator has been added in the blue subsystem.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 19/32

Step 20: Results
As in step 12, we can now plot the two angles with the command:plot(sol.time, sol.values*180/%pi)

The initial configuration is in this case

Note that, as already explained at the beginning of step 13, this regulator
works only for small perturbation of the angle
that represents the
position of the vertical rod.
Figure 8: Angles positions at time steps

As an exercise, try to change the initial configuration in the context
configuration parameters and see how the plot changes.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 20/32

Step 21: Control for a self-erecting inverted pendulum
Now, we want to develop a new controller that takes the pendulum fromits stable position to the inverted, unstable position and then maintains
this configuration.

The idea is to control the moving rod, through the use of a PID regulator,
such that the moving rod is in an opposite direction with respect of thependulum. Then, when the pendulum reaches a prefixed threshold wemove from the PID regulator to the LQ regulator.

The full scheme is reported on the right. This scheme is composed by thefollowing main components:
The nonlinear system block used to simulate the non-linear
system;The LQ regulator block used to control the pendulum in thevertical position;
A PID controller used to take the pendulum from its stableconfiguration to the unstable one;
A controller switcher that chooses between the LQ regulator
and PID controller.

Figure 9: Self-erecting controller for the pendulum (see file
inv_pend_se.zcos)

The two new blocks, the PID controller and the controller switcher, will be
described in the following steps.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 21/32

Step 22: Controller switcher
The controller switcher is based on the Scilab function inv_pend_mode.
The idea is to move from a configuration to another checking the angle
and its velocity.

function [mctrl]=inv_pend_mode(theta2, dtheta2);// Select the mode of control to be applied// 1 for trying to get vertical position// 0 for maintain vertical position// unwrapping of theta2
theta2u = unwrap(theta2);
mctrl = 0;
if (abs(theta2u) <= PositionThreshold) & (abs(dtheta2) <=VelocityThreshold) thenmctrl = 1;
end
if (abs(2*%pi - abs(theta2u)) <= PositionThreshold) &(abs(dtheta2) <= VelocityThreshold) thenmctrl = 1;
end
endfunction

Figure 10: Controller switcher

In the first part we movesuch thatand then we check theangle condition. Remember that the conditions that we want to control areand.

A Scilab Tutorial On An Inverted Pendulum

function b=unwrap(a);aa = abs(a);k = floor(aa / (2*%pi));
if a > 0 thenb = a - 2 * k * %pi;
else
b = aa - 2 * k * %pi;
b = 2 * %pi - b;
end
endfunction

www.openeering.com

page 22/32

Step 23: PID controller
The PID controller is used to moving rod is in an opposite way to directionof rising of the pendulum.

Several configurations of PID controllers exist in literature. Here, we use
the following:

Figure 12: PID scheme

Figure 11: Scheme of our PID controller
In general, this configuration is characterized by the derivative term
applied to the output. This controller is particularly useful when we preferlooking for stability than tracking the reference signal.
Figure 13: Basic PI_D scheme

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 23/32

Step 24: Numerical results
Running the Xcos scheme at step 21 we obtain a figure in which we cansee the behavior of the controller. It is visible that the controller switches
after six seconds.

We can even plot the trend of the two angles
previous steps.

andas we did in the

Using the command:plot(sol.time, sol.values*180/%pi)

Figure 14:Switch of the controller

we can plot the positions of the angles
and . Even in this plot we may
see that, after 6 seconds, the rod is taken into its unstable vertical position
and then controlled perfectly.

Figure 15: Angles positions at time steps

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 24/32

function [y1_deg, y2_deg]=inv_pend_anim(theta1, theta2)

Step 25: Animations in Scilab
Plotting the animation of the moving pendulum, from its stable state to its
vertical position, would be useful in order to understand the entire
dynamic of our system. Scilab has the capability to plot animations and inthese last steps of the tutorial we will show how to use this capability.

First of all, we need to develop a new Scilab function that, starting for thetwo angles
and(in radians) as input arguments, plots the pendulum
for this configuration. Then, the idea is to store, in the user_data field of
the figure, the handles of the two graphical objects and then update the
new coordinates of the rod points. The Scilab code on the right reports
only part of the source code of the inv_pend_anim.sci function.

y1_deg = theta1*180/%pi;y2_deg = theta2*180/%pi;// Model data should be inserted from a mask
l1 = 0.2;
l2 = 0.5;
L = 0.4
f = findobj("Tag", "ANIM_ROD");
if f == [] then//Initialization//download source code from Openeering.com
else
scf(f);
end// Modify coordinatesf = findobj("Tag", "ANIM_ROD");
drawlater();
e1 = f.user_data.e1;
xv1 = [0; l1*cos(theta1)];
yv1 = [0; l1*sin(theta1)];zv1 = [0; 0];// xsegs(xv1,yv1,zv1);e1.data = [xv1, yv1, zv1];e2 = f.user_data.e2;
xv2 = [l1*cos(theta1); l1*cos(theta1) l2*sin(theta2)*cos(%pi/2 - theta1)];
yv2 = [l1*sin(theta1); l1*sin(theta1) +l2*sin(theta2)*sin(%pi/2 - theta1)];
zv2 = [0; l2*cos(theta2)];// xsegs(xv2,yv2,zv2);e2.data = [xv2, yv2, zv2];
drawnow();

Figure 16: A single frame of the animation. This plot is obtained withthe command inv_pend_anim(1.8, 0)

A Scilab Tutorial On An Inverted Pendulum

endfunction

www.openeering.com

page 25/32

Step 26: Using the animation function in Xcos
To use the animation function as a block in Xcos, it is sufficient to open
one of the previous Xcos scheme and add a “SCIFUNC_BLOCK_M”.
To connect the block with the Scilab function inv_pend_anim.sci it issufficient to specify the number and type of input and output ports and thefunction name as reported in the following figures.

Figure 19: The Xcos scheme with the animation block(inv_pend_se_anim.zcos)

Figure 17: Specifying input and output ports

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 26/32

Figure 18: Specifying the Scilab command

Step 27: Running the animation
Before running the Xcos scheme, remember to load the function adding
the following command exec("inv_pend_anim.sci",-1) in the set context
menu.

Figure 20: set context window
The animation results are reported on the right.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 27/32

Figure 21: Simulation results: Some images
The entire animation is available for download

Step 28: Exercise 1
Try to implement an unwrapping function that maps, using only Xcos
blocks, an input signal into the intervaland having
as meanvalue (it maps 0 into ).

On the right we propose an idea of the scheme and its result.

Figure 22: Xcos System (ex1.zcos)

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 28/32

Hints: Use the quantization block.

Figure 23: Plots and Results

Step 29: Exercise 2
Starting from noised angle measures try to develop a recovery procedure
for the recovery of the derivative, i.e. if we kwon the angle at each time
step we want to know the velocity.

The idea is to use a high-pass filter with a unity gain. Try to complete thefollowing scheme adding the appropriate block in the empty block.
Solution is given in ex2.zcos.

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 29/32

Figure 24: Example of recovery strategy for the derivative of a signal

Figure 25: Noise input and original signal

Figure 26: Example of recovery

Step 30: Concluding remarks and References

A Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 30/32

In this tutorial we have presented a modeling approach for the control of
an inverted pendulum in Scilab/Xcos. The regulator is developing using
the Control System Toolbox available in Scilab known as CACSD while
the simulation is done using Xcos.

1. Scilab Web Page: Available: www.scilab.org
2. Openeering: www.openeering.com
3. Maxima: http://maxima.sourceforge.net/

All the symbolic manipulations of the expressions and equations havebeen obtained using Maxima; the software is free and available at [3].

It is trivial that the system is only a study version which can be improvedin several ways, for example improving the PID parameters ordevelopment a new strategy algorithm.

Figure 27: Maxima graphical user interface

Step 31: Software content

A Scilab Tutorial On An Inverted Pendulum-------------Main directory

www.openeering.com

page 31/32

To report bugs or suggest improvements please contact the Openeering
team.
www.openeering.com

Thank you for your attention,-------------Animation.png
ex1.zcosex2.zcos
inv_pend.zcos
inv_pend_anim.sci
inv_pend_anim.zcos
inv_pend_ctrl.zcos
inv_pend_ctrl_anim.zcos
inv_pend_ganim.sce
inv_pend_mode.sci
inv_pend_nl_scilab.sce
inv_pend_se.zcos
inv_pend_se_anim.zcos
inv_pend_se_conf.sce
inv_pend_se_data
invpend_check.sce
license.txt
system_maxima.txt: Animation of the inv. pend.
: Solution of the ex. 1: Solution of the ex. 2: Inv. pend. in Xcos
: Inv. pend. animation: Inv. pend. with animation in Xcos
: Inv. pend. with regulator: Inv. pend. with anim. and regulator: Post-processing animation: Inv. pend. mode function: Inv. pend. in Scilab: Inv. pend. self-erecting: Inv. pend. self-erecting with anim.
: Inv. pend. self-erecting conf.
: Inv. pend. self-erecting solut.
: Inv. pend. development: The license file
: Maxima scripts

Manolo Venturin, Silvia PolesA Scilab Tutorial On An Inverted Pendulum

www.openeering.com

page 32/32