Вы находитесь на странице: 1из 83

PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-

BALANCING AUTONOMOUS ROBOT

PROJECT REPORT

Submitted in partial fulfillment of the requirement for the award of degree


Bachelor of Technology in Electrical & Electronics Engineering of the University
of Kerala
By
ABHIJITH B. (13423001)
JOEL S. (13423014)
SARATH JAISON MEDAVILA (13423022)

DEPARTMENT OF ELECTRICAL AND ELECTRONICS


ENGINEERING

JOHN COX MEMORIAL CSI INSTITUTE OF TECHNOLOGY


KANNAMMOOLA, THIRUVANANTHAPURAM 695011, KERALA

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.

PROJECT CO-ORDINATOR GUIDED BY


Mr. Lim J. Seelan Mr. B. P. Beno Ben
Assistant professor Assistant professor
Dept. of EEE Dept. of EEE

Mrs. J. Sheeba Jeba Malar


Head of the Department
Electrical and Electronics Engineering
JCMCSIIT, KANNAMMOOLA
ACKNOWLEDGEMENT

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.

LIST OF FIGURES iii


LIST OF TABLES iv
LIST OF ABBREVIATIONS v
1 INTRODUCTION 1
1.1 Motivation 2
1.2 Scope 2
1.3 Objective 3
1.4 Limitation 3
2 LITERATURE REVIEW 4
2.1 Segway 6
2.2 Honda U3-X 8
2.3 Toyota Winglet 8
2.4 NXT Segway with Rider 9
2.5 JOE-A Mobile Inverted Pendulum 11
3 METHODOLOGY 12
3.1 Study Area 12
3.2 Equilibrium 12
3.3 Assumptions 14
3.4 Dynamic Model 14
3.5 Control model 17
4 EXPERIMENTS 20
4.1 Inertial Measurement Unit 20
4.2 Motor Driver 22
5 PROJECT DESCRIPTION 23
5.1 Materials Used 24
5.1.1 MPU 6050 24
5.1.2 Micro controller AT Mega-328 27
5.1.3 DC Geared Motor 30
5.1.4 DC Motor Driver 31
5.1.5 HC-05 Bluetooth Module 33
5.2 I2C Interface 35
5.3 Working 35
5.4 PID Controller 39

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

Figure No. Title Page No.


2.1 NXT Segway with Rider 10
3.1 Stable and Unstable Equilibrium of the free pendulum pivot about a frictionless point 13
3.2 Dynamic model parameters 14
3.3 Free body diagram of wheels 15
5.1 Block diagram of self balancing robot 23
5.2 MPU 6050 26
5.3 Micro Controller AT Mega 328 pin out 28
5.4 DC Gear Motor 31
5.5 L298N Motor driver 32
5.6 HC 05 Bluetooth Module 34
5.7 Robot Model 36
5.8 Axis defined when tilted by an angle 37
5.9 Control loop of robot 38
5.1 Diagram showing steps involved in feedback control of robot 38
0
5.11 Response of Proportional control 40
5.1 Response of Integral control 41
2
5.1 Response of Derivative control 42
3
5.1 Motor driver connection 46
4
5.1 Circuit Diagram 46
5
7.1 Project Model 51
8.1 Advantage loop 52

iii

LIST OF TABLES
Table No. Title Page No.

5.1 Absolute Maximum Ratings 33


5.2 Effects of increasing each of the controller parameters kp, ki and kd 44
6.1 Cost Estimation table 48
7.1 PID constants 50

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

Electrical and Electronics Engineering


JCMCSIIT

-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.

Electrical and Electronics Engineering


JCMCSIIT

-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.

Electrical and Electronics Engineering


JCMCSIIT

-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

Electrical and Electronics Engineering


JCMCSIIT

-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 Segway onboard charger uses a standard 110V/220V AC cord

o It applies a maximum torque of 2-hp to keep the rider upright

o It can climb a 30-degree grade

o It comes equipped with a 64-bit encrypted magnetic key to prevent theft.

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.

Electrical and Electronics Engineering


JCMCSIIT

-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

2.2. Honda U3-X


The Honda U3-X is a self-balancing one-wheeled electric vehicle similar to Segway PT.
Honda developed the U3-X with technology originally developed for ASIMO, the bipedal human
project. Honda states that the U stands for unicycle and for universal.

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:

o Dimension: Length - 313 mm, Width - 160 mm, Height - 647 mm

o Weight: ~10 Kg (22lbs)

o Top Speed: 6 km/h

