Академический Документы
Профессиональный Документы
Культура Документы
PROJECT REPORT
APRIL 2017
DEPARTMENT OF ELECRICAL AND ELECTRONICS ENGINEERING
JOHN COX MEMORIAL C.S.I INSTITUTE OF TECHNOLOGY
KANNAMMOOLA, THIRUVANANTHAPURAM-695011, KERALA
CERTIFICATE
This is to certify that this project report entitled PID CONTROLLERS ON A DESIGNED
TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT is a bonafide record of
project presented by ABHIJITH B. (13423001), JOEL S. (13423014), and SARATH JAISON
MEDAVILA (13423022) towards the partial fulfillment for the requirement for the award of the
Degree of Bachelor of Technology in Electrical and Electronics Engineering of the University
of Kerala during the year 2017.
We wish to express our sincere gratitude to Mrs. J. Sheeba Jeba Malar, Head of the
Department of Electrical and Electronics Engineering, John Cox Memorial C.S.I
Institute of Technology, Kannammoola for providing us opportunities and facilities for doing
this project.
We express our heartfelt gratitude to our project guide Mr. B. P. Beno Ben, Assistant
Professor, Department of Electrical and Electronics Engineering, John Cox Memorial
CSI Institute of Technology, Kannammoola for his valuable guidance, advice and constant
encouragement throughout the course of the project.
We are very thankful to our project coordinator Mr. Lim J Seelan, Assistant Professor of
Department of Electrical and Electronics Engineering, JCMCSIIT for his direction and
helpful suggestions.
We are also thankful to our Principal, Prof. Dr. N. Selvaraj for his support and
suggestions.
Above all, we would like to thank God Almighty for giving us strength, courage and
showing right way at all points of obstruction.
It would be unfair if we would forget to acknowledge the support of our parents, siblings
and our friends in this endeavor. We extend our honest gratefulness for their supports, help
and encouragement at various stages of this venture.
ABHIJITH B.
JOEL S.
SARATH JAISON MEDAVILA
ABSTRACT
The research on a two-wheel inverted pendulum, which is commonly known as the self-
balancing mobile robot, has gained momentum over the last decade in a number of robotic
laboratories around the world. This is shown by a rapid increase in the number of journal papers,
research projects and theses on the subject, which have been dealing with similar projects. The
principles of operation of such a robot are also used in a commercial electric transportation
vehicle called Segway. The self-balancing mobile robot on two wheels, called Tilter, works on
the principle of an inverted pendulum. The robot is inherently unstable and without external
control it would roll around the wheels rotation axis and eventually fall. Driving the motors in
the right direction returns the robot to the upward position. Although the robot is inherently
unstable, it has several advantages over the statically stable multi-wheeled robots since it has
only two wheels (two points touching the ground) it requires less space; since it is based on
dynamic stability (it constantly needs to correct its tilt angle to remain stable) it exhibits
improved dynamic behavior and mobility.
An autonomous dual wheel self balancing robot is developed that is capable of balancing
its position around predetermined position. Initially the system was nonlinear and unstable. It is
observed that the system becomes stable after redesigning the physical structure of the system
using PID controller and analyzing its dynamic behavior using mathematical modeling. The
position of self balancing robot is controlled by PID controller.
The aim of this project is to design and implement PID based two wheeled self-balancing
robot to solve the inclination angle problem to balance the movement of robot and to implement
in real time. We are designing the code and implement an efficient self-balancing PID algorithm
using the embedded controller and to implement in real time.
CONTENTS
CHAPTER NO. TITLE PAGE NO.
i
5.4.1 Proportional Control 39
5.4.2 Integral Control 40
5.4.3 Derivative Control 41
5.5 Stability 43
5.6 PID Controller tuning 44
5.7 Android Platform 45
6 PROJECT IMPLEMENTATION 47
6.1 Phases 47
6.2 Cost Estimation 48
7 RESULTS 49
8 ADVANTAGES AND DISADVANTAGES 52
8.1 Advantages 52
8.2 Disadvantages 53
9 APPLICATIONS 54
1 CONCLUSION AND FUTURE SCOPE 55
0
10.1 Evaluation 56
10.2 Improvements and alterations 56
10.3 Additional features and capabilities 56
10.4 Future Improvements 57
10.5 Ethical Considerations 58
11 REFERENCES 59
APPENDIX A 60
ii
LIST OF FIGURES
iii
LIST OF TABLES
Table No. Title Page No.
iv
LIST OF ABBREVIATIONS
PID - Proportional Integral Derivative
LQR - Linear Quadratic Regulator
PD - Proportional Derivative
DSP - Digital Signal Processing
SPI - Serial Peripheral Interface
DC - Direct Current
IMU - Inertial Measurement Unit
UAV - Unmanned Aerial Vehicle
UART - Universal Asynchronous Receiver Transmitter
ADC - Analog Digital Converter
FIFO - First In First Out
CMOS - Complementary Metal Oxide Semiconductor
GPS - Global Positioning System
LED - Light Emitting Diode
RISC - Reduced Instruction Set Computer
PC - Personal Computer
CISC - Complex instruction set computing
PWM - Pulse Width Modulation
SDA - Serial Data
SLC - Serial Clock
AVR - Alf and Vegard's RISC
v
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
CHAPTER 1
INTRODUCTION
We, since childhood, have inherently and unknowingly been practicing to balance various
objects. It may be balancing stick on palm, moving with a glass of water filled up to the brim,
walking on a narrow wall, cycling, etc. All of it requires a balancing algorithm for which we
have trained our brain to do so. Similar examples can be quoted from industrial applications like
Segway, loading machines at shipyard, robotic applications, etc.
We, in this project, will be working on a similar concept with a focus on transportation
industry and affordability. Over the years, this industry has been evolving, rolling out various
innovative products in the market. There has also been a constant focus on customers needs and
demands.
This project of ours will focus on small spectrum of personalized mobile platform,
primarily for physically challenged people for the Indian market. During the course of this
project, we will be making a scaled down version of the same to prove the concept, incurring
minimum cost. To be more precise, it is a two-wheeled platform with a dummy weight at the top
symbolizing a person, required to balance vertically and be able to move in desired direction.
A similar concept being studied since long is an experimental setup known as Inverted
Pendulum. It is a common control system implementation. It is a system with mass above its
pivot point. While a normal pendulum is stable hanging downwards, an inverted pendulum is
inherently unstable. For an inverted pendulum to balance, it is required to continuously take the
feedback of its tilt from its unstable equilibrium position and correct it by applying external
force, which, in our case, is done by actuating a motor.
In our case, we need to balance the pendulum about its unstable equilibrium. Hence, any
disturbance needs to be quantifiably detected and instantly corrected by an external force. There
-1-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
is a limited disturbance angle beyond which it may be mathematically impossible to get it back
to its equilibrium position with any amount of external force.
Its quite difficult to hold a pen in your hand and balance it. But to do the same thing with
a broom in your hand, its relatively simple. The reason is that there is more time to compensate.
For that reason, its actually easier the higher we are off the ground. There are various control
algorithms widely used for such applications. We have used a PID controller in our case. A
processor and electric motors in the base of the device keep the vehicle upright when powered on
with balancing enabled. Gyroscopic sensors are used to detect tilting of the device which
indicates a departure from perfect balance. Motors driving the wheels are commanded as needed
to bring the vehicle back into balance. The dynamics of the vehicle are identical to a classic
control problem, the inverted pendulum. The vehicle has electric motors powered by lithium-
polymer batteries. It balances with the help of a microcontroller, accelerometer, and gyroscope.
1.1. Motivation
Over past few years, we have seen the transportation industry grow and providing its
customers with innovative solutions in personalized mobile platforms. But, less was focus on
physically challenged people. Our focus in this project will be towards trying to engineer a
personalized mobile vehicle for physically challenged people and design it in away keeping in
mind their inherent constraints. At the same time, the vehicle will be designed with affordability
as one of the deciding factors in coming up with the design and manufacturing process.
1.2. Scope
As it is not possible for us to come up with a full scale, robust and aesthetic product in the
given time frame, we will be concentrating on making a scaled down version of the experimental
setup to prove the concept and affordability. During the process, we will be taking a standard
literature of inverted pendulum on an experimental basis and make a two-wheeled personalized
mobile platform, which could travel in the desired direction by sensing either the external control
signals or the tilt of the rider, which will be a dummy weight in our experiment. This inverted
pendulum, being free to move in any translational direction and rotate about its own vertical axis.
For the theoretical analysis, we will consider cart and a pendulum problem. For balancing this
system, there are various controllers that can be used. We, in our case, will be using PID
Electrical and Electronics Engineering
JCMCSIIT
-2-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
controllers, which is a common and basic of all. We will be stating a standard protocol to
manually tune the PID controller as per our needs with varying physical parameters. Because of
limited resources available, the setup will be limited to balance and traverse only on flat surfaces,
not even on inclined planes. Scaling it up to commercially launch it in the market will require
scaling up of hardware as well as electronics. Power requirements for the battery and current
ratings of the motor driver will go up proportionally. Motors will require to have higher torque
and speed. Sensor should be able to detect tilt independent of the ground in order for the setup to
work in all-terrain. Hardware will need to be stronger for it to be able to support an average
human beings weight. Aesthetics and ergonomics will play an important role when placing the
same in the consumer market.
1.3. Objective
Objective of this project is to demonstrate a working prototype (scaled down version) of a
personalized mobile platform which can move in desired direction of travel inclusive of
translation while at the same time balancing itself vertically in a smooth fashion.
1.4. Limitation
Resources available limit us, in this project. Sensors used in this project are not suited for
wide range of applications, as we would explain later in detail. Motors do not have inbuilt
encoders and hence cannot be used for dead reckoning. Motors not being a standard one, its
gains could not be determined and hence computer simulation of the same could not be carried
out with accuracy. Due to limited time availability, battery voltage could not be regulated for the
motors, which plays an important role in the response of the system. Acquisition of data on to the
computer for the purpose of further analysis of data is again limited due to less powerful
microprocessor onboard.
-3-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
CHAPTER 2
LITERATURE REVIEW
The paper [1] presents a method to design and control a two wheeled self balancing robot
and it focus on system modeling and PID controller design and then discussed method to control
a two-wheeled self balancing robot using a PID controller by analyzing the response, balance
and robustness against disturbance.
The development of kinematics model of a two wheeled self balancing robot and its
control using various control techniques is described in the paper [2]. The analysis of the
developed kinematic model can be divided into wheel and frame structure, after one is done with
design and development of system is finalized. The said test platform is highly non-linear and
unstable system. Main focus of the paper is to develop an efficient controller required to enable
the robot to act in real time and test different controllers to analyze their performance by the
vertical balance, position, its control signal and disturbance rejection capabilities.
A control strategy and sensor concept for a two wheeled self balancing robot is proposed
in the paper [3]. For nearly two decades research and development of self balancing vehicles is
taking place. In 2001 the Segway, a self balancing transportation system controlled by balance
shift of the driver, was introduced and got commercially available. It has been noticed by the
broad public as a modern, futuristic vehicle. Although the Segway evolved over the last years as
some kind of lifestyle product it was originally designed as a serious transportation system in
urban areas. With the upcoming availability of low-cost, high performance MEMS sensor
technology, the use of inertial sensors was no longer restricted to high end applications like
avionics or space missions and the self-balancing concept also arrived at robotics. Even though a
two-wheeled self-balancing robot is an inherently unstable system which needs to be stabilized
by electronic means, the two-wheeled movement can have also several benefits. Because of the
reduced wheel count the robot can provide low footprints, compared to traditional systems and is
also capable of turning around stationary for constricted area applications. Equipped with
Electrical and Electronics Engineering
JCMCSIIT
-4-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
loading platforms or manipulators self balancing robots, working in human controlled or even
completely autonomous operation, might be used in industrial autonomous transportations
systems or warehouses in the future. From a more technical standpoint, a two wheeled self
balancing robot is representing a mobile inverted pendulum, which is a classic problem in
dynamics and control theory. In recent years intensive and diverse research is going on in this
field and numerous robot concepts and control strategies have been proposed, ranging from
linear state space controllers with pole placement and LQR controller design to nonlinear and
intelligent control methods like sliding mode control. The majority of these studies have their
individual focus on trying to implement new control methods which have not been tested yet for
self-balancing robots. For development of such a robot numerous further issues like motor drive
and sensor characteristics also need to be considered in overall control design. Also, the
complexity of the control algorithms is important for efficient implementation on small
microcontroller systems. In this paper an in depth overview, beginning with basic theoretical
considerations and ending with a ready to implement control system is given. For stabilization, a
well proven linear state space control is used and for state variable acquisition a novel
gyroscope-accelerometer sensor fusion method is proposed. The model parameters of a real
prototype robot are determined by using specifically designed measurement proceedings.
Two wheeled self balancing robot is a nonlinear and unstable system, which has aroused
a lot of researchers attention. The kinematics analysis and dynamic modeling are the basis of the
research on the two wheeled self-balancing robot, and the key problem is the realization of real
time control. According to the mechanical characteristics of the two wheeled self balancing
robot, the mathematical model of the controlled system is established. The kinematic and
dynamic characteristics of the robot are analyzed, and the theoretical basis for the design of the
control system is obtained in this paper [4]. Self balancing is the premise of robot standing, while
standing is a necessary condition for robot motion. How to keep the balance and resist the
external disturbance is the key point of the research of the two-wheeled self-balancing robot. Self
balancing algorithms include traditional, modern and intelligent control algorithms. The modern
control theory is mainly focused on the multi variable and strong coupled nonlinear system
which cannot be solved by using the traditional control theory.
-5-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
The paper [5] presents a method to design and control a two-wheeled self balancing robot
and it focus on hardware description, signal processing, discrete Kalman filter algorithm, system
modeling and PID back stepping controller design. In the system, signals from angle sensors are
filtered by a discrete Kalman filter before being fed to the PID back stepping controller. The
objectives of the proposed controller are to stabilize the robot while try to keep the motion of
robot to track a reference signal. The proposed PID back stepping controller has three control
loops, in which the first loop uses a back stepping controller to maintain the robot at equilibrium,
the second loop uses a PD controller to control the position of robot and the last uses a PI
controller to control the motion direction. Simulations and experimental results show that the
proposed control system has good performances in terms of quick response, good balance, and
stability.
There has been a continuous and focused research towards personalized mobile vehicles.
Though they are commercially available in the market, they have their own disadvantages. There
are many experimental setups across the world with similar concept targeting at varied range of
application.
2.1. Segway
Segway Inc. of New Hampshire, USA is the manufacturer of a two-wheeled, self-balancing
electric vehicle, the Segway PT, invented by Dean Kamen. The name Segway is a homophone of
segue (a smooth transition, literally Italian for follows).
Segway, as the company claims, are worlds leading provider of personal electric
transportation. Segway markets a full line of zero-emissions personal transporters for indoor,
sidewalk, cross-terrain and patrol use, which deliver impressive energy efficiency equivalent to
450 miles per gallon.
Segway claims for inbuilt technologies in its product like dynamic stabilization (providing
incredible maneuverability, zero turning radius, a small footprint), electric propulsion (precise
software-based approach to traction control and braking), smart battery management
-6-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
(regenerative braking capability), advanced inertial sensing, intuitive user interfaces and digital
dashboard.
Its working principle remains the same. To move forward or backward on the Segway PT,
the rider just leans slightly forward or backward. To turn left or right, the rider simply moves the
Lean Steer frame left or right. Segways balance-control system works in tandem with a pair or
electric motors, one powering each wheel. That motion-control algorithm, which requires input
from four sensors under the riders feet and five solid state gyroscopes, is the soul of the Segway.
Specifications:
o Motion control algorithms are run on a DSP designed by Texas Instruments using a
variety of embedded control and data buses like I2C, SPI and SCI
o It can travel as far as 24 miles on a single battery charge, depending on terrain, payload
and riding style.
o The industrial model weighs 80 pounds, while the smaller, personal Segway is 65
pounds.
o At idle, the Segway can stand upright by itself, balancing on its internal gyros, and will
do so for up to 34 hours
In 2003, the company sold 6000 units, by September 2006 approximately 23,500 and by
May 2009 50,000 had been sold. Currently, the Segways will cost between $8000 and $10,000.
-7-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
For safety sake, the Segways control mechanisms were designed to be redundant. The
Segway contains two motors, each with a set of windings, but with a common shaft. Since the
motors can apply opposite torque, the machine can turn in place with no additional turning
radius. Segways also ship with kickstands.
Segways have had success in niche markets such as transportation for police departments,
military bases, warehouses, corporate campuses and industrial sites. The legal roadworthiness of
the Segway varies with different jurisdictions classifications of the device as a motor vehicle
Honda U3-X is a compact experimental device that fits comfortably between the riders legs,
to provide free movement in all directions just as in human walking forward, backward, side to
side and diagonally. It uses Honda Omni-Traction (HOT) drive system to permit it to move in
any lateral direction.
Specifications:
-8-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
The Winglet consists of a body (with a projected area the size of an A3 sheet of paper) that
houses an electric motor, two wheels, and internal sensors that constantly monitor the users
position and make adjustments in power to ensure stability. Meanwhile, a unique parallel link
mechanism allows the rider to go forward, backward and turn simply by shifting body weight,
making the vehicle save and useful even in tight spaces or crowded environments.
Specifications (L Model):
o Weight: 12.3 kg
o Turning Radius: 0
o Cruising Range: 10 km
-9-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
o Lighting: External lights can confuse the color sensor, especially if the amount of
lighting or shadow varies as the robot moves around. Also, florescent lights will interfere
less than incandescent lights.
o Surface: The robot requires a surface that has very uniform brightness. Blank white
paper will work well, or any surface that is a uniform solid color with no pattern. A wood
floor with a wood grain pattern, or a title floor with texture will not work well, because
the light reflection will vary as the robot moves.
o Initial Balance: Since the color sensor cannot tell which way is up, the robot must start
perfectly balanced to begin with, and then program will try to maintain that balance by
trying to seek out the same reflected light reading that the color sensor had at the
-10-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
beginning of the program. Specifically, the robot must be physically balance, which is not
the same as holding it visually straight up.
Programs that balance this robot is a basic PID controller that uses the color sensors reading
to determine an error in its position and then tries to correct for it. If the robot starts not quite
balanced, it will drive steadily in one direction, or perhaps even accelerate in that direction and
then fall.
This vehicle has 3 degrees of freedom. It can rotate about the wheel axis (pitch), linearly
translate and rotate about the vertical axis (yaw). Six state spaces variables fully describe the
dynamics of the system.
-11-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
CHAPTER 3
METHODOLOGY
We will carry out a theoretical analysis of our project and try to mathematically calculate the
results with given assumptions and constraints. We hereby state that these results may not closely
match the experimental results due to underlying assumptions and unavailability of few
parameters that determine the response of the setup.
-12-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
We will also be looking at methods to manually tune the controller, looking at its response to
any given parameter.
3.2. Equilibrium
Equilibrium is a state of a system in which the variables that describe the system are not
changing. Every pendulum pivot about a frictionless point has two equilibrium positions, stable
and unstable in its complete possible rotation. In a Stable equilibrium, if a small perturbation
away from equilibrium is applied, the system will return itself to the equilibrium state. In an
unstable equilibrium, if a small perturbation away from equilibrium is applied, the system will
move farther away from its equilibrium state. Strictly speaking, mathematically we determine
whether a mechanical equilibrium is stable or unstable by looking at the second derivative of the
energy with respect to the coordinate of interest.
As an example, assume we have a pendulum weighing 1kg and is pivot about a point
with the help of massless rod of length 50cm. Following will be its energy curve (assuming the
velocity to be zero at equilibrium) as a function of angle from vertical.
-13-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Figure 3.1: Stable and Unstable Equilibrium of the free pendulum pivot about a
frictionless point
3.3. Assumptions
The dynamic model of the proposed robot is calculated based on Newtonian method.
Assumptions which are considered in this dynamics model can be regarded as:
1) Body and wheels are rigid
2) Both wheels have same radius
3) The wheels roll on the ground without slipping
4) The ground is a flat surface with a certain slope
5) Both wheels have the same mass
-14-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Figures 3.2 and 3.3 illustrate the proposed robot dynamic model parameters. By considering m
as wheel mass and Ff as friction force between the ground and wheels, one has equation 3.1:
ma= Ff - FH (3.1
)
Where a is the linear acceleration and FH is the reactionary force between wheels and the
proposed robot body. By considering as the wheels angular acceleration and as motor
torque, one has equation 3.2:
-15-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Ffr = J (3.2)
In (3.2), r is the wheel radius and J is the model rotational moment of inertia. In order to
calculate the proposed robot body dynamic model terms, by considering M as the robot mass and
xs as distance between the robot center of mass and x-axis, one has:
xs = x+dsin (3.3)
2
d xs (3.4)
M dt
2 = 2 FH
In (3.3), is the angular displacement of the under-study self balancing robot body from balance
situation and d is the distance between the motor shaft and the proposed robot body center of
mass. By substituting (3.3) into (3.4), one has:
2
d (x +dsin ) (3.5)
M dt2 = 2 FH
ys = d(1-cos) (3.6)
2
d ys (3.7)
M dt
2 = 2 Fv Mg
where Fv is the reactionary vertical force. By substituting (3.6) into (3.7), one has (3.8):
2
d (d ( 1cos )) (3.8)
M d t2 = 2 Fv Mg
-16-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
sin (3.10)
cos 1 (3.11)
By considering (3.10) and (3.11), (3.5), (3.8) and (3.9) are rewritten as:
M(a+d) = 2 FH (3.12)
Mg = 2Fv (3.13)
= k I (3.16)
di (3.17)
V = Ri + L dt + Ve
V = RI + Ve (3.18)
-17-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Ve = Ke (3.19)
where Ke is the back-EMF constant and is the shaft angular velocity. By considering (3.16),
(3.17), (3.18) and (3.19), one has:
R (3.20)
Ke
V K +
Due to difference of angular velocity in ground coordinate and the angular velocity which is
measured by encoder, one has:
(3.21)
e=
r
d (3.22)
e
= + dt
e
In (3.21) and (3.22), is the angular velocity which is measured by encoder. By substituting
-18-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
d
dt ]
Mgd = 0
Now, tilt angle, and displacement, x can be calculated as shown in equation (3.27) and (3.28).
[ J s + Md (r + d)]a (3.27)
= 2J dt
[ + 2rm+(r +d )M ]a
r
(3.28)
Mgd [J s + Md ( r+ d) a]
x = 2J
+2rm+(r +d )M
r
-19-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
CHAPTER 4
EXPERIMENTS
Many experiments were carried out before coming up with a working prototype which
suits our purpose. Depending on feasibility and success, some of them are implemented on the
final prototype, while others are not.
-20-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
calculate and give euler angles i.e., pitch, roll and yaw as its output in a standard format, taking
input from accelerometer, gyroscope and magnetometer present onboard. A special hardware
called UART, piece of hardware that translates data between parallel and serial forms, present on
both sides of the communications enables the transfer of data from IMU to Arduino. The
continuous feedback of tilt angles is used to run a PID algorithm in Atmega328, which in turn
actuates the motor.
Discussion:
The earths gravity is a constant acceleration where the force is always pointing down to
the center of the earth. When the accelerometer is parallel with the gravity, the measured
acceleration will be 1G, when the accelerometer is perpendicular with the gravity, it will measure
0G. Unfortunately, this theory can be applied when the robot is completely static. When robot is
moving, there will be other components of acceleration acting on the robot and causing the
calculated tilt angle to be inaccurate.
It is challenging to design, test and integrate low-cost inertial sensors into a powerful
IMU for navigation uses. More considerations for system design and sensor fusion algorithms
need to be addressed to achieve autonomous navigations missions. The sensor fusion problem is
defined as making an optimal estimation of the required vehicle states with the direct
measurement from multiple sensors. There are possible solutions to this problem such as Kalman
filters or complimentary filters. The orientation is not directly measurable and has to be
estimated from a set of correlated states. Therefore, the estimation accuracy of IMUs heavily
relies on the sensor fusion algorithm. These algorithms may have high demands for
computational power, which is not possible for low-cost IMUs.
Accelerometer lets us measure the forces caused by turning, accelerating or braking, but
the measurements wont be accurate unless the vehicle is level relative to the earth during these
maneuvers. If the vehicle tilts forward, we will get gravity components measured by the
accelerometer we use to measure the braking force. Most tilt sensors sense the direction of
gravity as a reference direction. Braking, accelerating and turning a vehicle produce
accelerations on the vehicle. In a tilt measurement, we want to measure gravitational acceleration
only. In a measurement of a vehicles dynamics, we want to measure motional acceleration only.
-21-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
A tilt sensor (uncompensated) will give inaccurate angle measurements when subjected to
motion acceleration. An accelerometer will give inaccurate acceleration measurements when the
vehicle tilts.
Angular rate sensors can help correct for the effect of the forward tilt by measuring
rotations around the center of gravity of the vehicle. Unfortunately, angular rate measure rotation
rate, not rotation angle; the rotation angle is found by integrating the measured rotation rate over
time. Error in rotation rate will integrate in larger error value. In addition, the random noise in
the rate sensors will produce a random walk effect in the calculated angle. These effects will
limit the usefulness of all but the most expensive angular rate sensors for measurements longer
than a few minutes.
Fortunately, use the rate sensor to measure angle changes on short time scales. Use the
accelerometer like a tilt sensor to calculate the tilt angles, and force the rate sensor derived
angles to slowly match the accelerometer angles over a long time scale. To perform these
measurements, we need sensors, data-acquisition equipment and computational power.
Results:
This IMU could not be used as the data was not reliable in case of dynamic environment.
Its acceleration compensation for the dynamic movements of the setup was not proper due to
limited computing power. Also, its delayed response makes it unsuitable for our purpose. Further,
one of the problems noticed was the continuous shift of reference angle even during its
operation.
L298N Specifications:
-22-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
o Over-temperature protection
But motor was demanding more inrush current at the start than L298N could handle. Also,
due to sudden demand of power at the start, battery voltage goes down. As a result, it shuts down
the whole control circuit and resets it. Hence, we had to go with a higher capacity motor driver.
RIGHT RIGHT
GYROSCOPE MOTOR WHEEL
MICRO
CONTROLLER
MOTOR
DRIVER
BLUETOOTH MODULE
ACCELEROMETER
LEFT LEFT
MOTOR WHEEL
Electrical and Electronics Engineering
JCMCSIIT
-23-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
-24-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
power consumption, high accuracy and repeatability, high shock tolerance, and application
specific performance programmability all at a low consumer price point.
The MPU-6050 shown in figure 5.2 is the worlds first integrated 6-axis Motion Tracking
device that combines a 3-axis gyroscope, 3-axis accelerometer, and a Digital Motion Processor
(DMP) all in a small 4x4x0.9mm package. With its dedicated I2C sensor bus, it directly accepts
inputs from an external 3-axis compass to provide a complete 9-axis Motion Fusion output. The
MPU-6050 Motion Tracking device, with its 6-axis integration, on-board Motion Fusion, and
run-time calibration firmware, enables manufacturers to eliminate the costly and complex
selection, qualification, and system level integration of discrete devices, guaranteeing optimal
motion performance for consumers. The MPU-6050 is also designed to interface with multiple
non-inertial digital sensors, such as pressure sensors, on its auxiliary I2C port. The MPU-6050 is
footprint compatible with the MPU-30X0 family.
The MPU-6050 features three 16-bit analog-to-digital converters (ADCs) for digitizing
the gyroscope outputs and three 16-bit ADCs for digitizing the accelerometer outputs. For
precision tracking of both fast and slow motions, the parts feature a user-programmable
gyroscope full-scale range of 250, 500, 1000, and 2000/sec (dps) and a user-programmable
accelerometer full-scale range of 2g, 4g, 8g, and 16g.
An on-chip 1024 Byte FIFO buffer helps lower system power consumption by allowing
the system processor to read the sensor data in bursts and then enter a low-power mode as the
MPU collects more data. With all the necessary on-chip processing and sensor components
required to support many motion-based use cases, the MPU-6050 uniquely enables low-power
Motion Interface applications in portable applications with reduced processing requirements for
the system processor. By providing an integrated Motion Fusion output, the DMP in the MPU-
6050 offloads the intensive Motion Processing computation requirements from the system
processor, minimizing the need for frequent polling of the motion sensor output.
Communication with all registers of the device is performed using either I2C at 400kHz
or SPI at 1MHz (MPU-6000 only). For applications requiring faster communications, the sensor
and interrupt registers may be read using SPI at 20MHz (MPU-6000 only). Additional features
include an embedded temperature sensor and an on-chip oscillator with 1% variation over the
operating temperature range.
-25-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Features:
Gyroscope Features:
The triple-axis MEMS gyroscope in the MPU-6050 includes a wide range of features:
Digital-output X-, Y-, and Z-Axis angular rate sensors (gyroscopes) with a user-
programmable full-scale range of 250, 500, 1000, and 2000/sec
External sync signal connected to the FSYNC pin supports image, video and GPS
synchronization
Integrated 16-bit ADCs enable simultaneous sampling of gyros
Enhanced bias and sensitivity temperature stability reduces the need for user calibration
Improved low-frequency noise performance
Digitally-programmable low-pass filter
Gyroscope operating current: 3.6mA
Standby current: 5A
Factory calibrated sensitivity scale factor
User self-test
Accelerometer Features:
The triple-axis MEMS accelerometer in MPU-6050 includes a wide range of features:
Digital-output triple-axis accelerometer with a programmable full scale range of 2g,
4g, 8g and 16g
-26-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Applications:
Handset and portable gaming
Motion-based game controllers
Wearable sensors for health, fitness and sports
Toys
-27-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
purpose microprocessors (such as those used in PCs). Basically, the use of a microcontroller is in
the processing of data from one of your peripherals, with the set of output data. For example,
send data via serial port or generate a reaction in system as an LED light.
Microcontrollers are typically used in automation and control products and peripherals,
such as control systems of automotive engines, remote controls, machines, etc.
AT Mega-328 is an 8-bit microcontroller with low power CMOS technology and RISC
architecture. It has the ability to execute one instruction per clock cycle due to direct connection
of its 32 general registers with an arithmetic logic unit and frequency of operation in a range
from 0 to 16 MHz. Moreover, although RISC has a large number of instructions, which allows
better optimization of high-level code in C.AT Mega 328 pin out is shown in figure 5.3
-28-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
The AtmelAVR core combines a rich instruction set with 32 general purpose working
registers. All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU),
allowing two independent registers to be accessed in one single instruction executed in one clock
cycle. The resulting architecture is more code efficient while achieving up to ten times faster
than conventional CISC microcontrollers.
The device is manufactured using Atmels high density non-volatile memory technology.
The Flash Program memory can be reprogrammed in system through an SPI serial interface, by a
conventional non-volatile memory programmer, or by an On-chip boot program running on the
AVR core. The boot program can use any interface to download the application program in the
Application Flash memory. Software in the Boot Flash Section will continue to run while the
Application Flash Section is updated, providing true Read-While-Write operation. By combining
an 8-bit RISC CPU with In-System Self-Programmable Flash on a monolithic chip, the Atmel
ATmega8 is a powerful microcontroller that provides a highly flexible and cost effective solution
to many embedded control applications.
Features:
o High-performance, Low-power AtmelAVR 8-bit Microcontroller
-29-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
o 512Bytes EPROM
o Peripheral Features
o One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode
-30-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
o Five Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, and Standby
o Operating Voltages
o Speed Grades
o 0 - 16MHz (ATmega8)
-31-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
o Active: 3.6mA
-32-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
-33-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Features:
o Operating supply voltage up to 46 v
o Total dc current up to 4A
o Low saturation voltage
o Over temperature protection
o High noise immunity
-34-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Specifications:
1. Hardware features:
Typical -80dBm sensitivity
Up to +4dBm RF transmit power
Low Power 1.8V Operation ,1.8 to 3.6V I/O
UART interface with programmable baud rate
-35-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
2. Software features:
Default Baud rate: 38400, Data bits:8, Stop bit:1,
Parity: No parity
Data control has supported baud rate: 9600,19200,38400,57600,115200,230400,460800.
Permit pairing device to connect as default.
5.3. Working
Two wheeled balancing robot is an unstable dynamic system. Unstable means that robot
is free to fall forward or backward without any applied forces. The word balance means the robot
is in equilibrium state, which its position is like standing upright 90 degrees. However, the
system itself is not balance, which means it keeps falling off, away from the vertical axis.
Therefore, a combination of gyroscope and accelerometer is needed to sense angle position of
the robot and input into the microcontroller, which implements the balancing procedure to Self-
-36-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Balancing Robot stabilize the robot. The microcontroller will then provide a type of feedback
signal to the H-bridge circuit to turn the motor clockwise or anticlockwise. If tilt is in forward
direction, wheels are moved in forward direction and vice versa, thus balancing the robot.
IMU consists of accelerometer and gyroscope. The job of the IMU is to quickly and
accurately report the angle of your robot. The angle is used to decide to move your robot
forward or backward in an attempt to keep it upright. This tiny board combines a gyroscope with
an accelerometer with a convenient Arduino library.
The IMU is installed so that the front of the robot points in the positive z direction.
When the robot tilts forward, it corresponds to a positive rotation about the x-axis and a
Electrical and Electronics Engineering
JCMCSIIT
-37-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
downward (negative) acceleration of the z-axis. The tilt angle can be determined based on a
combination of the accelerometer and gyroscope readings. The accelerometer readings return the
linear acceleration for each of the three axis. Axis defined when tilted by an angle is shown in
figure 5.8.
As the robot tilts forward by an angle of , gravity exerts a force on the y and z aspects of
the accelerometer. After projecting the force of gravity along those axes, we can express the z-
axis acceleration Az is shown in equation 5.1.
For angles, less than 30 degrees (our intended control range for the robot), the angle in
radians can be approximated within 1% or less by using the sine of the angle as a close
approximation of the actual angle is shown in equation 5.2.
-38-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
The tilt angle from the accelerometer is a point-in-time measurement and is not constant
over any period of time.
As the robot tilts forward by an angle of over a period of time, it acquires an angular
velocity. The angular velocity is measured by a gyroscope as the number of radians per second
and is often designated . In this implementation leaning forward will be designated as a
positive tilt angle. Using the right-hand rule, the above example will have a positive angular
velocity. In order to make an angle determination, a time element must be considered in
conjunction with the angular velocity the value must be integrated.
-39-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Control loop of robot is shown in figure 5.9 and steps shown in figure 5.10. The inputs to
control loop are target angle and feedback signal, current angle. The error will be computed and
given to PID controller to give output to motors so as to reduce error.
In this project, we will also design a HC-05 Bluetooth based Android Mobile controlled robot
with AVR ATmega 328 microcontroller. Here, we will use the Android Mobile as the input
device to drive the robot in different direction.
The communication between HC-05 Bluetooth Module and Android Mobile takes place
through wireless Bluetooth technology. And the communication between HC-05 Bluetooth
Module and AT mega 328 microcontroller takes place through UART serial communication
protocol. The HC-05 Bluetooth Module and Android Mobile are connected through Bluetooth.
User enters the control signal from the connected Android Mobile through Bluetooth Terminal
App and the Android Mobile transmits the control signal to the HC-05 Bluetooth Module
through its Bluetooth. The HC-05 Bluetooth Module receives the control signal and transmits it
to the ATmega microcontroller through UART.
-40-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
The ATmega microcontroller receives the control signal and processes it and sends the
required control signal to the DC Motor Driver (L298N) of the robot to drive the robot in the
desired direction. Now, we can press different keys from the Android Mobile and drive your
robot as you want.
Process is a controlled object. The purpose of control is to make the output y (PV)
followed r set point (set point-SP). To do this, the controller will get the error between output
signal and input signal and then through the stages of control to make control signals
accordingly, to minimize this error. A proportional controller (K p) will have the effect of reducing
the rise time and will reduce, but never eliminate, the steady-state error. An integral control (Ki)
will have the effect of eliminating the steady-state error, but it may make the transient response
worse. A derivative control (Kd) will have the effect of increasing the stability of the system,
reducing the overshoot, and improving the transient response
-41-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
(5.4)
Where Iout is the integral of output, Ki is Gain of the integral, e is error = SP-PV, t is
current time. The contribution from the integral term is proportional to both the magnitude of the
error and the duration of the error. Summing the instantaneous error over time (integrating the
error) gives the accumulated offset that should have been corrected previously. The accumulated
error is then multiplied by the integral gain and added to the controller output.
-42-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Integral control in PID controller increase process to output close SP value and eliminate
setting error of proportional control. However, Integral control added up all bias in stages before,
so it is cause of overshoot. The integral term (when added to the proportional term) accelerates
the movement of the process towards set point and eliminates the residual steady-state error that
occurs with a proportional only controller. However, since the integral term is responding to
accumulated errors from the past, it can cause the present value to overshoot the set point value.
5.4.3. Derivative control
Derivative control will determine the rate of change of error given by equation 5.5.
(5.5)
Where Dout is the derivative of output, Kd is Gain of
the derivative, e is error = SP-PV, t is current time. Derivative control is used to reduce the
magnitude of the overshoot produced by the integral component and improve the combined
controller-process stability. The derivative term slows the rate of change of the controller output
and this effect is most noticeable close to the controller set point. Hence, derivative control is
used to reduce the magnitude of the overshoot produced by the integral component and improve
the combined controller-process stability. Response of Derivative control is shown in figure 5.13.
-43-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
-44-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
-45-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
kd NT Decrease Decrease NT
Table 5.2: Effects of increasing each of the controller parameters kp, ki and kd
Android devices are powerful mobile computers and they become more and more popular
smart phones used worldwide. They become more and more popular for software developers
because of its powerful capabilities and open architecture, also its based on the java
programming language. For the communication of the robot with the cell phone or a mobile we
are using the Bluetooth device. The Bluetooth device (HC-05) is attached to the robot that
receives the data from the mobile and also can transmit data. Figure 5.14 shows the circuit
diagram of self balancing robot.
Figure 5.15 shows the circuit diagram of self balancing robot. 7805 regulator used to get 5-volt
output to drive the circuit. Capacitor used to filter out ripples. 16 MHz crystal oscillator
connected to pins XTAL1 and XTAL2 of Atmega 8. Enable pins of motor driver (EN) used for
PWM to control speed of motor and motor driver connection is shown in figure 5.14. OUT 1 and
Electrical and Electronics Engineering
JCMCSIIT
-46-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
OUT 2 of the motor driver is used to drive the motor 1 and OUT 3 and OUT 4 of the motor
driver is used to drive the motor2. Program is written to micro controller through MAX32. MPU
6050 is connected to ADC pins.
-47-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
CHAPTER 6
PROJECT IMPLEMENTATION
6.1. Phases
Phase 1:
-48-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
We have learned about embedded system, then introduction to Arduino microcontroller and next
we have done basic programming in Arduino microcontroller and interfacing with Arduino
microcontroller and studied about inertial sensors in this phase. Finally, we completed our
literature review.
Phase 2:
We did our hardware part of the project in this phase. Interfacing of motors through drivers,
MPU 6050 (which contains inbuilt gyroscope and accelerometer) to the microcontroller were
studied and obtained. After that we did hardware design i.e., chassis design which is built in three
layer. In the top most layer we placed load and Bluetooth module HC 05. In the second layer we
placed designed PCB board and in the third layer we placed motor driver.
Phase 3:
We have done software part of the project in this phase. Programming is done in
Arduino Software (Integrated development environment). PID controlling is done using
programming where present error is depending on proportional term (P), past error obtained by
integrating all the past errors using Integral term (I) and future error depends on rate of change of
present error obtained using Derivative term (D). So, combination of all these error gives us the
required error to be compensated.
Phase 4:
In this phase, we assembled our robot and made the final prototype. We have done hardware
connection between sensors, motors and Atmega 328. For this we have done PCB circuit design
and then finally using soldering we connected the circuits between various components.
-49-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
COMPONENT PRICE
1x ATmega-328 Rs. 500
2x USB Cable Rs. 800
2x Gear Motor Rs. 500
2x Wheel and Chassis Rs. 600
1x L293D Rs. 800
MPU 6050 Rs. 1000
Adapter Rs. 500
Jumper wires Rs. 400
Blue tooth module (HC 05) Rs. 500
ESTIMATED PRICE Rs. 5600
CHAPTER 7
RESULTS
In our project by gradually tuning the PID coefficients, we were able to improve the
stability of the system. It turns out that the robot is most stable for settings with very low D
Electrical and Electronics Engineering
JCMCSIIT
-50-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
coefficients in PID, so our controller is effectively PI. To find the reason why this is the case will
require a deeper analysis. After a lot of trial and error, we successfully got our robot to balance.
If the gyroscope is properly calibrated, the tilt is zeroed, and the robot is placed gently in an
upright position, it stays upright despite disturbances that would normally make it fall over. It is
even able to carry a significant load and remain perfectly balanced:
In our demo, the robot balanced before we turned it off. On a surface with high resistance, like
carpets, the robot is able to balance more steadily than it does on hard surfaces like floors. We
also noticed that raising the center of gravity improves the stability of the robot. So to prove this
we put the load at the very top.
While the robot performed at least as well, if not better, than we expected, we did notice a
few limitations that affected its performance. For example, regardless of how the PID
coefficients are tuned, the robot always exhibits a minor wobble. We think this is due to the
motors having a minimum PWM duty cycle threshold below which they do not move. That can
possibly be compensated for in software to improve stability.
Second of all, while we supplied exactly the same power to both of the wheels
simultaneously, one wheel tends to spin noticeably faster than the other at low speeds. This
causes the robot to move in somewhat of an arc. The difference seems less noticeable at higher
speeds. The robot still balances, so we did not spend too much time looking into this issue.
A third issue has to do with a design choice that we made. Due to budget limitations, we
decided to not add motor encoders to our robot. Encoders are not inherently necessary for self-
balancing, but they would have allowed us to directly measure and control the speed of the robot.
When testing our robot, we noticed that, for various reasons, it sometimes begins to accumulate
speed. It remains balanced until it reaches a point where the motor speed saturates, the wheels
cannot keep up with the body of the robot, and it falls over. Having faster motors could have
helped, but the issue here is the lack of encoders. With encoders, we could have prevented the
robot from approaching speeds that it cannot handle, and even controlled the robot such that it
stayed in place rather than roaming around with no speed control
-51-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Kp Ki Kd
50 300 4
Table 7.1: PID constants
By using trial and error method we finally obtained PID constants as shown in table 7.1. The
project model is shown in figure 7.1.
-52-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
CHAPTER 8
-53-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
REDUCES LOW
GLOBAL CARBON
WARMING EMISSIONS
NO FUEL AVOIDS
CONSUMPTION TRAFFIC
HELPS IN
MULTITASKING
Figure 8.1: Advantage loop
8.2. Disadvantages
-54-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
2. Does not exactly say how far the system will go with objects of different masses.
-55-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
CHAPTER 9
APPLICATIONS
o It is used for carrying load.
o It can be used in such a way to move forward or backward.
o They can be used as vehicles by humans.
o The current day short distance usage vehicles can be substituted by them.
o It can be used for surveillance purpose.
CHAPTER 10
Electrical and Electronics Engineering
JCMCSIIT
-56-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
10.1 Evaluation
-57-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
We came into this project expecting to build a two-wheeled robot that would balance
itself with the help of an IMU. It took a good amount of work, and we encountered significant
challenges, but we met our expectations and achieved our goal. After building the chassis,
designing and testing the circuits, writing the software, and tuning the PID coefficients, we were
able to successfully balance the robot on the two wheels, and even carry a load. But it is still not
perfect the few issues detailed above, including the minor wobble, the asymmetrical motor
speeds, and the lack of encoders are small problems that can be fixed in a future update.
The key to completing this project was careful advance planning of every step we needed to
make, and every material we need to buy. We spent what at first seemed like an excessive
amount of time planning, but it all paid off in the end, because we were able to more effectively
manage our time, and were more prepared for the problems we would encounter.
-58-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
microcontroller that would indicate that a low voltage measurement has been established. This
would call upon a return to charge station procedure which would ensure the robot returns
safely before power is lost to its systems.
To better transverse uneven terrain such as stairs, the wheels could be enhanced to allow
an upward and/or downward extension to its height. This could either apply a force in the
direction of travel onto the obstacle to push itself up or it could raise the wheel over the obstacle
itself. This would allow the robot to travel upstairs or over obstacles whilst maintaining balance.
An outer skin may be incorporated for cosmetic and well as shielding effect for the robot.
A skin that allows the IR sensors to easily see through would be ideal, allowing a smooth
covering of the outer side. This would also be protective against dust, water and other forms of
intrusion into the sensitive circuits within. A cushion belt could be added to the bumper switch
arrangement to allow a softer collision in the event one may occur.
10.4. Future Improvements
o Fix the wobble by setting a minimum PWM duty cycle that is just below the threshold at
which the motors begin to spin. That will get rid of the current dead spot in which the
motors don't spin for a number of degrees.
o Fix the asymmetry in the motor speeds. That likely has to do with friction, so using
machine oil to lubricate one or both of the motors might fix the problem.
o Add encoders to the robot to allow it to measure and control its speed. That will prevent it
from approaching its maximum speed and falling over.
o Implement automatic tilt calibration so that the robot will always remain balanced even if
its centre of gravity is shifted, requiring no action by the user.
o Add a light sensing system to the bottom of the robot and make it autonomously follow a
dark path drawn on the ground.
-59-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
During the course of final project, we made decisions consistent with safety such that
nobody was in danger of getting injured. We are honest and realistic in stating our claims
according to data collected. We are accurate in listing our component cost to our best knowledge.
We are willing to accept constructive feedback and incorporate it into our design. We strove to
solve challenging problems by ourselves, and sought the help of the instructor and TAs for those
we were not able to resolve. We did not hold any bias against anyone nor engaged in acts of
discrimination based on race, religion, gender, disability, age, national origin, sexual orientation,
and gender identity. We treated all of our peers with equal respect and offered help to our
colleagues whenever possible. We give credit when using the code from any external sources to
prevent any perceived conflicts of interests, and acknowledge all contributions made to the final
project.
-60-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
CHAPTER 11
REFERENCES
1 Nguyen Gia Minh Tao, Duong Hoai, A PID Controller for Two-Wheeled Self-Balancing
Robot, IEEE, 13 December 2010
3 Bernhard Mahler, Jan Haase, Mathematical model and control strategy of two wheeled
self balancing robot, IEEE, 06 January 2014
APPENDIX A
ARDUINO
-61-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
This is very commonly used electronic platform for quick results without investing much time
and effort. Loads of tutorials are available online for getting started with this board, including
tutorials on coding language, hardware setup and procedure to burn the code onto the Arduino.
We can find all this information online from Arduino.cc which is quite easy to understand and
extensive. Hence, we will not be explaining them here.
Main Arduino Code:
Changing the set point for the PID controller individually for two motors can control the
translational motion of the robot. If we change one while keeping the other constant, the robot
will go into rotational motion as well. Higher the difference between the set point for it to
vertically balance and actual set point, faster will the translational motion be.
#define version_0.66
#define BLUE
#include <I2Cdev.h>
#include <Wire.h>
#include <MPU6050_6Axis_MotionApps20.h>
#include <helper_3dmath.h>
#include <PID_v1.h>
#include <digitalIOPerformance.h>
#define DIGITALIO_NO_INTERRUPT_SAFETY
#define DIGITALIO_NO_MIX_ANALOGWRITE
#include<SoftwareSerial.h>
-62-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
MPU6050 mpu;
Quaternion q;
VectorFloat gravity;
float ypr[3];
#define ROTATION_KP 50
#define ROTATION_KI 300
#define ROTATION_KD 4
#define MOTOR_A_PWM 9
Electrical and Electronics Engineering
JCMCSIIT
-63-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
#define MOTOR_A_DIR 5
#define MOTOR_A_BRAKE 10
#define MOTOR_B_DIR 8
#define MOTOR_B_BRAKE 7
#define MOTOR_B_PWM 11
// Motor Misc
#define PWM_MIN 0
#define PWM_MAX 255
float MOTORSLACK_A=32;
float MOTORSLACK_B=39;
#define MOTOR_A_PWM_MAX 255
#define MOTOR_B_PWM_MAX 255
double yaw,input,out,setpoint,originalSetpoint,Buffer[3];
double yinput,yout,ysetpoint,yoriginalSetpoint;
//uint32_t timer,timer1;
double bal_kp,bal_ki,bal_kd,rot_kp,rot_ki,rot_kd;
//int addressFloat=0;
PID pid(&input,&out,&setpoint,BALANCE_KP,BALANCE_KI,BALANCE_KD,DIRECT);
PID
rot(&yinput,&yout,&ysetpoint,ROTATION_KP,ROTATION_KI,ROTATION_KD,DIRECT);
-64-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
//String d;
void setup()
{
#ifdef DEBUGING
Serial.begin(9600);
#endif
#ifdef BLUE
blue.begin(9600);
blue.setTimeout(10);
#endif
init_imu();
initmot();
pid.SetMode(AUTOMATIC);
pid.SetOutputLimits(-210, 210);
pid.SetSampleTime(10);
rot.SetMode(AUTOMATIC);
rot.SetOutputLimits(-20, 20);
rot.SetSampleTime(10);
setpoint = 0;
originalSetpoint = setpoint;
ysetpoint = 0;
yoriginalSetpoint = ysetpoint;
bal_kp=BALANCE_KP;
-65-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
bal_ki=BALANCE_KI;
bal_kd=BALANCE_KD;
rot_kp=ROTATION_KP;
rot_ki=ROTATION_KI;
rot_kd=ROTATION_KD;
void loop()
{
getvalues();
new_pid();
#ifdef BLUE
Bt_control();
#endif
#ifdef DEBUGING
printval();
#endif
void init_imu()
{
Electrical and Electronics Engineering
JCMCSIIT
-66-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Wire.begin();
mpu.initialize();
devStatus = mpu.dmpInitialize();
mpu.setXGyroOffset(-88);
mpu.setYGyroOffset(-54);
mpu.setZGyroOffset(17);
mpu.setXAccelOffset(-6537);
mpu.setYAccelOffset(77);
mpu.setZAccelOffset(1216);
if (devStatus == 0) {
mpu.setDMPEnabled(true);
attachInterrupt(0, dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
dmpReady = true;
packetSize = mpu.dmpGetFIFOPacketSize();
}
}
void getvalues()
{
if (!dmpReady) return;
-67-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
fifoCount = mpu.getFIFOCount();
mpu.resetFIFO();
} else if (mpuIntStatus & 0x02) {
}
yinput = ypr[0]* 180/M_PI;
input = -ypr[1] * 180/M_PI;
}
void printval()
{
Serial.print(yinput);Serial.print("\t");
Serial.print(yoriginalSetpoint); Serial.print("\t");
Serial.print(ysetpoint); Serial.print("\t");
Serial.print(yout); Serial.print("\t");Serial.print("\t");
Serial.print(input);Serial.print("\t");
Serial.print(originalSetpoint); Serial.print("\t");
Serial.print(setpoint); Serial.print("\t");
Serial.print(out); Serial.print("\t");Serial.print("\t");
Serial.print(MotorAspeed); Serial.print("\t");
Electrical and Electronics Engineering
JCMCSIIT
-68-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
Serial.print(MotorBspeed); Serial.println("\t");
void Bt_control()
{
if(blue.available())
{
content=blue.readString();
if(content[0]=='F')
setpoint = originalSetpoint - d_speed;
else if(content[0]=='B')
setpoint = originalSetpoint + d_speed;
else if(content[0]=='L')
ysetpoint = constrain((ysetpoint + yoriginalSetpoint - d_dir),-180,180);
else if(content[0]=='R')
ysetpoint = constrain(ysetpoint + yoriginalSetpoint + d_dir,-180,180);
else if(content[0]=='S')
d_speed = (content.substring(2)).toInt();
else if(content[0]=='D')
d_dir = content.substring(2).toInt();
else if(content[0]=='P')
{
if(content[1]=='S')
{
// if(content[2]=='B')
// //save_pid(1);
// else
// //save_pid(0);
} else if(content[1]=='C')
Electrical and Electronics Engineering
JCMCSIIT
-69-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
{
if(content[2]=='B')
{
change_pid(1);
}
else
change_pid(0);
}
}
if(content=="updateb")
return_pid(1);
else if(content=="updater")
return_pid(0);
}
}
void return_pid(bool b)
{
char charVal[10];
String sent = "";
if(b)
{
sent.concat("OP");dtostrf(bal_kp, 5, 3, charVal);sent.concat(charVal);
sent.concat("OI");dtostrf(bal_ki, 5, 3, charVal);sent.concat(charVal);
sent.concat("OD");dtostrf(bal_kd, 5, 3, charVal);sent.concat(charVal);
sent.concat("e");
}
else
{
Electrical and Electronics Engineering
JCMCSIIT
-70-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
sent.concat("OP");dtostrf(rot_kp, 5, 3, charVal);sent.concat(charVal);
sent.concat("OI");dtostrf(rot_ki, 5, 3, charVal);sent.concat(charVal);
sent.concat("OD");dtostrf(rot_kd, 5, 3, charVal);sent.concat(charVal);
sent.concat("e");Serial.println(sent);
}
blue.print(sent);
}
void change_pid(bool b)
{
blue.print("O");
while(!blue.available());
for(int i=0;i<3;i++)
{
Buffer[i]=blue.parseFloat();
}
if(b)
{
bal_kp=Buffer[0];bal_ki=Buffer[1];bal_kd=Buffer[2];
}
else
{
rot_kp=Buffer[0];rot_ki=Buffer[1];rot_kd=Buffer[2];
}
}
-71-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
{
if (Output >= 0)
Output = Output + MOTORSLACK_A - yOutput;
if (Output < 0)
Output = Output - MOTORSLACK_A - yOutput;
}
else
{
if (Output >= 0)
Output = Output + MOTORSLACK_B + yOutput;
if (Output < 0)
Output = Output - MOTORSLACK_B + yOutput;
}
Output = constrain(Output, BALANCE_PID_MIN, BALANCE_PID_MAX);
return Output;
}
void new_pid()
{
//Compute error
pid.Compute();
rot.Compute();
MotorAspeed = compensate_slack(yout,out,1);
MotorBspeed = compensate_slack(yout,out,0);
motorspeed(MotorAspeed, MotorBspeed); //change speed
}
void initmot()
{
Electrical and Electronics Engineering
JCMCSIIT
-72-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
pinMode(MOTOR_A_DIR, OUTPUT);
pinMode(MOTOR_A_BRAKE, OUTPUT);
pinMode(MOTOR_B_DIR, OUTPUT);
pinMode(MOTOR_B_BRAKE, OUTPUT);
analogWrite(MOTOR_A_PWM, 0);
analogWrite(MOTOR_B_PWM, 0);
}
analogWrite(MOTOR_A_PWM,abs(MotorAspeed));
// Motor B control
if (MotorBspeed >= 0)
{
digitalWrite(MOTOR_B_DIR,HIGH);
digitalWrite(MOTOR_B_BRAKE,LOW);
}
else
{
Electrical and Electronics Engineering
JCMCSIIT
-73-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT
digitalWrite(MOTOR_B_DIR,LOW);
digitalWrite(MOTOR_B_BRAKE,HIGH);
}
analogWrite(MOTOR_B_PWM, abs(MotorBspeed));
}
-74-