You are on page 1of 23

# Indian Institute of Technology Bombay

## I Semester control lab project

Report on Inverted
Pendulum Controller
Design

Authors:
Barath Sastha (133070022)
Krishnamohan M (133070020)
Sandeep Kumar (133074016)
Vaibhav Somani (133074001)

Prof. Debraj Chakraborty

Abstract
Inverted Pendulum is a device with an arm fixed at a fulcrum
point that has a single axis of freedom. The objective is to apply
force or torque to this pivot point so that the arm balances on its
joint. The controlled point may be actuated in either linear or rotary
orientation. This experiment considers the rotary inverted pendulum
problem where a DC motor with rotation axis perpendicular to the
axis of the fulcrum is connected to the base.
The inverted state of the pendulum is an unstable equilibrium.
Small errors or noise can destabilize it. Feedback control is required
to continuously compensate for the noise. This experiment uses an optical encoder to provide the feedback. We use Simulink and MATLAB
environment to model the control system, which uses this feedback and
models a PID controller that outputs to the DAQ card. The motor
at base is thus controlled bidirectionally using PWM signals output
by the DAQ card. A separate motor driver circuit is used to generate
both power and electrical isolation to protect the DAQ card.

Contents
1 Introduction

## 2 Angle and angular speed measurement

2.1 Obtaining and interpreting data from relative encoder
2.2 Using DAQ card to calculate angle . . . . . . . . . .
2.3 Using Arduino to calculate angle . . . . . . . . . . .
2.4 Calculating angular speed from angle . . . . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

7
. 7
. 8
. 10
. 13

14

## 4 Motor driver circuits

14
4.1 L293D IC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2 L298N IC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5 Results, complications and future endeavors
5.1 Limitations of MATLAB as realtime operating system . . . . .
5.2 ARDUINO Serial port output . . . . . . . . . . . . . . . . . .
5.3 Motor driver . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19
19
21
22

6 Suggestions

22

List of Figures
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

## Basic overview of the system . . . . . . . . . . . . . . . . . .

Pendulum physical dimensions . . . . . . . . . . . . . . . . .
Motor details . . . . . . . . . . . . . . . . . . . . . . . . . .
Relative encoder diagram . . . . . . . . . . . . . . . . . . . .
Encoder track pattern and corresponding signal . . . . . . .
Basic logic for detecting angular change at 4x in Simulink . .
Main Angle counter and Angular Speed decoder blocks in
Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Angle and Angular Velocity using Arduino and serial communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PID controller Simulink diagram . . . . . . . . . . . . . . . .
L293D Pin layout . . . . . . . . . . . . . . . . . . . . . . . .
L293D maximum ratings . . . . . . . . . . . . . . . . . . . .
L293D application diagram for bi-directional motor control .
Circuit diagram to illustrate using channel 1 to drive motor .
L298N DC motor driver layout . . . . . . . . . . . . . . . .
L298N DC motor driver maximum ratings . . . . . . . . . .
L298N DC motor driver application diagram . . . . . . . . .
L298N DC motor driver application note . . . . . . . . . . .
Encoder Angle conversion process by DAQ card . . . . . . .
PD controller output . . . . . . . . . . . . . . . . . . . . . .
PWM output . . . . . . . . . . . . . . . . . . . . . . . . . .
Missed ticks behavior in MATLAB . . . . . . . . . . . . . .

.
.
.
.
.
.

5
6
6
7
8
9

. 10
.
.
.
.
.
.
.
.
.
.
.
.
.
.

12
14
15
15
16
17
17
18
18
18
20
20
21
21

List of Tables
1
2
3

## Logic for reading change in angle at various speeds . . . . . . 9

L293D application note . . . . . . . . . . . . . . . . . . . . . . 15
Absolute maximum ratings for L298N . . . . . . . . . . . . . . 16

Introduction

## An inverted pendulum is a classic example of a nonlinear mechanical system

containing a pendulum with its center of mass above its pivot point.
The objective of the experiment is to balance a pendulum vertically up
with motor driven arm using PID control.
Setup Description:
PC running MATLAB
Plant: The system consists of a 24-Volt DC motor that is coupled
with an encoder and is mounted vertically in the metal chamber. It
allowed to freely rotate in vertical configuration. The arm link rotates
in horizontal configuration and is connected to the pendulum link at
one end and to the motor shaft at the other.
Optical encoder: There are two optical encoders, one to measure the
angular position of the pendulum link and another for the arm link.
These encoders converts angular displacement into digital pulses which
are fed into MATLAB blocks, where it is converted as degrees. The
angular position and its corresponding derivatives are used as feedbacks
for PID control.
The system is later enhanced by using arduino (ATmega2560) to measure angles from encoder for high sampling rate to avoid missed ticks. The measured
angles are then fed into MATLAB from Arduino connected to PC through
an USB port.
Motor driver circuit: The motor driver used is L293D of Texas Instruments through which controlled (PWM) voltage is given to motor input terminals. The same driver is used to give direction control to the motor.
DAQ: The DAQ card used is PCI-MIO-16E-1 model of National Instruments which is used to connect optical encoders and motor drivers to the
PC.