o Drive System: Honda Omni Traction (HOT) Drive System

o Battery Type: Lithium-Ion battery

o Operation Time: ~1 hour

2.2. Toyota Winglet

Electrical and Electronics Engineering


JCMCSIIT

-8-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Toyota Motor Corporation announced the development of Winglet, a personal transport


assistance robot ridden in a standing position, self-balancing through gyroscopic sensors
detecting the gentle directional tilts of a rider. Designed to contribute to society by helping
people enjoy a safe and fully mobile life, the Winglet is a compact next generation everyday
transport tool that offers advanced ease of use and expands the users range of mobility.

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.

Toyota Winglet enters production priced at $3,500.

Specifications (L Model):

o Dimension: Length - 265 mm, Width - 464 mm, Height - 1130 mm

o Weight: 12.3 kg

o Maximum Cruising Speed: 6 km/h

o Turning Radius: 0

o Cruising Range: 10 km

o Charging Time: 1 h (full charge)

2.4. NXT Segway with Rider


This robot simulates a Segway, which is a two-wheeled self-balancing vehicle that a rider
stands on. By using the NXT color sensor as a simple proximity sensor to the ground, measuring
the reflected light, which will change slightly depending on how close the sensor is to the
ground, detecting the approximate tilt angle of the robot, the robot can actually balance itself.
Electrical and Electronics Engineering
JCMCSIIT

-9-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 2.1: NXT Segway with Rider

Its underlying issues are as follows:

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

Electrical and Electronics Engineering


JCMCSIIT

-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.

2.5. JOE A Mobile Inverted Pendulum


The Industrial Electronics laboratory at the Swiss Federal Institute of Technology (EPFL) in
Lausanne has built a prototype of a revolutionary two-wheeled vehicle. Due to its configuration
with two coaxial wheels, each of which is coupled to a DC motor, the vehicle is able to do
stationary U-turns. A control system, made up of two decoupled state space controllers, pilots the
motors so as to keep the system in equilibrium.

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.

Electrical and Electronics Engineering


JCMCSIIT

-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.

3.1. Study Area


Our area of study will be primarily Control Theory. It is an interdisciplinary branch of
engineering and mathematics that deals with the behavior of dynamical systems. The external
input of a system is called reference. When one or more output variables of a system need to
follow a certain reference over time, a controller manipulates the inputs to a system to obtain the
desired effect on the output of the system.

Our system is a practical application of a common control system experimental setup,


known as Inverted Pendulum. While a pendulum is normally stable handing downwards, a
pendulum upside-down is inherently unstable and needs a continuous external force to keep it in
an upright position. Every pendulum setup has two equilibrium points Stable and Unstable
Equilibrium. As the setup demands, we are required to continuously take the tilt feedback and
provide an external force to keep the system balanced about its unstable equilibrium. There are
various control algorithms that can be implemented in order to achieve the same. However, we
will be using most commonly used algorithm, PID (Proportional Integral Differential).

Electrical and Electronics Engineering


JCMCSIIT

-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.

Electrical and Electronics Engineering


JCMCSIIT

-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

3.4. Dynamics Model

Electrical and Electronics Engineering


JCMCSIIT

-14-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 3.2: Dynamic model parameters

Figure 3.3: Free body diagram of wheels

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:

Electrical and Electronics Engineering


JCMCSIIT

-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

For y-axis, (3.3), (3.4) and (3.5) can be rewritten as:

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

By considering Js as the proposed robot rotational moment of inertia, one has:

Electrical and Electronics Engineering


JCMCSIIT

-16-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Js = -2( + FHLcos - FVdsin) (3.9)

Due to the balance angle in = 0, two assumptions can be regarded as:

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)

Js = -2( + FHL Fvd) (3.14)

Now, by substituting (3.1), (3.12) into (3.2), one has:


J rM rMd (3.15)
= a [ r + rm + 2 ] + [ 2 ]

3.5 Control Model


By considering as motor torque and k as torque constant, one has:

= k I (3.16)

di (3.17)
V = Ri + L dt + Ve

In (3.17), R is nominal terminal resistance, L is rotor inductance and Ve is back electromotive


force (EMF) voltage. Equation (3.17) can be written as (3.18) because the electrical actions of
motors are faster than mechanical action:

V = RI + Ve (3.18)

Electrical and Electronics Engineering


JCMCSIIT

-17-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

The back EMF voltage in (3.17) is:

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

(3.22) into (3.21), one has:


d (3.23)
= r + dt

Now, by substituting (3.23) in (3.20), one has:


