Sei sulla pagina 1di 34

Controlling an inverted pendulum using full state feedback controller

Tsegazeab Shishaye
[ID:2012420012]
Northwestern Polytechnical University, Xian,China

Abstract
In this paper an inverted pendulum is presented using state space modeling method. And full state feedback controller is
developed using pole placement and LQR (Linear Quadratic Regulation) methods. After that, tracking problem is
addressed by designing a steady state error controller. Then, considering the reality conditions, first assuming by some of
the state variables are measurable, a reduced state observer is designed and then for a worst scenario a full order state
observer is designed. Finally, the state feedback controller and the state observer are summed up to give a pre-
compensator and an overall steady state error controller is added to that new system. All mathematical modeling are
presented clearly and simulations together with their analysis were done using MATLAB software. For clear view on
what is going on with the control method and the system, an animation GUI is also presented.
Introduction
As a typical control system, the control of an inverted pendulum is excellent in testing and evaluating different control
methods. Its popularity derives in part from the fact that it is unstable without control, that is, the pendulum will simply
fall over if the cart isn't moved to balance it. Additionally, the dynamics of the system are nonlinear. The objective of the
control system is to balance the inverted pendulum by applying a force to the cart that the pendulum is attached to. A real-
world example that relates directly to this inverted pendulum system is the attitude control of a booster rocket at takeoff
but The fundamental principles within this control system can be found in many industrial applications, such as stability
control of walking robots, vibration control of launching platform for shuttles etc

Problem formulation
The cart which a slim stick is fasted on can move along
a smooth track under the force, a controller needs to be
designed such that the one stage inverted pendulum
can be steadily balanced at its vertical position
after some disturbance.
Given parameters:
M - Mass of the cart 0.5 kg
m - Mass of the pendulum 0.5 kg
b - Friction of the cart 0.1 N/m/sec
l - Length to pendulum center of mass 0.3 m
I - inertia of the pendulum 0.006 kg*m^2
F - Force applied to the cart
X - Cart position coordinate
- Pendulum angle from vertical, and

#Task-1
- Linearizing the non-linear equation of motion of the system around =0 and
- Finding the associated state space model of the system
Taking the system equations of motion of the system from above,

System modeling
Since the analysis (state space model) and control design techniques that I will employ in this problem apply only to linear
systems, these equations need to be linearized. Specifically, I will linearize the equations about the vertically upward
equilibrium position, = 0, and will assume that the system stays within a small neighborhood of this equilibrium.
Linearization
Here, instead of using the linearization method (Taylor method for small perturbations), I will use simple approximation
around = 0. This assumption is reasonably valid since under control it is desired that the pendulum not deviate more
than 20 degrees (0.35 radians) from the vertically upward position.
So, for small ,
sin 0 = 0, And
cos 0 = 1, (According to the above diagram 0 will lie in the first quadrant. so, the Cosine function is positive)
Also dropping all the non-linear components (0

2
= 0) the above equations will become:
(H+m)x +bx +ml0

= F .. (3)
(I +ml
2
)0

mgl = mlx .. (4)


Solving for x and 0

independently from equation (3) and equation (4) respectively gives,


x =
-mI
M+m
0

b
M+m
x +
1
M+m
F . (5)
0

=
-mI
I+mI
2
x +
mgI
I+mI
2
0 . (6)
Substituting equation (5) in (4) and equation (6) in (3) it yields,
0

=
mgI(M+m)
I(M+m)+MmI
2
0 +
mIb
I(M+m)MmI
2
x
mI
I(M+m)+MmI
2
F
x =
-gm
2
I
2
I(M+m)+MmI
2
0
b(I+mI
2
)
I(M+m)+MmI
2
x +
I+mI
2
I(M+m)+MmI
2
F
State-space model
Now, let u = F, x
1
= 0, x
2
= 0

= x
1
, x
3
= x, x
4
= x = x
3
, y
1
= x, y
2
= 0 , the four state equations will be,
x
1
= x
2

x
2
=
mgl(H+m)
I(H+m) +Hml
2
x
1
+
mlb
I(H+m)Hml
2
x
4

ml
I(H+m) +Hml
2
u
x
3
= x
4

x
4
=
gm
2
l
2
I(H+m) +Hml
2
x
1

b(I +ml
2
)
I(H+m) +Hml
2
x
4
+
I +ml
2
I(H+m) +Hml
2
u
State space model of an LTI system is
x = Ax +Bu
y = Cx +Du
So, substituting the above equations in to the matrices properly will give the following state space representation.
x = _
x
1
x
2
x
3
x
4
_ =

u 1 u u
mgI(M+m)
I(M+m)+MmI
2
u u
mIb
I(M+m)MmI
2
u u u 1
-gm
2
I
2
I(M+m)+MmI
2
u u
b(I+mI
2
)
I(M+m)+MmI
2

_
x
1
x
2
x
3
x
4
_ +

mI
I(M+m)+MmI
2
u
I+mI
2
I(M+m)+MmI
2