## Figure 1: Basic overview of the system

More details on every component will be given in respective topics of this
report.
The work has been carried out in following steps:
1. Study and analyze the physical inverted pendulum model, DAC cards,
optical encoders and motor driver circuits used
2. Setup connections between optical encoders, motor driver (L293D),
DAC card to the computer running MATLAB
3. Design the PID controller for balance up controller
4. Code in Arduino (ATmega2560) to measure the pendulum angle at
high sampling rate
How is inverted pendulum balanced?
The inverted pendulum (IP) is balanced by implementing a feedback from
pendulum angle and its derivative (the other states being arm angle and its
derivative). Please note that the experiment has been setup only for balance
up position and not for swing up control.
The pendulum has two stationary points, one at 0 degree (stable) and
another at 180 degree (unstable). The inverted pendulum can be kept at
vertical position by applying oscillating force as motor torque. 24V DC
motor has been used. Physical dimensions of the inverted pendulum are as
follows:
5

6

## Angle and angular speed measurement

Optical encoder is an electro-mechanical device, primarily a sensor that encodes angle into an analog or digital electrical signal. There are generally
two classes of optical encoders: Relative encoders, that only give the change
in angle, and absolute encoders which give the absolute value of the angle
with reference to a designated zero. This experiment uses two relative optical
encoders, one to give positional change of the motor axis and the other for
the arm axis, perpendicular to that of the motor axis.

2.1

## Obtaining and interpreting data from relative encoder

The relative encoder consists of two perforated disks set in quadrature with
respect to each other. This is illustrated in figure 4.

## Figure 4: Relative encoder diagram

Each disk has 1024 perforations in the cycle. The data is mapped onto
two channels: A and B, with track patterns as shown in figure 5, which lead
to two square pulses that are a quadrature apart.

## Figure 5: Encoder track pattern and corresponding signal

From this information, position value of angle may be inferred by arbitrarily defining:
The initial state as reference value 0 degrees
Clockwise rotation as negative count

2.2

## Using DAQ card to calculate angle

The first option is to use the DAQ card to input the data from channels A
and B as discussed in previous section, at the digital I/O port. Since the
channels are sending a square pulse, digital port is sufficient to read them.
The simulink setup to read angle for logic given above, at each rate are shown
in figures 6 and 7.

Speed
1x
2x
4x

Clockwise
BA=1
B A = 1; B A = 0
A B = 0; A B = 1;
B A = 1; B A = 0

Anticlockwise
AB=1
A B = 1; A B = 0
A B = 1; A B = 0;
B A = 0; B A = 1

## Figure 6: Basic logic for detecting angular change at 4x in Simulink

9

Figure 7: Main Angle counter and Angular Speed decoder blocks in Simulink
The sampling rate guarantee of real time windows target in normal mode
is claimed by Mathworks to be nearly 500. In practice, it is found that the
current setup gives generally a much worse performance. This is elaborated
upon in the last section. Due to the inaccuracy resulting from missed ticks,
we move to the second option, using arduino to decode and count angle.
Application Note
1. Mathworks claims that executing the real time simulink design in external mode guarantees a much better (20khz) rate, the next logical
step is to use it and verify the existence and frequency of missed ticks,
or lack thereof.

2.3

## As noted before, a real time system is essential to provide a feedback to

make this system solvable. This drawback of the previous setup may be
circumvented by having a man-in-the-middle as it were that provides a nearly
real-time performance for the same.
10