(3.24)
R d
r
V= KT + Ke
+ dt ]

By substituting (3.15) from dynamics model section in (3.23), one has:


(3.25)
R Ja (rMa +rMda)
r
V= K +[ r + rma + 2 ]a + Ke
+

Electrical and Electronics Engineering


JCMCSIIT

-18-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

d
dt ]

Now, by substituting (3.12), (3.13) and (3.15) in (3.14), one has:


2J (3.26)
Js
[ + Md(r+d)] + [ r + 2rm + (r+d)M] -

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

Electrical and Electronics Engineering


JCMCSIIT

-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.

4.1. Inertial Measurement Unit


An Inertial Measurement Unit, or IMU, is an electronic device to measure the relative
states of a static or mobile unit with respect to the inertial reference frame. It measures and
reports on a crafts velocity, acceleration, and gravitational forces, using a combination of
accelerometers, gyroscopes and magnetometers. IMUs are typically used to maneuver aircraft,
including unmanned aerial vehicles (UAVs), among many others, and spacecraft, including
shuttles, satellites and landers. IMU has an onboard processor, Atmega 328, the output can be
modified as desired by changing its firmware. Procedure to modify its firmware is exactly same
as that of Arduino, an electronic open source prototypic platform. Hence, it was modified to
Electrical and Electronics Engineering
JCMCSIIT

-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.

Electrical and Electronics Engineering


JCMCSIIT

-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.

4.2. Motor Driver


We were initially using a standard motor driver used very commonly in all the basic
robotics applications. It was L298N.

L298N Specifications:

o Dual Full Bridge Driver

o Operating supply voltage upto 46V

Electrical and Electronics Engineering


JCMCSIIT

-22-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

o Total DC current upto 4A

o Low Saturation voltage

o Over-temperature protection

o Logical 0 input voltage upto 1.5V (high noise immunity)

o Current sensing capability

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.

POWER SUPPLY CHAPTER 5


PROJECT DESCRIPTION
Block Diagram of self balancing robot is shown in figure 5.1. It consists of MPU 6050, micro
controller AT Mega 328, L298N motor driver and DC gear motor.

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

Figure 5.1: Block diagram of self balancing robot

5.1. Materials Used

5.1.1 MPU 6050


Overview:
Motion Interface is becoming a must-have function being adopted by smartphone and
tablet manufacturers due to the enormous value it adds to the end user experience. In smart
phones, it finds use in applications such as gesture commands for applications and phone control,
enhanced gaming, augmented reality, panoramic photo capture and viewing, and pedestrian and
vehicle navigation. With its ability to precisely and accurately track user motions, Motion
Tracking technology can convert handsets and tablets into powerful 3D intelligent devices that
can be used in applications ranging from health and fitness monitoring to location-based
services. Key requirements for Motion Interface enabled devices are small package size, low

Electrical and Electronics Engineering


JCMCSIIT

-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.

Electrical and Electronics Engineering


JCMCSIIT

-25-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

By leveraging its patented and volume-proven Nasiri-Fabrication platform, which


integrates MEMS wafers with companion CMOS electronics through wafer-level bonding,
InvenSense has driven the MPU-6050 package size down to a revolutionary footprint of
4x4x0.9mm (QFN), while providing the highest performance, lowest noise, and the lowest cost
semiconductor packaging required for handheld consumer electronic devices. The part features a
robust 10,000g shock tolerance, and has programmable low-pass filters for the gyroscopes,
accelerometers, and the on-chip temperature sensor.
For power supply flexibility, the MPU-6050 operates from VDD power supply voltage
range of 2.375V-3.46V. Additionally, the MPU-6050 provides a VLOGIC reference pin (in
addition to its analog supply pin: VDD), which sets the logic levels of its I2C interface. The
VLOGIC voltage may be 1.8V5% or VDD.

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

Electrical and Electronics Engineering


JCMCSIIT

-26-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Integrated 16-bit ADCs enable simultaneous sampling of accelerometers while requiring


no external multiplexer
Accelerometer normal operating current: 500A
Low power accelerometer mode current: 10A at 1.25Hz, 20A at 5Hz, 60A at 20Hz,
110A at 40Hz
Orientation detection and signaling
Tap detection
User-programmable interrupts

Figure 5.2: MPU 6050

Applications:
Handset and portable gaming
Motion-based game controllers
Wearable sensors for health, fitness and sports
Toys

5.1.2. Micro Controller AT Mega 328