u . (7)
y = j
y
1
y
2
[ = j
u u 1 u
1 u u u
[ _
x
1
x
2
x
3
x
4
_ +j
u
u
[ u . (8)
In MATLAB,
systcm = xx(A, B, C, ) % to find the state space model
0 = t(systcm) % to find the transfer function of the system (for both outputs)
N.B.
Examining the results, especially the numerators, in the transfer functions of each output solved from the state space
model, there exists some terms with very small coefficients. These terms should actually be zero, they only show up due
to numerical round-off errors that accumulate in the conversion algorithms that MATLAB employs. This can be checked
by solving the transfer functions of the cart and the pendulum independently from the motion equations using Laplace
transform by assuming zero initial conditions.

#Tsak-2
- Simulating the dynamic behavior of the system under impulse force and step force
- Analyzing the stability, controllability and observability condition of the system
The design requirements for the Inverted Pendulum project are:
Settling time for x and 0 of less than 5 seconds.
Rise time for x of less than 0.5 seconds.
Overshoot of 0 less than 20 degrees (0.35 radians).
System analysis
1. Open-loop impulse response of the system
Examining on how the system responds to a 1-Nsec impulsive force applied to the cart, I found the following result.

Fig.1. open-loop impulse response of an inverted pendulum system
From the plot, the response is unsatisfactory. Both outputs never settle, the angle of the pendulum goes to several
hundred radians in a clockwise direction though it should be less than 0.35 rad. And the cart goes to the right infinitely.
So, this system is unstable in an open loop condition when there is a small impulsive force applied to the cart.


0
20
40
60
80
From: u
T
o
:

x
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
-500
-400
-300
-200
-100
0
T
o
:

t
h
e
t
a
Open-Loop Impulse Response
Time (sec)
A
m
p
lit
u
d
e
2. Open-loop step response of the system
Here also, it can be seen from the outputs that the system is unstable under 1-Newton step input applied to the cart. The
outputs are found by using the lism command of MATLAB which can be employed to simulate the response of LTI
models to arbitrary inputs.
The plot, fig.2, shows that the responses of the system to a step force are unstable.

Fig.2. open-loop step response of an inverted pendulum

3. Stability of the system
To check stability means to analyze whether the open-loop system (without any control) is stable. That has partly done by
the above simulations under the impulse and step forces. But as per the definition, the eigenvalues of the system state
matrix, A, can determine the stability. That is equivalent to finding the poles of the transfer function of the system. The
eigenvalues of the A matrix are the values of s where det(xI A) = . A system is stable if all its poles have lied in the
left-half of the s-plane.
poles = eig(A)
Poles =
0
7.1430
-7.2220
-0.1000
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
-50
-40
-30
-20
-10
0
10
20
30
40
50
Open-Loop Step Response


x
theta
Or it can be shown by pole-zero mapping of the system as below using MATLAB command
pzmop(sytcm)

Fig.3. Pole-zero mapping of the system
As can be seen from the output, there is one pole on the right-half plane at 7.1430. This confirms the intuition that the
system is unstable in open loop.

4. Controllability of the system
A system is controllable if there exists a control input u(t) that transfers any state of the system to zero in finite time. It
can be shown that an LTI system is controllable if and only if its controllability matrix, CO, has full rank. i.e. if
rank(CO) = n, where n is the number of states.
So, the necessary and sufficient condition for controllability of the system is:
ronk(C0) = ronk|B AB A
2
B A
n-1
B] = n
Using the following MATLAB command, the controllability matrix of the system is:
RankCO = rank (ctrb(A, B))
RankCO= 4
So, since the controllability matrix has full rank, the system is controllable!

5. Observability of the system
-8 -6 -4 -2 0 2 4 6 8
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Pole-zero mapping of the system
Real Axis
I
m
a
g
i
n
a
r
y

A
x
i
s
In cases where all the state variables of a system may not be directly measurable, it is necessary to estimate the values of
the unknown internal state variables using only the available system outputs.
Conceptually, a system is observable if the initial state, x(t_0), can be determined from the system output, y(t), over some
finite time t
0
< t < t
f
.
Since this system is linearized to be LTI system, the system is observable if and only if the Observability matrix, OB, has
full rank (i.e. if rank(OB) = n, where n is the number of states).
So, necessary and sufficient condition for Observability is:
ronk(0B) = ronk

C
CA
CA
2

CA
n-1

= n
So, in MATLAB using the command
Ronk0B = ronk(obs:(A, C))
RankOB=
4
So, since the observability matrix has full rank, the system is observable!

#Task-3
- Designing a state feedback controller to stabilize the system by improving performance of the system using pole
placement and linear quadratic regulator(LQR) methods
- If all the states are not measurable, designing a faster stable full-order state observer for state feedback controller.
- If only 0 , x are measurable, designing a reduced-order state observer for state feedback controller.
- To make design more challenging, applying a step input to the cart and yet achieving the following design
requirements,
o Settling time for x and 0 of less than 5 seconds.
o Rise time for x of less than 0.5 seconds.
o Overshoot of 0 less than 20 degrees (0.35 radians).

Designing full-state feedback controller
Here the main purpose is to design a controller so that when a step reference is given to the system, the pendulum should
be displaced, but eventually return to zero (i.e. vertical) and the cart should move to its new commanded position.
Design procedure:
Checking if the pair (A, B) is controllable.
Constructing equations that will govern the controller dynamics
Placing the eigenvalues of the controller matrix in a desired position by finding an arbitrary vector state feedback
control gain vector K assuming that all of the state variables are measurable. This can be accomplished using
either of the two methods pole placement method and LQR (Linear Quadratic Regulation) method.
So, it has been checked before that the system is controllable. i.e. the pair (A, B) is controllable.
Since, the state of the system is to be to be feedback as an input, the controller dynamics will be:
u = r Kx
x = Ax +B(r Kx) = (A BK)x +Br
y = Cx
1- Using pole placement method
This method depends on the performance criteria, such as rise time, settling time, and overshoot used in the design.
The design requirements are,
Settling time, T
xett||ng
, for both outputs should be less than 5 seconds. And
%Overshoot, %OS, of the angle of the pendulum should be less than 20 (0.35 radians).
Design procedures for pole placement:
1. Using time domain specifications to locate dominant poles roots of x
2
+2m
n
x +m
n
2
= . This is done by
using the following formulas and finding the dominant poles at o _jm
d

=
-In (%0S100)
n
2
+In
2
(%0S100)

I
scttIng
=
4
m
n
, valid up to ~ 0.7, and

d
=
n
1
2

o =
n

= cos
-1

2. Then placing rest of poles so they are much faster than the dominant second order behavior.
Typically, keeping the same damped frequency
d
and then moving the real part to make them faster
than the real part of the dominant poles so that the transient response of the real poles of the system will
decay exponentially to insignificance at the settling time generated by the second order pair.
While taking care of moving the poles too far to the left because it takes a lot of control effect (needs
large actuating signal)
#procedure 1
Given %0S = 2u (0.35 rad) and I
scttIng
= Sscc , calculating the parameters as follow:
=0.456,

n
=1.78rad/sec,
= cos
-1
= 62.87
0
,

=
n
= -0.811,
]
d
= 1.584
So, the dominant poles are:
=> -
n
_ ]
n
1
2
= -0.811+j1.584 and -0.811-j1.584 (which are complex conjugates)

Fig.4. Dominant poles and guide for desired poles allocation






#procedure 2
Using MATLAB software, the following are the gain
vectors for different sets of desired poles.
Test -1
K1 = [-12.4835 -1.2055 -0.2423 -0.4731]
Desired poles_1 = [-2.433 -1.622 -0.811_1.584j],
by making the remaining poles 2 and 3 times faster than the
real part of the dominant poles.


Test 2
K2 = [-21.0855 -3.2251 -2.0191 -1.8811]
Desired poles_2 = [-8.11 -4.055 -0.811_1.584j],
by making the remaining poles 5 and 10 times faster than
the real part of the dominant poles.
Test - 3
K3 = [-40.2010 -5.9361 -6.7842 -4.8694]
Desired poles_3 = [-11.354 -9.732 -0.811_1.584j],
by making the remaining poles 10 and 12 times faster than
the real part of the dominant poles.