For this function, dedicated ICs like HCTL-2021 quadrature decoder/counter IC are available in market. Due to constraints, the arduino development board is used here without noticeable loss of performance. The
channels A and B are supplied to interrupt enabled pins of the arduino board,
because we need edge detection for the signals as is explained in the logic
above. However, to avoid any issues with conflict of interrupt service routine
(ISR), the arduino board is used to handle only one optical encoder.
Transmitting data from arduino board to MATLAB For this purpose,
multiple options are available:
Serial port that is already interfaced to the onboard serial to USB
converter
Analog output through PWM pin, using analogWrite() command
Breaking down the data as individual bits and transmitting via digital
pins using digitalWrite() command
Clearly, considering clocking considerations and overhead, the digital
port write appears to be the best option. However, the DAQ card available
has 8 digital I/O pins, 3 of which are interfaced to control the motor driver
circuit (this can however be circumvented by using the analog channel instead, which can be used as a quasi digital input port). In addition, it takes
some clever register manipulation and multiplexing to:
1. Distribute each 10 bit resolution signed count over two cycles of 8 bit
digital writes
2. add signatures to each frame to denote start frame, stop frame and
signed/unsigned state
Although the overhead for this is not comparable to that for serial communication and it still takes place at a quicker pace than PWM output, the
arduino platform is unsuitable for such programming tactics. It will require
instead to build a basic application board with a raw microcontroller, programmed using either ASM or C for best effect considering the complexity
in our code is not high.
On the other hand, PWM is impractical for this purpose because this
mode requires the Timer0 to be enabled, which relies on its own interrupt
calling where it halts other ISRs to service its own. This is clearly unacceptable for our situation where we require real time handling of optical encoder
interrupts. A framework that is capable of handling parallel interrupt calls is
required. In addition, PWM resolution is 8bits, whereas our tick resolution
11

at 4x is 16 bits deep being a signed integer data type. This can be circumvented by using PWM to denote only a small variation from the mean. This
solution is good enough for this application because the controller design
is just for balancing the pendulum, which becomes irreversibly unstable for
larger deviations of angles anyways.
Serial port transmit has two major issues:
1. The output data is always as strings of characters where each block
varies in length according to data to be transmitted. This requires
some clock formatting on both ends to transmit and receive properly.
2. There is an inherent latency in serial data transmit due to the fact
that the serial communication header file for arduino contains a delay
command for 25ms. If this is tampered with, it may lead to somewhat
unpredictable serial communication behavior.
This builds a stronger case to move away from arduino and onto a raw microcontroller platform or dedicated quadrature decoder counter IC. However,
a working version of serial transmit, with very low error but high latency is
presented in its Simulink model form.

Figure 8: Angle and Angular Velocity using Arduino and serial communication

12

Application Notes
1. We can observe that error in angle computation still creeps in even with
arduino. With a little engineering, we see that changing the overflow
conditions to optimize and then adding a delay in the range of 25
microseconds reduces the error to least possible value. Our hypothesis
is that this is the point where there is the least probability of false
positives while the sampling being fast enough to avoid false negatives.

2.4

## Calculating angular speed from angle