In the area of control and automation, the need for some processing unit became
indispensable in a wide variety of applications. Among these, microcontrollers stand as a lower
cost alternative, satisfactory reliability, simplicity, reduced consumption energy, however, with
limited memory capacity and processing.

A microcontroller contains a processor, memory access and peripheral input / output. It is


a microprocessor that can be programmed for specific functions, in contrast to other general
Electrical and Electronics Engineering
JCMCSIIT

-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.

The architecture of a microcontroller generally consists of a core processing, bus and


Peripherals:
Processing core consists of the data processor (calculations, flow control program, etc.)
and administration of peripherals.
Bus is divided into data and address, is on the lines of communication between the
processor and peripherals.
Peripherals characterize the set of features available by the microcontroller and are
controlled by the processor. For example, memory, serial port, parallel port and AD
converter.

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

Electrical and Electronics Engineering


JCMCSIIT

-28-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 5.3: Micro Controller AT Mega 328 pin out

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

Electrical and Electronics Engineering


JCMCSIIT

-29-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

o Advanced RISC Architecture

o 130 Powerful Instructions Most Single-clock Cycle Execution

o 32 8 General Purpose Working Registers

o Fully Static Operation

o Up to 16MIPS Throughput at 16MHz

o On-chip 2-cycle Multiplier

o High Endurance Non-volatile Memory segments

o 8Kbytes of In-System Self-Programmable Flash program memory

o 512Bytes EPROM

o 1Kbyte Internal SRAM

o Data retention: 20 years at 85C/100 years at 25C

o Optional Boot Code Section with Independent Lock Bits

o In-System Programming by On-chip Boot Program

o True Read-While-Write Operation

o Programming Lock for Software Security

o Peripheral Features

o Two 8-bit Timer/Counters with Separate Prescaler, one Compare Mode

o One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode

o Real Time Counter with Separate Oscillator

o Three PWM Channels

Electrical and Electronics Engineering


JCMCSIIT

-30-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

o Eight Channels 10-bit Accuracy

o 6-channel ADC in PDIP package

o Six Channels 10-bit Accuracy

o Byte-oriented Two-wire Serial Interface

o Programmable Serial USART

o Master/Slave SPI Serial Interface

o Programmable Watchdog Timer with Separate On-chip Oscillator

o On-chip Analog Comparator

o Special Microcontroller Features

o Power-on Reset and Programmable Brown-out Detection

o Internal Calibrated RC Oscillator

o External and Internal Interrupt Sources

o Five Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, and Standby

o I/O and Packages

o 23 Programmable I/O Lines

o Operating Voltages

o 4.5V - 5.5V (ATmega8)

o Speed Grades

o 0 - 16MHz (ATmega8)

o Power Consumption at 4 MHz, 3V, 25C

Electrical and Electronics Engineering


JCMCSIIT

-31-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

o Active: 3.6mA

o Idle Mode: 1.0mA

o Power-down Mode: 0.5A

5.1.3. DC Gear Motor


DC motor (BO) Battery Operation converts electrical energy into mechanical energy is
shown in figure 5.4.DC motor concept is where gears reduce the speed of the vehicle but
increase its torque is known as gear reduction. In DC motor is assembled with multiple gear
setup. Speed of motor is counted in terms of RPM. RPM means Revolution per Minute. The
setup assembles helps to increasing the torque and reduces the motor speed. All micro-
controller based Robots use this type of DC motor. The speed of motor is counted in terms of
rotations of the shaft per minute and is termed as RPM. The gear assembly helps in increasing
the torque and dropping the speed. Using the correct arrangement of gears in a gear motor, its
speed can be reduced to any required figure. This concept of reducing the speed with the help of
gears and increasing the torque is known as gear reduction. Reducing the speed put out by the
motor while increasing the quantity of applied torque is an important feature of the reduction
gear trains found in a gear motor. The decrease in speed is inversely relative to the increase in
torque. DC Geared motors with robust metal gear box for heavy duty applications, available in
wide RPM range and ideally suited for robotics and industrial applications. It is very easy to use
and available in standard size. Nut and threads are used on shaft to easily connect and internal
threaded shaft used for easily connecting it to wheel.

Electrical and Electronics Engineering


JCMCSIIT

-32-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 5.4: DC Gear Motor


Specifications:
Weight: 100gm
RPM: 60 TO 400
Voltage: 2 DC to 12 VDC
Shaft diameter: 6mm
Torque: 2 Kg-cm
No-load current: 70mA (Max)

5.1.4. DC Motor Driver