Note:
As can be seen from the respective plots of the system step
response for each calculated gain vectors as per the desired
pole locations, System design requirements are satisfied in
all the three tests. And, the system response tends to be
faster when the real poles go farther to the left from the real
part of the dominant poles. A more faster response can be
found by moving the real poles deeper in to the left half
side of the s-plane, but it requires a larger actuating signal
which in turn brings larger control effort.

0 1 2 3 4 5 6 7 8 9 10
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
c
a
r
t

p
o
s
i
t
i
o
n

(
m
)
Step Response using pole placement-1st test
0 1 2 3 4 5 6 7 8 9 10
-0.06
-0.04
-0.02
0
0.02
0.04
0.06
p
e
n
d
u
l
u
m

a
n
g
l
e

(
r
a
d
i
a
n
s
)
0 1 2 3 4 5 6 7 8 9 10
-0.15
-0.1
-0.05
0
0.05
c
a
r
t

p
o
s
i
t
i
o
n

(
m
)
Step Response using pole placement-2nd test
0 1 2 3 4 5 6 7 8 9 10
-0.02
-0.01
0
0.01
0.02
p
e
n
d
u
l
u
m

a
n
g
l
e

(
r
a
d
i
a
n
s
)
0 1 2 3 4 5 6 7 8 9 10
-0.04
-0.03
-0.02
-0.01
0
0.01
c
a
r
t

p
o
s
i
t
i
o
n

(
m
)
Step Response using pole placement-3rd test
0 1 2 3 4 5 6 7 8 9 10
-6
-4
-2
0
2
4
x 10
-3
p
e
n
d
u
l
u
m

a
n
g
l
e

(
r
a
d
i
a
n
s
)
2- Using Linear Quadratic Regulator (LQR)
This approach is to place the pole locations so that the closed-loop system optimizes the cost function given by
[
R
= _|x(t)
1
x(t) +u(t)
1
Ru(t)]Jt

0

Where:
x
1
x - is the state cost with weight Q
u
1
Ru - is the control cost with weight R
Therefore, LQR selects closed-loop poles that balance between state errors and control effort.
Design procedures for LQR:
1. Selecting design parameter matrices Q and R
Easily, starting with = C
i
C onJ R = 1 and increasing the weight on the matrix Q
This is done supposing that the cost [ = (y
2
+u
2
)Jt is to be minimized. If so,
y = Cx, y
2
= x
i
C
i
Cx = x
i
Qx wilc Q = CC
2. Solving the algebraic Riccati equation for P, (done using MATLAB software)
A
T
P+PA +Q PBR
-1
B
T
P =
3. Finding the state variable feedback using
K = R
-1
B
T
P
4. Simulating results using lsim MATLAB command and observing
5. Verifying design, if it seen to be unsatisfactory, trying again with different weighting matrices Q and R
All the above procedures are completed easily in MATLB as follow:
>> Q = C'*C;
>> Q(1,1) = 10;
>> Q(3,3) = 100
>> R = 1
>> K = lqr(A,B,Q,R)
>> Ac = A-B*K; %control matrix
>> system_c = ss(Ac,B,C,D);
And all the results can be seen below.

Q =_
8u u u u
u u u u
u u 4uu u
u u u u
_, R = 1
K = [-38.1423 -6.2197 -10.0000 -7.7060]


0 1 2 3 4 5 6 7 8 9 10
-0.02
0
0.02
c
a
r
t

p
o
s
i
t
i
o
n

(
m
)
Step Response with LQR Control
0 1 2 3 4 5 6 7 8 9 10
-5
0
5
x 10
-3
p
e
n
d
u
l
u
m

a
n
g
l
e

(
r
a
d
i
a
n
s
)
Note:
- The reason this weighting was chosen is because it just satisfies the transient design requirements. Increasing the
magnitude of more would make the tracking error smaller, but would require greater control force. More
control effort generally corresponds to greater co
can be seen clearly by varying the weights
- The above LQR design method has brought a good stability to the system
a good manner. But, if the reference input is different fro
degraded. So, for best quality of performance, an

Designing an asymptotic error tracking controller
- So far, both controller design methods, the pole placement and LQR design, helped to pick the gain vector K so
that the dynamics of the system to have nice properties
- The question remains as to how well the designed controller in both methods allows to
command?
This deals with performance issue of the system rather than just stability.
x = Ax +Bu
y = Cx
u = r Kx
For good tracking performance, it should be
y(t) r(t) ax t
To make this, one solution is to scale the reference input
u = N

r Kx, where N

is a feedforward
fig.5. Adding a pre-compensation scale factor to the reference input command
weighting was chosen is because it just satisfies the transient design requirements. Increasing the
more would make the tracking error smaller, but would require greater control force. More
control effort generally corresponds to greater cost (more energy, larger actuator, etc.).
seen clearly by varying the weights tetha and x in the animation GUI that will be attached with this document.
The above LQR design method has brought a good stability to the system and fulfilled the design requirements in
a good manner. But, if the reference input is different from zero, r(t) = a , the systems performance will be
degraded. So, for best quality of performance, an asymptotic tracking of a step reference input
error tracking controller for good regulation
both controller design methods, the pole placement and LQR design, helped to pick the gain vector K so
that the dynamics of the system to have nice properties more importantly to stabilize A.
The question remains as to how well the designed controller in both methods allows to
This deals with performance issue of the system rather than just stability.
it should be
To make this, one solution is to scale the reference input r(t) so that,
feedforward gain used to scale the closed loop transfer function.

compensation scale factor to the reference input command
weighting was chosen is because it just satisfies the transient design requirements. Increasing the
more would make the tracking error smaller, but would require greater control force. More
st (more energy, larger actuator, etc.). More improved responses
that will be attached with this document.
and fulfilled the design requirements in
, the systems performance will be
asymptotic tracking of a step reference input must be designed.
both controller design methods, the pole placement and LQR design, helped to pick the gain vector K so
importantly to stabilize A.
The question remains as to how well the designed controller in both methods allows to track a reference
used to scale the closed loop transfer function.
Then, the above equations becomes,
x = (A BK)x +BN

r
y = Cx
Then, the new transfer function will be
Y(x)
R(x)
= C(xI (A BK))
-1
BN

= 6
c|
(x)N


So, clearly the scaling factor N

can be computed as follow.


N

= 6
c|
()
-1
= (C(A BK))
-1
B)
-1

In this specific problem, before calculating N

, the C = j
1
1
[ should be modified to a new one C
n
=
| 1 ] because it is redefined that y = x, which means the reference input is only applied to the position of the
cart.
Therefore, having K from the previous LQR design and scaling the reference input with following result, the system
responses are plotted below.
N