Once we have the angle input into the system, the angular speed needs to be
calculated according to the following algorithm for maximum accuracy and
performance
input : Angle
output: Angular speed
begin
Timer t : {t = 1ms
end
while 1 do
if > 0 then
= /t
end
if t = 1s AND = 0 then
= 0;
end
Reset t;
end
Algorithm 1: Discrete domain angular speed calculator
In practice, due to the various limitations cited earlier, the simple algorithm shown below also works within tractable error bound.
Application Notes
1. To compensate for performance loss due to missed ticks, we can assume
that the simple algorithm for angular velocity can also be implemented
externally on the arduino board. However, this is impossible because
of the same reason as PWM is not practical, in that due to the Timer
class being initiated, ISR for optical encoders are interrupted.

13

input : Angle
output: Angular speed
begin
Timer t : {t = 1ms
end
while 1 do
if t = 1ms then
= /t
end
end
Algorithm 2: Simple angular velocity algorithm

## Executing with simple PD controller

The PID controller used is illustrated in figure 9. We havent included Integrator because it is not applicable for experiment.

4
4.1

L293D IC

## The L293D is a quadruple high current half-H driver IC .It is designed to

provide bidirectional drive currents up to 600 mA at voltages from 4.5 volts
to 36 volts. It is a 16 Pin IC consisting of 2 driver channels on either side
of the chip.channel 1 has inputs at Pin 2 and Pin 7 respectively and outputs
at Pin 3 and Pin 6 respectively.Channel 2 has inputs at Pin 10 and Pin 15
respectively and outputs at Pin 11 and Pin 14 respectively.
14

## Figure 10: L293D Pin layout

The absolute maximum ratings of various parameters are given in figure
11

## Figure 11: L293D maximum ratings

The following table presents the motor driving function of channel 1 depending on inputs given at 1A and 2A(Pins 2 and 7) .The outputs of the
drivers 1A and 2A (Pin 3 and 6 respectively) are to be connected to the
input channels of the motor(motor channel A and B).EN denotes the enable
pin(Pin 1 for drivers with inputs 1A and 2A) .The drivers remain disabled
as long as this pin is grounded.
EN
1A
2A
Function
high
low
high
Turn right
high
high
low
Turn left
high
low
low
Fast Motor Stop
high
high
high
Fast Motor Stop
Low high/low high/low Fast Motor Stop
Table 2: L293D application note
15

## Thus the motor can be made to rotate in either direction by applying

appropriate inputs 1A and 1B .In order to vary the output torque and thus
the speed of rotation a Pulse width modulated(PWM) wave can be applied
at the enable pin ,EN. Now the output torque depends on the duty cycle of
the PWM wave.

## Figure 12: L293D application diagram for bi-directional motor control

Parameter
Supply voltage,VS
Logic supply voltage,VSS
Input voltage,V1
Output voltage range V0
Peak output current,I0
Continuous output current,Ic

Value
36V
36V
7V
-3V to VCC2 + 3V
1.2A
600mA

16

## Figure 13: Circuit diagram to illustrate using channel 1 to drive motor

4.2

L298N IC

The L298N is a high voltage,high current dual full bridge driver.Like in the
L293D,it has 2 channels and 2 enable inputs are provided to enable or disable
the device independently of the input signals.Channel 1 input is between pins
5 and 7 and output is to be taken across Pins 2 and 3.Channel 2 inputs are
to be given between Pins 10 and 12 and outputs are obtained across Pins 13
and 14.Pin 6 serves as the enable Pin for channel 1 and Pin 11 is the enable
Pin for channel 2. The IC can output a maximum of 2A per channel.As in
the case of L293D the outputs of both channels can be Paralleled for higher
current.

17

## Figure 15: L298N DC motor driver maximum ratings

The followings diagram shows half part of the IC being used to drive a
stepper motor and the table for rotation of the motor.

18

5
5.1

## Results, complications and future endeavors

Limitations of MATLAB as realtime operating system

## We used MATLAB-Simulink model to decode the encoder output to get the

angle of the pendulum and the motor arm. We noted that the angle recorded
was quite accurate during initial program runs but errors crept into it as
the time progressed. We also noted that the error was very high when the
pendulum was moved at high angular speeds. After few runs we understood
that the mean value (or reference value) of the angle was shifting.
Then to analyse the problem we conducted lot of experiments by giving
squarewave from a function generator and reading it in MATLAB. After
analysis we found that the MATLAB was not recording the input signal
correctly. It was missing many of the samples of the input signal. We found
out that there was a relation between the Missticksreported by Digital
Input block. Whenever there was a misstick the program missed to record
a sample. The number of samples missed are proportional to the number of
missticks.
It was obsevered that the number of missticks reduced as we reduced the
sampling frequency but they were always present. At sampling frequency as
low as 500 Hz also there were missticks.
We therefore concluded that MATLAB as an realtime operating system
does not give a guarantee of even 500 Hz. As the encoder input signal
frequency is upward of 1 Khz, a minimum sampling rate of 10Khz is required
getting recording signal in high fidelity, hence MATLAB is unsuitable for the
puporse of decoding the encoders.

19

20

5.2

## To solve the problem of decoding angle, we wrote a code in Arduino using

Mega 2560 kit. The angle now measured was quite accurate and very low
error was there even when pendulam was moved at high angular velocity. We
transmitted the data to MATLAB through serial port, but we found that
there was some lag in the data. On analysing we was found that the serial
port eventhough when used at high baud rates of 38400 was not sufficient
to work on the problem. Another option was to send analog data through
21

analog card, but the bit resolution of Mega 2560 is 8 bits (256 counts) is too
low for angle as we wont be able to get even one degree resolution.
Also one Arduino can be used for only one encoder as the program is
based on interrupt.

5.3

Motor driver

We analysed that the power supply required for the motor is more than 2 A.
We designed motor driver with two numbers of IC L293D in parallel. This
gave a total of 1.2A output current but this was not sufficient. To go for
higher current rating we tried to make a motor driver with IC L298N which
is capable of giving 2A current. But, we somehow couldnt make it work.

Suggestions

Hardware based decoder for optical incremental encoders As decoding the encoder output is the most important par of the experiment,
no error can be tolerated in it. We analysed that the best way is to
go for hardware based decoders such as HCTL-2032 or LFLS7082-S.
These IC based decoders can give output for two numbers of incremental encoders as required in our case. We tried to procure them but the
delivery time in India was 21 days.
Better Motor driver As the error increases the motor driver is not able to
give sufficient current to the motor and hence torque developed is not
suffiecient to reduce the error. Suitable motor driver may be fabricated
with current capacity of 3 A.
Incremental Encoder with reference signal Most of the incremental encoders have a reference signal for correction of the errors in angle
calculation. We suggest that if a new experiment setup is being designed/procured then if they should have incremental encoders with
reference signal. This will enable the experiment to be completed by
MATLAB alone.

22