Description:
The L298N motor driver shown in figure 5.5 is an integrated monolithic circuit in a 15
lead Multi watt and PowerSO20 packages. It is a high voltage, high current dual full-bridge
driver designed to accept standard TTL logic levels and drive inductive loads such as relays,
solenoids, DC and stepping motors. Two enable inputs are provided to enable or disable the
device independently of the input signals. The emitters of the lower transistors of each bridge are
connected together and the corresponding external terminal can be used for the connection of an
external sensing resistor. An additional supply input is provided so that the logic works at a lower
voltage. In Arduino, the analog Write function allows you to generate a PWM wave in a pin. If
we have tried out the LED fade example in Arduino, then we already know how to use it. If not,
then checkout the PWM tutorial from Arduino reference. This function takes a value between 0
and 255 and doesnt work on all pins in Arduino. In Arduino Uno, it works on pins 3, 5, 6, 9, 10
and 11 for controlling speed of DC Motors. To control the speed of the motor, all we need to do
is to replace digital Write function on L298N enable pins to analog Write. The speed of the motor
depends on value that was passed to the analog Write function. Remember the value can be
between 0 and 255. If we pass 0, then the motor will stop and if you pass 255 then it will run at
full speed. If we pass a value between 1 and 254, then the speed of the motor will vary
accordingly. We connect the enable pins of H Bridge to PWM pins. PWM motor output
calculation functions. Absolute maximum ratings of driver is shown in table 5.1.

Electrical and Electronics Engineering


JCMCSIIT

-33-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 5.5: L298N Motor driver

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

Symbol Parameter Value Unit


VS Power Supply 50 V
VSS Logic Supply Voltage 7 V
VI,Ven Input and Enable Voltage 0.3 to 7 V
IO Peak Output Current (each Channel)
Non Repetitive (t = 100ms) 3 A
Repetitive (80% on 20% off; ton = 10ms) 2.5 A
DC Operation 2 A

Electrical and Electronics Engineering


JCMCSIIT

-34-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Vsens Sensing Voltage 1 to 2.3 V


Ptot Total Power Dissipation (Tcase = 75C) 25 W
Top Junction Operating Temperature 25 to 130 C
Tstg, Tj Storage and Junction Temperature 40 to 150 C
Table 5.1: Absolute maximum ratings

5.1.5. HC-05 Bluetooth module:


HC-05 module shown in figure 5.6 is an easy to use Bluetooth SPP (Serial Port Protocol)
module, designed for transparent wireless serial connection setup. Serial port Bluetooth module
is fully qualified Bluetooth V2.0+EDR (Enhanced Data Rate) 3Mbps Modulation with complete
2.4GHz radio transceiver and baseband. It uses CSR Bluecore 04-External single chip Bluetooth
system with CMOS technology and with AFH (Adaptive Frequency Hopping Feature). It has the
footprint as small as 12.7mmx27mm.

Figure 5.6: HC 05 Bluetooth Module

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

Electrical and Electronics Engineering


JCMCSIIT

-35-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

With integrated antenna


With edge connector

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.2. I2C Interface


Inter-integrated Circuit (IC pronounced I- Squared- C) is a 2 wire serial bus generally used to
communicate with sensors and other small accessories. The 2 lines of the I2C bus are SDA
(acknowledge) and SLC (clock) which can be run in parallel to communicate with a couple of
instruments at once. I2C enables up to 112 "slave" (similar to a sensor) contraptions to be
controlled by a single "master" (such as Arduino, in our case). Every slave device on the bus
ought to have it is own special deal with so the master can keep up a correspondence
immediately with the supposed device. This enables more than one of the same device to be on
the same bus without conflicting addresses.
I2C basic command sequence.
1. Send the start bit (S).
2. Send the slave address with (ADDR).
3. Send the read(R)-1 / Write(W)-0 bit.
4. Wait up for/send an acknowledge bit (A).
5. Send//Receive the data byte (eight bits) (information).
6. Expect/send acknowledge bit (A).
7. Send the STOP bit (P).

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-

Electrical and Electronics Engineering


JCMCSIIT

-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.

Much of the internal workings of an IMU implementation depend on the physical


installation and orientation of the hardware. The following diagram in figure 5.7 shows how it is
installed.

Figure 5.7: Robot Model

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.

Figure 5.8: Axis defined when tilted by an angle

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.