= (C
n
(A BK)
-1
B)
-1

In MATLAB,
>> Cn = [0 0 1 0]; %modification of C matrix
>> Nbar=-inv(Cn*((A-B*K)\B));
>> system_cl = ss(Ac,B*Nbar,C,D);


As can be seen from the above plot, all design
requirements are satisfied. i.e., the overshoot is below the
limits, the settling time is also <5 sec and the rise time is
<0.5 sec. And also, it can be clearly seen that the system
performance becomes better and smooth than the one
found using the previous controller designed by LQR
only.



0 1 2 3 4 5 6 7 8 9 10
-0.1
0
0.1
0.2
0.3
0.4
c
a
r
t

p
o
s
i
t
i
o
n

(
m
)
Step Response with Pre-compensation and LQR Control
0 1 2 3 4 5 6 7 8 9 10
-0.1
-0.05
0
0.05
0.1
0.15
p
e
n
d
u
l
u
m

a
n
g
l
e

(
r
a
d
i
a
n
s
)
Designing a reduced order state observer

If 0 and x are measurable, then a reduced order state estimator can be designed to estimate 0

and x .
To do this taking the original state space representation
x = Ax +Bu
y = Cx
Generally if p of he n states are measurable,
x = j
x
m
x
u
[, where x
m
R
p
onJ x
u
R
n-p
are the measured and unmeasured states respectively.
And the system dynamics can be described as:
x
m
= A
mm
x
m
+A
mu
x
u
+B
m
u
x
u
= A
um
x
m
+A
uu
x
u
+B
u
u
y = C
m
x
m

For z(t) to be an estimate of Tx(t), that is, for z = Fz +gy +hu to be an estimate of Tx , the following conditions
must be satisfied.
- TA FT = gc
- h = TB
- All eigenvalues of F have to have negative real parts and are different from the eigenvalues of A.
So, to estimate the states 0

= x
1
and x = x
3
, the reduced dimension observer can be designed as the following:

Design Procedures:
1. Choosing an arbitrary 2x2 matrix F so that all eigenvalues have negative real parts and are different from those of
A.

F =

1.0e+003 *

-0.0632 0.0011
-1.0497 0.0016
And checking its eig(F)= -30.8206 +10.2537i and -30.8206 -10.2537i, both eigenvalues of F have negative real
values and all are different from those of eig(A)= 0,7.1430, -7.2220, -0.1000.
2. Choosing a 2x2 vector g so that (F, g) is controllable,

g =
1.uc + uu4

6.471S u.u6uu
u.279u u.uuS4
And checking ronk(ctrb(F, g)) = 2 so, it is satisfied.
3. Solving 2x4 matrix I using Lyapunov equation IA FI = gC in MATLAB software

I = lyop(F, A, g C)

T =

1.0e+004 *

-0.0035 0.0002 0.0094 -0.0068
-0.1986 0.0084 6.4223 -0.3785

4. Checking if the square matrix P of order 4 is singular or non-singular

P = j
C
I
[ =
p =

1.0e+004 *

0 0 0.0001 0
0.0001 0 0 0
-0.0035 0.0002 0.0094 -0.0068
-0.1986 0.0084 6.4223 -0.3785

Finding its inverse in:(P) =

P
-1
=
1.0e+003 *

-0.0000 0.0010 0 0
2.0405 -0.0009 0.0019 -0.0000
0.0010 0 0 0
0.0624 -0.0005 0.0000 -0.0000

So this means it is non-singular because its inverse is found.
5. If P is non-singular, computing = IB

= IB=

1.0e+003 *

-0.1315
-7.2163

Then, the reduced observer can be put as follow.

z = Fz +gy +u
y = Cx
All the coefficient matrices are calculated above.

Finally, the estimate is
x = P
-1
j
y
z
[

And the error is

c = z Ix = Fz +gy +u I(Ax +bu)
e = Fe

x = 1. oc +uuS _
u.uuuu u.uu1u u u
2.u4uS u.uuu9 u.uu19 u.uuuu
u.uu1u u u u
u.u624 u.uuuS u.uuuu u.uuuu
_ j
y
z
[

c = 1.uc +uuS j
u.u6S2 u.uu11
1.u497 u.uu16
[ c



Designing full order state observer (closed loop state estimator)
So far, it was assumed that there is full or partial access to the state x(t) when the controllers in each method are
designed. But in reality, most often, all of this information is not available.
To address this issue, a replica of the dynamic system that provides an estimate of the system states based on the
measured output of the system should be developed the so called a state observer or state estimator.
Here, a full order state observer will be developed assuming as if all the states cant be measured taking in to
consideration that there might be lack of sensors.
Design procedures:
1- Checking whether the pair (A, C) is observable
2- Developing estimate of x(t) that will be called x(t)
3- Selecting a suitable real constant vector L so that all eigenvalues of (A LC)have negative real parts
4- Making sure that the estimator eigenvalues are faster than the desired eigenvalues of the state feedback,
because it will be used together to form a compensator.
So, it has been checked initially that this system is observable. i.e the pair (A, C) is observable.
x

= Ax +Bu +Ly
= Ax +Bu +L(y y)
= (A LC)x +Bu +Ly
y = Cx
u(t) = N

r Kx
Then the closed loop estimator error dynamics is
x

= x x


= |Ax +Bu] |Ax +Bu +L(y y)]
= (A LC)(x x )
x

= (A LC)x
e = (A LC)e Where e = x = x x
This equation governs the estimator error. If all eigenvalues of (A LC) can be can be assigned in the negative half plane,
then all entries of the error e will approach to zero at faster rates. Thus, there is no need to compute the initial state of the
original state equation.
To select L a common guideline is to make the estimator poles 4-10 times faster than the slowest controller pole. Making
the estimator poles too fast can be problematic if the measurement is corrupted by noise or there are errors in the sensor
measurement in general.
Controller poles from the above system with error tracking controller are:
>>contr_poles=eig(Ac)
>>contr_poles =
-7.6280 + 3.4727i
-7.6280 - 3.4727i
-3.1744 + 2.1467i
-3.1744 - 2.1467i
The slowest poles have real parts at -3.1744, so the estimator poles can be placed at -30. Since the closed-loop estimator
dynamics are determined by a matrix (A LC) that has a similar form to the matrix that determines the dynamics of the
state-feedback system (A BK).
Therefore, the same commands, that were used to find the state feedback gain K, can be used to find the estimator gain L.
Since e|g(A LC) = e|g(A
i
C
i
L
i
) and A
i
C
i
L
i
have an exact form as A BK then the MATLAB command
place can be used to compute L.
%Placing obsserver poles

>> obsr_poles = [-30 -31 -32 -33];
>> L = place(A',C',obsr_poles)'
>> L =

1.0e+003 *

-0.0006 0.0632
-0.0018 1.0497
0.0626 -0.0008
0.9732 -0.0341


Final goal is to build the compensator (state feedback controller + full state observer).
Dynamic output feedback compensator is the combination of the regulator (state feedback controller developed using the
LQR method) and full state estimator using
u = Kx
x

= (A LC)x +Bu +Ly


x

= (A BKLC)x +Ly
Rewriting with new state x
c
x
x
c
= A
c
x
c
+B
c
y
u = Kx
c

Where
A
c
= A BKLC and B
c
= L
But since there is a reference input, the compensator can
be implemented using the following feedback.
e(t) = r(t) y(t)
Then the state space model of the compensator will be
x
c
= A
c
x
c
+B
c
c (this can be seen in the block diagram)
So, equations that can describe the overall closed loop dynamics will be
Having u = r Kx
c
and e = r y while y = Cx
x = Ax +Bu = Ax BKx
c
+hr
x
c
= A
c
x
c
+B
c
e = A
c
x
c
+B
c
(r y) = A
c
x
c
+B
c
(r Cx)
= B
c
Cx +A
c
x
c
+B
c
r
In short, the overall closed loop final state space model is:
_
x
x
c
_ = _
A BK
B
c
C A
c
_ j
x
x
c
[ +_
B
B
c
_ r
y = |C ] j
x
x
c
[
Where
A
c
= A BKLC and B
c
= L
By making an equivalent transformation to the above state space model, it can be represented as the following equivalent
state equation. And this equivalent state equation governs the whole controller-estimator configuration.

j
x
e
[ = j
A BK BK
A LC
[ j
x
e
[ +j
B

[ r Where e = x = x x
y = |C ] j
x
e
[
The response of the system with controller + observer is:

Note:
The overall design requirements are satisfied and the system has a relatively good performance. But it can be seen that the
response graph for the inverted pendulum lucks a slight smoothness. That means there is something which creates that
vibration. i.e. there is a tracking problem of the output to the reference input. The next task will solve this problem.






0 1 2 3 4 5 6 7 8 9 10
-0.02
0
0.02
c
a
r
t

p
o
s
i
t
i
o
n

(
m
)
Step Response with controller + observer
0 1 2 3 4 5 6 7 8 9 10
-5
0
5
x 10
-3
p
e
n
d
u
l
u
m

a
n
g
l
e

(
r
a
d
i
a
n
s
)
#Final-Task
- Redefining y = x (step ummand applted tu pustttun uI the art unly)
- Designing no steady state error tracking controller for the new SISO system to eliminate the steady state
error
Having the final controller-observer state space model, if the reference input is a constant different from zero, (t) = a
, and if it is applied only on the carts position, it can be taken that y = x so that the system will become a SISO system.
So, the matrix C = j
1
1
[ should be modified to a new one C
n
= | 1 ] when calculating a steady state
error tracking controller that can be implemented by adding a feedforward gain N

to scale the reference input.


This has the same approach as I used in the LQR controller, but slightly different in calculating the scaling factor N

since
it uses the overall controller-estimator configuration closed loop matrices.
So, taking the equivalent state equation of the new system (controller + observer),
j
x
e
[ = j
A BK BK
A LC
[ j
x
e
[ +j
B

[ r Where e = x = x x
y = |C ] j
x
e
[
For good tracking performance, it should be
y(t) r(t) ax t That means DC gain of the response from r to y should be unity.
To make this, one solution is to scale the reference input r(t) so that,
u = N

r Kx, where N

is a feedforward gain used to scale the closed loop transfer function.


Then using the closed matrix,
N

= (C
c|
(A
c|
))
-1
B
c|
)
-1

Where A
c|
= j
A BK BK
A LC
[, B
c|
= j
B

[ and C
c|
= |C
n
] in which C
n
= | 1 ] because the
step reference command is to be applied only to the carts position (y = x).
Then the final inverted pendulum system controlled by designing a controller, a full state observer and
adding a no steady state error tracker can be described by the following state space model.
j
x
e
[ = j
A BK BK
A LC
[ j
x
e
[ +_
BN

_ r
y = |C ] j
x
e
[
And the system response graph can be seen below.
As can be seen clearly from the graph the whole design
has solved clearly the problems of stability and
performance. And the no steady state error tracker has
eliminated the oscillation of the pendulum and made it
smooth.

And it can be seen from the animation GUI graph below
that, no matter the applied input force is varied, the
pendulum quickly balances itself with almost zero
vibration in its steady state. These graphs are draw by
varying the step inputs by sliding the bar from 0.2 to 0.5
randomly and at each time pressing the Run command
without clearing the previous output.
Fig.7. Animation GUI for a controlled Inverted pendulum
Explanation:
- Run button performs the simulation and plots the
response and the animation.
- Clear button clears the both plots. If the plots are
not cleared, then during the next run the step
response will be graphed on the same plot. This is
useful if you want to graphically see the effect of
varying a parameter.
- Exit button closes the GUI
- Weighting factor
x - This editable text field weights the cart's position in the LQR controller. Increasing the weighting
factor improves the cart's response, making it reach it's commanded position faster.
theta - This editable text field weights the pendulum's angle. Similar to the x weighting factor, making
this larger will quicken the pendulum's response. Feel free to change the weighting factors to see what
happens!
- Step Slider - The slider allows you to change the magnitude of the step disturbance on the cart.
- Manual Advance - If this control is checked, the user is able to advance the animation and plot one frame at a
time. The frames are advanced by pressing any key on the keyboard. This function is useful if the animation
moves too fast for the user and will allow the user to better visualize the entirety of the system's motion.
0 1 2 3 4 5 6 7 8 9 10
-0.1
0
0.1
0.2
0.3
0.4
c
a
r
t

p
o
s
i
t
i
o
n

(
m
)
Step Response with compensator and no steady state error traker
0 1 2 3 4 5 6 7 8 9 10
-0.1
-0.05
0
0.05
0.1
0.15
p
e
n
d
u
l
u
m

a
n
g
l
e

(
r
a
d
i
a
n
s
)
- Reference Input - This box is automatically checked when the GUI is run. By un-checking it the user removes
the reference input term, Nbar, from the simulation. The reference input is used to correct steady-state errors
common to full-state feedback systems.

Conclusion
Modeling of an inverted pendulum shows that the system is unstable without a controller. Results of applying state
feedback controllers show that the system can be stabilized. While both pole placement and LQR controller methods are
cumbersome because of selection of constants of controller though they can brought a good result if done systematically
with some guide lines.
When a DC reference input is applied to the cart, the system has failed slightly to track the input and has given a stable
output with some oscillations unsatisfactory steady state performances. To eliminate this, a no steady state error tracking
controller is designed and has brought good results as can be seen on the graphs in each steps.
And since in reality all the states cant be measured, a full-order state estimator (observer) is designed. Finally, the state
feedback controller is summed with a full-order state observer to give a pre-compensator and then a steady state error
tracking mechanism is also added to the whole new system. All those have brought a really nice controlled inverted
pendulum system with good performance.

References
[1] Chi-Tsong Chen, Linear system theory and design, 3
rd
edition , 1999 Oxford University press

[2] Chi-Tsong Chen, Analog and digital control system design transfer function, state space and algebraic methods

[3] B.Wayne Bequette, Process control Modeling, Design and simulation, Rensselaer Polytechnic Institute

[4] Friedland, Bernard, Control System Design, McGraw-Hill, Boston, 1986.

[5] P. Kumar, O.N. Mehrotra, J. Mahto, Controller design of inverted pendulum using pole placement and LQR, ISSN:
2319 - 1163

[6] A. Bazoune, Transient Response Specifications of a Second Order System

[7] Andrew K. Stimac, Standup and Stabilization of the Inverted Pendulum, MIT, June 1999

[8] Stormy Attaway, MATLAB, Practical Introduction to Programming and Problem Solving Second Edition,
department of Mechanical engineering Boston university, 2012

[9] http://ocw.mit.edu/courses/aeronautics-and-astronautics/16-30-feedback-control-systems-fall-2010/lecture-notes/

[10] http://ctms.engin.umich.edu/CTMS/index.php?example=InvertedPendulum&section=ControlStateSpace



Appendix A: Matlab Scripts and Function Files

File-1: InvertedPendulum.m
- This file has all the steps of developing the state feedback controller, full order state observer and the steady state
error controller. Its outputs are shown in graphs launched automatically when you run it.

%{
====================================================================
File:InvertedPendulum.m
Project: Controlling an inverted pendulum
Method: state space model and state feedback

By: TSEGAZEAB SHISHAYE (ID:2012420012), July-2013,NWPU, Xi'an-China
===================================================================
%}


%--------System Modeling-------%

% Defining variables

clc;
clear;
M=0.5;
m=0.5;
b=0.1;
l=.3;
I=.006;
g=9.8;
d=I*(M+m)+M*m*l^2;

% State-space model

disp('====================================')
disp('state space model of the system is:')
disp('====================================')

A=[0 1 0 0;m*g*l(M+m)/d 0 0 m*l*b/d;0 0 0 1;-g*m^2*l^2/d 0 0 -b*(I+m*l^2)/d];
B=[0;-m*l/d;0;(I+m*l^2)/d];
C=[0 0 1 0;1 0 0 0];
D=[0;0];

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

% Transfer function of the system

disp('=======================================')
disp('The transfer function of the system is:')
disp('=======================================')

inputs = {'u'};
outputs = {'x'; 'tetha'};
G=tf(system)
set(G,'InputName',inputs)
set(G,'OutputName',outputs)


%--------System Analysis-------%

%------Checking stability of the system--------%

%open-Loop impulse response

inputs = {'u'};
outputs = {'x'; 'theta'};
set(G,'InputName',inputs)
set(G,'OutputName',outputs)

figure(1);clf;subplot(221)
t=0:0.01:1;
impulse(G,t);
grid;
title('Open-Loop Impulse Response of the system')

%Open-Loop step response

subplot(222)
t = 0:0.05:10;
u = ones(size(t));
[y,t] = lsim(G,u,t);
plot(t,y)
title('Open-Loop Step Response of the system')
axis([0 2 -50 50])
legend('x','theta')
grid;


% Poles of the system and pole-zero mapping

disp('===========================')
disp('Poles of the system are:')
disp('===========================')

Poles=eig(A)
subplot(2,2,3:4)
pzmap(system);
title('Pole-zero mapping of inverted pendulum')

% Checking controllability

disp('=========================')
disp('checking controllability:')
disp('=========================')
CO=ctrb(system);
Rank_CO=rank(CO)
unco=length(A)-rank(CO)

if(unco==0)
disp('system is controllable!')
else
disp(['number of uncontrollable states are:',unco])
end;

% Checking Obserevability

disp('=======================')
disp('Checking observability:')
disp('=======================')
OB=obsv(system);
Rank_OB=rank(OB)
unobsv=length(A)-rank(OB)
if(unobsv==0)
disp('system is observable!')
else
disp(['number of unobservable states are:',unobsv])
end;

%--------Designing a closed loop controller using...
%...State feed-back control method-------%

%-----(1)-pole placement methode-------%


disp('================================================')
disp('desirable poles and the respective gain vectors:')
disp('================================================')

% First test....taking to 2 and 3 times of the real part of the dominant
% poles to the left

desirable_1=[-2.433 -1.622 -0.811+1.584j -0.811-1.584j]
K1=place(A,B,desirable_1)
Ac1 = A-B*K1;
system_c1 = ss(Ac1,B,C,D);

t = 0:0.01:10;
r =0.2*ones(size(t));
figure(2);clf;subplot(311)
[y,t,x]=lsim(system_c1,r,t);
[AX,H1,H2] = plotyy(t,y(:,1),t,y(:,2),'plot');
set(get(AX(1),'Ylabel'),'String','cart position (m)')
set(get(AX(2),'Ylabel'),'String','pend-angle(rad)')
title('Step Response using pole placement-1st test')
grid

% Second test.....taking to 5 and 10 times of the real part of dominant
% poles to the left

desirable_2=[-8.11 -4.055 -0.811+1.584j -0.811-1.584j]
K2=place(A,B,desirable_2)
Ac2 = A-B*K2;
system_c2 = ss(Ac2,B,C,D);

t = 0:0.01:10;
r =0.2*ones(size(t));
subplot(312)
[y,t,x]=lsim(system_c2,r,t);
[AX,H1,H2] = plotyy(t,y(:,1),t,y(:,2),'plot');
set(get(AX(1),'Ylabel'),'String','cart position (m)')
set(get(AX(2),'Ylabel'),'String','pend-angle(rad)')
title('Step Response using pole placement-2nd test')
grid

% Third test....taking to 12 and 14 times of the real part of the dominant
% poles to the left

desirable_3=[-11.354 -9.732 -0.811+1.584j -0.811-1.584j]
K3=place(A,B,desirable_3)
Ac3 = A-B*K3;
system_c3 = ss(Ac3,B,C,D);
t = 0:0.01:10;
r =0.2*ones(size(t));
subplot(313)
[y,t,x]=lsim(system_c3,r,t);
[AX,H1,H2] = plotyy(t,y(:,1),t,y(:,2),'plot');
set(get(AX(1),'Ylabel'),'String','cart position (m)')
set(get(AX(2),'Ylabel'),'String','pend-angle(rad)')
title('Step Response using pole placement-3rd test')
grid


% controlling using LQR Method
%-----------------------------

disp('===============================================')
disp('The weight matrices Q and R and the vector K:')
disp('===============================================')

Q = C'*C;
Q(1,1) = 80; %increasing the weight on the pendulum's angle(tetha)
Q(3,3) = 400 % increasing the weight on the cart's position(x)
R = 1
K = lqr(A,B,Q,R) %state-feedback control gain matrix
Ac = A-B*K; %constrol matrix
system_c = ss(Ac,B,C,D); %the controlled system state space model

t = 0:0.01:10;
r =0.2*ones(size(t));
figure(3);clf
[y,t,x]=lsim(system_c,r,t);
[AX,H1,H2] = plotyy(t,y(:,1),t,y(:,2),'plot');
set(get(AX(1),'Ylabel'),'String','cart position (m)')
set(get(AX(2),'Ylabel'),'String','pendulum angle (radians)')
title('Step Response using LQR')
grid


% [LQR + steady state error controller]
%--------------------------------------


Cn = [0 0 1 0]; % Modifiying C matrix for y=x
Nbar=-inv(Cn*((A-B*K)\B)); %calculating gain scaling factor
sys_lqr_et = ss(Ac,B*Nbar,C,D);

t = 0:0.01:10;
r =0.2*ones(size(t));
figure(4);clf
[y,t,x]=lsim(sys_lqr_et,r,t);
[AX,H1,H2] = plotyy(t,y(:,1),t,y(:,2),'plot');
set(get(AX(1),'Ylabel'),'String','cart position (m)')
set(get(AX(2),'Ylabel'),'String','pendulum angle (radians)')
title('Step Response using LQR and steady state error controller')
grid

%Designing state observer (state estimator)
%------------------------------------------

ob = obsv(system_c); % first checking observability of the controller
observability = rank(ob)
contr_poles = eig(Ac) %finding Controller poles

obsr_poles = [-30 -31 -32 -33] % 10 times faster than the controller
L = place(A',C',obsr_poles)' % placing observer poles


%response of the system with controller + observer = compensator
%---------------------------------------------------------------

Aco = [(A-B*K) (B*K);zeros(size(A)) (A-L*C)];
Bco = [B;zeros(size(B))];
Cco = [C zeros(size(C))];
Dco = [0;0];

sys_co_ob = ss(Aco,Bco,Cco,Dco);

t = 0:0.01:10;
r = 0.2*ones(size(t));

figure(5);clf
[y,t,x]=lsim(sys_co_ob,r,t);
[AX,H1,H2] = plotyy(t,y(:,1),t,y(:,2),'plot');
set(get(AX(1),'Ylabel'),'String','cart position (m)')
set(get(AX(2),'Ylabel'),'String','pendulum angle (radians)')
title('Step Response using compensator (controller + observer)')
grid

% the new system with Compensator + no steady state error tracker
%----------------------------------------------------------------

Acl = [(A-B*K) (B*K);zeros(size(A)) (A-L*C)];
Bcl = [B;zeros(size(B))];
Ccl = [C zeros(size(C))];
Dcl = [0;0];
Ccln=[Cn zeros(size(Cn))];%reference step command applied to x only
Nbar=-inv(Ccln*(Acl\Bcl))

Bclt = [B*Nbar;zeros(size(B))]; %modifing Bcl for the error traking purpose
sys_cm_et = ss(Acl,Bclt,Ccl,Dcl);

t = 0:0.01:10;
r = 0.2*ones(size(t));

figure(6);clf
[y,t,x]=lsim(sys_cm_et,r,t);
[AX,H1,H2] = plotyy(t,y(:,1),t,y(:,2),'plot');
set(get(AX(1),'Ylabel'),'String','cart position (m)')
set(get(AX(2),'Ylabel'),'String','pendulum angle (radians)')
title('Step Response using compensator with steady state error controller')
grid



File-2: inv_pend_ani.m
- This file has all the necessary codes (functions) for the GUI animation of the Inverted Pendulum system control
using a compensator and a steady state error controller.

function varargout = inv_pend_ani(varargin)

%{
***************************************************************************

This function is intended for use in the inv_pend_ani GUI file. It contains
the code necessary to run the GUI's simulations and controls based on the
designed compensator with steady state error controller.

Modification by: TSEGAZEAB SHISHAYE(2012420012), NWPU,Xi'an,China

Original Copyright (C) 1997 by the Regents of the University of Michigan

**************************************************************************
%}

gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @inv_pend_ani_OpeningFcn, ...
'gui_OutputFcn', @inv_pend_ani_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before inv_pend_ani is made visible.
function inv_pend_ani_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to inv_pend_ani (see VARARGIN)

% Choose default command line output for inv_pend_ani
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes inv_pend_ani wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = inv_pend_ani_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in Run.
function Run_Callback(hObject, eventdata, handles)
% hObject handle to Run (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global K
global cartpos
global pendangl
global T
global Nbar
global stepval

% Nbar data stored in the Run.UserData

A = [0 1 0 0;
51.58 0 0 0.5263;
0 0 0 1;
-7.737 0 0 -0.1789];
B = [0; -5.263; 0; 1.789];
C = [0 0 1 0;1 0 0 0];
D = [0;0];
Cn = [0 0 1 0]; %C matrix when Y=x, or step command only applied to x

% Get the weighing factors from the editable text fields of the GUI
% x=for pendulum angle, y=for cart position

x=str2num(get(handles.xtext,'string'));
y=str2num(get(handles.ytext,'String'));

Q=[x 0 0 0;
0 0 0 0;
0 0 y 0;
0 0 0 0];
R = 1;

%Finding the state feedback gain K matrix with the lqr command

disp('state feedback gain vector is:')
K = lqr(A,B,Q,R)

%The resulting LQR controller matrices
Ac = [(A-B*K)];
Bc = [B];
Cc = [C];
Dc = [D];

%finding Controller poles

disp('controller poles are:')
cp= eig(Ac);

% making the observer poles 10 times faster than the...
%real part of the slowest pole of the controller

disp('observer poles are:')
obsr_poles = [real(min(cp))*10 real(min(cp))*10-1
real(min(cp))*10-2 real(min(cp))*10-3];

% placing observer poles

disp('gain vector for the output feedback to the observer is:')
L = place(A',C',obsr_poles)'

%Compensator(controller + observer) matrices

Acl = [(A-B*K) (B*K);zeros(size(A)) (A-L*C)];
Bcl = [B;zeros(size(B))];
Ccl = [C zeros(size(C))];
Dcl = [0];

%Modifing Ccl because reference step command applied to x only ==> y=x

Ccln=[Cn zeros(size(Cn))];


%there should be some modification in the input signal for good tracking performance. that means...
%there should be extra gain used to scale the closed loop transfer function to make the steady state step
error=0.

Nbarval = get(handles.reference,'Value');
if Nbarval == 0
Nbar = 1;
set(handles.Run,'UserData',Nbar);
stepaxis=stepval/1000;
elseif Nbarval == 1

%calculating the scale factor for the overall closed-loop system

Nbar=-inv(Ccln*(Acl\Bcl))
set(handles.Run,'UserData',Nbar);
end

%Get the value of the step input from the step slider

stepval=get(handles.stepslider,'Value');

T=0:0.1:6;
U=stepval*ones(size(T));

%modifing Bcl for the steady state error traking purpose

Bclt = [B*Nbar;zeros(size(B))];
[Y,X]=lsim(Acl,Bclt,Ccl,Dcl,U,T);
cartpos=X(:,3);
pendangl=X(:,1);

%Pendulum and cart data

cart_length=0.3;
cl2=cart_length/2;

ltime=length(cartpos);

cartl=cartpos-cl2;
cartr=cartpos+cl2;

pendang=-pendangl;
pendl=0.6;

pendx=pendl*sin(pendang)+cartpos;
pendy=pendl*cos(pendang)+0.03;

axes(handles.axes1)
plot(T(1),cartpos(1), 'r', 'EraseMode', 'none')
plot(T(1),pendangl(1), 'b', 'EraseMode', 'none')

%Set the axis for the step response plot

axes(handles.axes1)
if stepval > 0
axis([0 6 -stepval/2 stepval*2])
elseif stepval < 0
axis([0 6 stepval*2 -stepval/2])
else
axis([0 6 -0.5 0.5])
end

title(sprintf('Step Response to %0.4f cm input',stepval))
xlabel('Time (sec)')

hold on

%Plot the first frame of the animation

axes(handles.axes2)
cla
L = plot([cartpos(1) pendx(1)], [0.03 pendy(1)], 'b', 'EraseMode', ...
'xor','LineWidth',[7]);
hold on
J = plot([cartl(1) cartr(1)], [0 0], 'r', 'EraseMode', ...
'xor','LineWidth',[20]);

axis([-.7 0.7 -0.1 0.7])
title('Animation of Inverted pendulum')
xlabel('X Position (m)')
ylabel('Y Position (m)')

%Check if the animation is to be advanced manually

manual=get(handles.manualbox,'Value');

%Run the animation

for i = 2:ltime-1,
if manual == 1
pause
end

set(J,'XData', [cartl(i) cartr(i)]);
set(L,'XData', [cartpos(i) pendx(i)]);
set(L,'YData', [0.03 pendy(i)]);
drawnow;

axes(handles.axes1)
plot([T(i),T(i+1)],[cartpos(i),cartpos(i+1)], 'r', 'EraseMode', 'none')
plot([T(i),T(i+1)],[pendangl(i),pendangl(i+1)], 'b', 'EraseMode', 'none')
end

%Add legend to step plot

axes(handles.axes1)
hold on
legend('Pendulum Angle (rad.)','Cart Position (cm.)')

guidata(hObject, handles);


function xtext_Callback(hObject, eventdata, handles)
% hObject handle to xtext (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of xtext as text
% str2double(get(hObject,'String')) returns contents of xtext as a double


% --- Executes during object creation, after setting all properties.
function xtext_CreateFcn(hObject, eventdata, handles)
% hObject handle to xtext (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end



function ytext_Callback(hObject, eventdata, handles)
% hObject handle to ytext (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ytext as text
% str2double(get(hObject,'String')) returns contents of ytext as a double


% --- Executes during object creation, after setting all properties.
function ytext_CreateFcn(hObject, eventdata, handles)
% hObject handle to ytext (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in reference.
function reference_Callback(hObject, eventdata, handles)
% hObject handle to reference (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of reference


% --- Executes during object creation, after setting all properties.
function reference_CreateFcn(hObject, eventdata, handles)
% hObject handle to reference (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called


% --- Executes on slider movement.
function stepslider_Callback(hObject, eventdata, handles)
% hObject handle to stepslider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
%Get the value of the step input from the step slider%
stepval=get(hObject,'Value');
set(handles.text5,'string',sprintf('%6.4f',stepval));
guidata(hObject, handles);



% --- Executes during object creation, after setting all properties.
function stepslider_CreateFcn(hObject, eventdata, handles)
% hObject handle to stepslider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end


% --- Executes during object creation, after setting all properties.
function text5_CreateFcn(hObject, eventdata, handles)
% hObject handle to text5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called



% --- Executes on button press in manualbox.
function manualbox_Callback(hObject, eventdata, handles)
% hObject handle to manualbox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of manualbox


% --- Executes during object creation, after setting all properties.
function manualbox_CreateFcn(hObject, eventdata, handles)
% hObject handle to manualbox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called


% --- Executes on button press in clear.
function clear_Callback(hObject, eventdata, handles)
% hObject handle to clear (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

%Callback for the RESET button%
axes(handles.axes1)
cla
axis([0 6 -0.5 0.5])
title('Step Response')
xlabel('Time (sec)')

axes(handles.axes2)
cartpos=0;
cart_length=0.3;
cl2=cart_length/2;

cartl=cartpos-cl2;
cartr=cartpos+cl2;

pendang=0;
pendl=0.6;

pendx=pendl*sin(pendang)+cartpos;
pendy=pendl*cos(pendang)+0.03;
cla
K = plot([cartpos(1) pendx(1)], [0.03 pendy(1)], 'b', 'EraseMode', ...
'xor','LineWidth',[7]);
hold on
J = plot([cartl(1) cartr(1)], [0 0], 'r', 'EraseMode', ...
'xor','LineWidth',[20]);
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function text1_CreateFcn(hObject, eventdata, handles)
% hObject handle to text1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
% hObject handle to axes1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes1


% --- Executes during object creation, after setting all properties.
function axes2_CreateFcn(hObject, eventdata, handles)
% hObject handle to axes2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes2


% --- Executes on button press in exit.
function exit_Callback(hObject, eventdata, handles)
% hObject handle to exit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(inv_pend_ani)

Potrebbero piacerti anche