Sin () = Az/g (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.

Electrical and Electronics Engineering


JCMCSIIT

-38-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

(t) = Az/g (for a point in time from the accelerometer) (5.2)

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.

Figure 5.9: Control loop of robot

Electrical and Electronics Engineering


JCMCSIIT

-39-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 5.10: Diagram showing steps involved in feedback control of 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.

Electrical and Electronics Engineering


JCMCSIIT

-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.

5.4. PID Controller

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

5.4.1. Proportional control


Proportional control generates the changes of output and the equation is given by 5.3.
This change is proportional to the bias current value. Response of Proportional control shown in
figure 5.11 can be adjusted multiplying the difference signal with Kp.

Pout = Kpe(t) (5.3)

Where Kp is Gain, e is error = SP-PV, t is current time

Electrical and Electronics Engineering


JCMCSIIT

-41-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 5.11: Response of Proportional control


With larger Kp value is easy to adjust error. However, the system lost stability. K p is too small
then the system will react very slowly with the input error. A high proportional gain results in a
large change in the output for a given change in the error. If the proportional gain is too high, the
system can become unstable. In contrast, a small gain results in a small output response to a large
input error, and a less responsive (or sensitive) controller. If the proportional gain is too low, the
control action may be too small when responding to system disturbances.
5.4.2. Integral control
The value adjusted at Integral control is proportional with bias in a period of time and the
equation is given by 5.4. It is total of bias. This signal is then multiplied by the integral gain Ki
and taken to adjust output. Response of Integral control is shown in figure 5.12.

(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.

Electrical and Electronics Engineering


JCMCSIIT

-42-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 5.12: Response of Integral control

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.

Electrical and Electronics Engineering


JCMCSIIT

-43-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 5.13: Response of Derivative control


A proportionalintegralderivative controller is a control loop feedback mechanism
widely used in industrial control systems. A PID is the most commonly used feedback controller.
A PID controller calculates an "error" value as the difference between a measured process
variable and a desired set point. The controller attempts to minimize the error by adjusting the
process control inputs. Its calculation involves three separate parameters, and is accordingly
sometimes called three-term control: the proportional, the integral and derivative values, denoted
P, I, and D.P depends on the present error, I on the accumulation of past errors, and D is a
prediction of future errors, based on current rate of change. The weighted sum of these three
actions is used to adjust the process variable. By tuning the three constants in the PID controller
algorithm, the controller can provide control action designed for specific process requirements.
This section describes the parallel or non-interacting form of the PID controller.
Output= Pout + Iout + Dout (5.6)
Where, Pout, Iout, and Dout are the contributions to the output from the PID controller from each of
the three terms and output is given by equation 5.6.
Tuning parameters are:
Proportional gain, Kp:
Larger values typically mean faster response since the larger the error, the larger the
proportional term compensation. An excessively large proportional gain will lead to process
instability and oscillation.

Electrical and Electronics Engineering


JCMCSIIT

-44-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Integral gain, Ki:


Larger values imply steady state errors are eliminated more quickly. The trade-off is
larger overshoot: any negative error integrated during transient response must be integrated away
by positive error before reaching steady state.
Derivative gain, Kd:
Larger values decrease overshoot, but slow down transient response and may lead to
instability due to signal noise amplification in the differentiation of the error.
5.5. Stability
If the PID controller parameters (the gains of the proportional, integral and derivative
terms) are chosen incorrectly, the controlled process input can be unstable, i.e. its output
diverges. Instability is caused by excess gain. So, for stability, gain must not be too large.
Generally, stability of response is required and the process must not oscillate for any
combination of process conditions and set points, though sometimes marginal stability (bounded
oscillation) is acceptable or desired. Problem faced with PID controllers is that they are linear,
and in particular symmetric. Thus, performance of PID controllers in non-linear systems is
variable. In this case the PID should be tuned to be over damped, to prevent or reduce overshoot.

5.6. PID Controller Tuning:


PID parameters affect the system dynamics and table 5.2 shows the effects of increasing each of
the controller parameters kp, ki and kd. We are most interested in four major characteristics of
the closed loop step response. They are
o Rise Time: The time it takes for the plant output to rise beyond 90% of the desired level
for the first time
o Overshoot: It the difference between the peak level and the steady state
o Settling Time: The time it takes for the system to converge to its steady state
o Steady State Error: The difference between the steady-state output and desired output

Response Rise Time Overshoot Settling Time S-S Error

kp Decrease Increase NT Decrease

ki Decrease Increase Increase Eliminate


Electrical and Electronics Engineering
JCMCSIIT

-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

Where NT means No definite Tread or Minor change.


Steps for designing a PID controller are:
o Determine what characteristics of the system needs to be improved
o Use kp to decrease the rise time
o Use kd to reduce the overshoot and settling time
o Use ki to eliminate the steady-state error
Here are the steps which adopted to get Kp, Ki and Kd faster:
o Set I and D term to 0, and adjust P so that the robot starts to oscillate (move back and
forth) about the balance position. P should be large enough for the robot to move but not
too large otherwise the movement would not be smooth.
o With P set, increase I so that the robot accelerates faster when off balance. With P and I
properly tuned, the robot should be able to self-balance for at least a few seconds.
o Finally, increase D so that the robot would move about its balanced position gentler, and
there shouldnt be any significant overshoots
5.7. Android Platform:

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.

Figure 5.14: Motor driver connection

Electrical and Electronics Engineering


JCMCSIIT

-47-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 5.15: Circuit Diagram

CHAPTER 6

PROJECT IMPLEMENTATION

6.1. Phases

Phase 1:

Electrical and Electronics Engineering


JCMCSIIT

-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.

Electrical and Electronics Engineering


JCMCSIIT

-49-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

6.2. Cost Estimation

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

Table 6.1: Cost Estimation table


Cost estimation is shown in table 6.1 and estimated price is about 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

Electrical and Electronics Engineering


JCMCSIIT

-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.

Electrical and Electronics Engineering


JCMCSIIT

-52-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

Figure 7.1: Project Model

CHAPTER 8

Electrical and Electronics Engineering


JCMCSIIT

-53-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

ADVANTAGES AND DIS ADVANTAGES


8.1. Advantages

1. Reduces time for travelling foot distance.


2. A clean, green, eco-friendly machine. (zero emission)
3. Require less space for riding, parking.
4. Become more productive: more work can be done by using the product versus walking.
5. Become more recognizable: Riders stand an additional eight inches off the ground,
allowing you to be better seen and giving the rider better sight lines, over cars in a
parking lot or boxes in a warehouse.
6. Low operating costs: no need for gas and inexpensive battery charging (A complete cycle
charge will take eight to ten hours)

REDUCES LOW
GLOBAL CARBON
WARMING EMISSIONS

NO FUEL AVOIDS
CONSUMPTION TRAFFIC

HELPS IN
MULTITASKING
Figure 8.1: Advantage loop
8.2. Disadvantages

Electrical and Electronics Engineering


JCMCSIIT

-54-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

1. If system becomes unstable, it may fall.

2. Does not exactly say how far the system will go with objects of different masses.

Electrical and Electronics Engineering


JCMCSIIT

-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

CONCLUSION AND FUTURE SCOPE


A self balancing robot was designed and manufactured as desired with limited resources
possible. It was able to balance smoothly with a maximum tilt error of 5 degrees. Range of
payload and its height for which it balances was quantified. Maximum angle of tilt for balancing
was also determined through various experiments. However, there are some limitations. Such
technology is suitable only for flat ground. In order to make it work on slant surface, the angle of
slant needs to be fed into the system, either manually or using some intelligence. Project can
further be extended to make a full scale personalized mobile vehicle for common people,
especially physically challenged. Further, such robots in higher quantity can be made to work in
coordination and realize a collective effort. This can also be developed as a surveillance body
and made to send back informative signals back to base station from remote areas which are
partially or completely inaccessible. This report studies the balancing of a system in only one
direction i.e., pitch. Such theory can also be extended to balance in multiple axis i.e., pitch and
roll and is under research. Any practical implementation may not be easy and requires
continuous effort and improvement. In order to get a prototype working of similar nature, one is
required to have a good knowledge in manufacturing, product design, basic electronics, PCB
design, basic programming language like C, C++ or Java, and debugging skills. Latest
manufacturing technologies may not be available which may pose some problems and may lead
to a compromise on designs. Many concepts are generally not included in theory and come into
picture only when it comes to implementation stage. Something working may not work in all
conditions and will have constraints, similar to sensor sensitivity, which keeps changing in
accordance to ambient lighting conditions. Also, its a good practice to perform any activity or
experiment in best manner possible and not implement any temporary solution which might end
up taking more time in debugging the unknown errors. In this implementation, because we have
non-zero integral constant in PID controller, system does not start balancing the moment it is
switched on, but takes some time before the integral error goes to zero.

10.1 Evaluation

Electrical and Electronics Engineering


JCMCSIIT

-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.

10.2. Improvements and Alterations


Improvements to the current version of the robot can easily be achieved through the
microcontrollers programming. This would provide the fundamental benefits faster control
responses, effective and efficient computations and improved overall system performance.
Completing the software implementation of the interaction system would allow the operator to
have video and audio streaming capabilities, locomotion control and microcontroller
reprogramming capability. Although the hardware would not require any significant change, the
completion of visual basic programs would complete the process.

10.3. Additional Features and Capabilities


Additional feature or capabilities that may improve the effectiveness, efficiency or
operability of the robot include the addition of arms. This would allow the robot to interact with
its surrounds thus providing a larger impact on the operability it may now achieve. This could be
further extended to include grippers at the end of each arm that would be capable of effectively
lifting large masses or obscure shapes. The number of arms fitted would increase the complexity
of the control systems in place but the enhanced capability may be beneficial.
Although not fully explorer, the webcam vision could be expanded to incorporate stereo
vision. This would allow the robot to autonomously navigate, identify and avoid obstacles
through the added vision capability. The voltage monitoring circuit could provide a signal to the
Electrical and Electronics Engineering
JCMCSIIT

-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 Implement manual remote steering of the robot, commanding it to rotate clockwise or


counter-clockwise.

o Add a light sensing system to the bottom of the robot and make it autonomously follow a
dark path drawn on the ground.

Electrical and Electronics Engineering


JCMCSIIT

-59-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

10.5. Ethical Considerations

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.

Electrical and Electronics Engineering


JCMCSIIT

-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

2 Osama Jamil, Mohsin Jamil , Modeling, control of a two-wheeled self-balancing robot,


IEEE, 12 June 2014

3 Bernhard Mahler, Jan Haase, Mathematical model and control strategy of two wheeled
self balancing robot, IEEE, 06 January 2014

4 Yulei GONG, Xiao WU, Research on Control Strategy of Two-wheeled Self-Balancing


Robot, IEEE, 07 January 2016

5 Nguyen, A PID Back stepping Controller for Two-Wheeled Self-Balancing Robot,


IEEE, 06 January 2014

6 M. H. Khan, M. Chaudhry, T. Tariq q, Fabrication and modeling of segway, IEEE, 28


August 2014

APPENDIX A
ARDUINO

Electrical and Electronics Engineering


JCMCSIIT

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

const int rxpin = 3;


const int txpin = 6;

SoftwareSerial blue(rxpin, txpin);


#define RESTRICT_PITCH

Electrical and Electronics Engineering


JCMCSIIT

-62-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

MPU6050 mpu;

bool dmpReady = true;


uint8_t mpuIntStatus;
uint8_t devStatus;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];

Quaternion q;
VectorFloat gravity;
float ypr[3];

volatile bool mpuInterrupt = false;


void dmpDataReady() {
mpuInterrupt = true;
}

#define BALANCE_KP 15//15


#define BALANCE_KI 90//90
#define BALANCE_KD 0.8//0.8
#define BALANCE_PID_MIN -255
#define BALANCE_PID_MAX 255

#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

int MotorAspeed, MotorBspeed, MotorSlack,moveState=0,d_speed,d_dir;

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);

String content = "";


char character;
Electrical and Electronics Engineering
JCMCSIIT

-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;

Electrical and Electronics Engineering


JCMCSIIT

-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;

pid.SetTunings(bal_kp,bal_ki,bal_kd); //change PID values


rot.SetTunings(rot_kp,rot_ki,rot_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;

while (!mpuInterrupt && fifoCount < packetSize) {


}
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();

Electrical and Electronics Engineering


JCMCSIIT

-67-
PID CONTROLLERS ON A DESIGNED TWO-WHEELED SELF-BALANCING AUTONOMOUS ROBOT

fifoCount = mpu.getFIFOCount();

if ((mpuIntStatus & 0x10) || fifoCount == 1024) {

mpu.resetFIFO();
} else if (mpuIntStatus & 0x02) {

while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();


mpu.getFIFOBytes(fifoBuffer, packetSize);
fifoCount -= packetSize;
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

}
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];
}
}

double compensate_slack(double yOutput,double Output,bool A)


{
if(A)
Electrical and Electronics Engineering
JCMCSIIT

-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);
}

void motorspeed(int MotorAspeed, int MotorBspeed) {


// Motor A control
if (MotorAspeed >= 0)
{
digitalWrite(MOTOR_A_DIR,HIGH);
digitalWrite(MOTOR_A_BRAKE,LOW);
}
else
{
digitalWrite(MOTOR_A_DIR,LOW);
digitalWrite(MOTOR_A_BRAKE,HIGH);
}

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));
}

Electrical and Electronics Engineering


JCMCSIIT

-74-

Вам также может понравиться