Professional Documents
Culture Documents
Pid Based Self-Balancing Robot
Pid Based Self-Balancing 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 customer’s 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
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.
It’s quite difficult to hold a pen in your hand and balance it. But to do the same thing with
a broom in your hand, it’s relatively simple. The reason is that there is more time to compensate.
For that reason, it’s 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
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 being’s 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.
CHAPTER 2
LITERATURE REVIEW
Hau-Shiue Juang, et al (2013), Author in his research paper “Design and control of a two-wheel
self-balancing robot using the arduino microcontroller board” have discussed about design,
construction and control of a two-wheel self-balancing robot. The system architecture comprises
a pair of DC motor and an Arduino microcontroller board; a single-axis gyroscope and a 2-axis
accelerometer are employed for attitude determination. In addition, a complementary filter is
implemented to compensate for gyro drifts. Electrical and kinematic parameters are determined
experimentally; PID and LQR-based PI-PD control designs, respectively, are performed on the
linearized equations of motion. Experimental results show that self-balancing can be achieved
with PI-PD control in the vicinity of the upright position.
Frank L. Lewis, et al (1999), Author in his research paper “Hybrid Control for a Class of
Underactuated Mechanical Systems” have discussed about stabilizing hybrid scheme to control a
class of underactuated mechanical systems. The hybrid controller consists of a collection of state
feedback controllers plus a discrete-event supervisor. When the continuous-state hits a switching
boundary, a new controller is applied to the plant. Lyapunov theory is used to determine the
switching boundaries and to guarantee the stability of the closed-loop hybrid system. This
approach is applied to the well-known swing up and balancing control problem of the inverted
pendulum.
Joshua Gafford, et al (2012), Author in his article “Modeling, Simulation and Fabrication of a
Balancing Robot” said that we had to perform a hardware design of the balancing robot,
including any rationale behind component selection. We will then give a derivation of the
equations of motion using a Lagrangian approach, and investigate the effect of center-of-mass
position on the closed-loop dynamics of the system. In addition, we will discuss controllability
and observability of the system and derive a fullstate feedback control based on the Linear
Quadratic Regulator (LQR) method. Finally we will derive a two-state discrete Kalman filter for
smoothing out sensor/process noise, and simulate the entire system in Simulink. We will close
with some discussion on the actual response of the physical balancing robot, outfitted with full-
state control and Kalman filter.
Eldhose P. Kunnel, et al (2018), The article is about “Controlling of two wheeled self balancing
robot using PID”. According to this article Self balancing robot is essentially an inverted
pendulum. It can balance better if centre of mass is higher relative to the wheel axels. A higher
centre of mass means a higher moment of inertia which means a lower angular acceleration. It
act as a robot which can balance by itself. The experiment requires Arduino, MPU6050 board,
L293D driver module. Balancing of the robot can be done with help of feedback and a correction
element. Feedback element is the MPU6050 board which tells the Arduino about current
orientation of the robot. Experiment mainly uses PID controller, having gains Kp, Kiand Kd. PID
provides correction between desired value and actual value. The difference between input and
output is called error. The PID controller reduces the error to smallest value possible by adjusting
theoutput. MU6050 reads the current tilt of robot and feeds it to the PID algorithm, which
performs calculations to control motor and keep the robot in upright position.
Nguyen Gia Minh Thao, et al (2010), Write a paper “ A PID backstepping controller for two
wheeled self balancing robot”. This paper 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 modelling and PID backstepping controller design. In the system, signals
from angle sensors are filtered by a discrete Kalman filter before being fed to the PID
backstepping 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 backstepping
controller has three control loops, in which the first loop uses a backstepping 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, stability .
Rich Chi Ooi, et al (2003), In his thesis on the topic “ Balancing a two wheeled autonomous
robot” discusses the processes developed and considerations involved in balancing a two-
wheeled autonomous robot based on the inverted pendulum model. The instability of inverted
pendulum systems has always been an excellent test bed for control theory experimentation.
Therefore it is also the aim of this thesis to investigate the suitability and examine the
performance of linear control systems like the Linear Quadratic Regulator and Pole-placement
controller in stabilising the system.
Siddhesh Bhagat, et al (2018), Author have discussed in their research article about “Self
Balancing Robot”. Author writes, In last few decades, the open source community has expanded
to make it possible for people to build complex product at home. The most common is the
passively balanceness (i.e. state of stable equilibrium). The main goal of our project is to design
and implement a discrete control system that will provide robotic stability. There has been
varieties of technique to increase the robotic stability on dynamic environments .One such
popular technique used for mobile robots is an inverted pendulum based model. A robot that
implements the inverted pendulum is usually a tower shaped structure, usually standing on two-
wheels and autonomously commanding the motors such that it can keep itself upright while also
travelling guided by the user input .Complementary are implemented which is associated with
the noise of the signal .Thus the purpose of complementary filter if to simplify the noise by
passing it to low pass and high pass filter. We are demonstrating a method which presents the
stability by reading the robots tilt from sensors and computing commands for the motors and is
analysed using different filter coefficients using PID algorithm as the control strategy.
Peter Miller, et al (2008), Author have written an article about “ Building a two wheeled
balancing robot”. According to him two wheeled balancing robots are an area of research that
may well provide the future locomotion for everyday robots. The unique stability control that is
required to keep the robot upright differentiates it from traditional forms of robotics. The
inverted pendulum principle provides the mathematical modelling of the naturally unstable
system. This is then utilised to develop and implement a suitable stability control system that is
responsive, timely and successful in achieving this objective.
Henrik, et al (2015), Author have written an article on “ Two wheeled self balancing robot”.
According to author In the last decade, the open source community has expanded to make it pos-
sible for people to build complex products at home. In this thesis a two- wheeled self-balancing
robot has been designed. These types of robots can be based on the physical problem of an
inverted pendulum . The system in itself requires active control in order to be stable. Using open
source microcontroller Arduino Uno and reliable angular and positional data the system can be
made stable by implementing a controller.A modern and efficient controller is the LQR - Linear
Quadratic Regulator. Being a state space feedback controller the model has to be a good
representation of reality since the output signal depends on the model. In this thesis, the
validation process was performed using a PID-regulator. The results showed that the model is
not yet reliable. The reasons for this are discussed and recommendations for future development
are listed.
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.
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.
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.
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 wheel’s angular acceleration and ‘τ’ as motor
torque, one has equation 3.2:
τ – Ff × r = 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)
d2 xs (3.4)
M = 2 FH
dt2
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:
d2 (x+dsinθ) (3.5)
M = 2 FH
dt2
ys = d×(1-cosθ) (3.6)
d2 y s (3.7)
M = 2 Fv –Mg
dt2
where Fv is the reactionary vertical force. By substituting (3.6) into (3.7), one has (3.8):
d2 (d×(1−cosθ)) (3.8)
M = 2 Fv –Mg
dt2
sinθ ≈ θ (3.10)
cosθ ≈ 1 (3.11)
By considering (3.10) and (3.11), (3.5), (3.8) and (3.9) are rewritten as:
Mg = 2Fv (3.13)
τ = kτ × I (3.16)
di (3.17)
V = Ri + L + Ve
dt
V = R×I + Ve (3.18)
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:
𝑅×τ (3.20)
V≈ + 𝐾𝑒 ω
𝐾τ
Due to difference of angular velocity in ground coordinate and the angular velocity which is
measured by encoder, one has:
ẋ (3.21)
𝜔𝑒 =
𝑟
𝑑θ (3.22)
ω=𝜔𝑒 +
𝑑𝑡
In (3.21) and (3.22),𝜔𝑒 is the angular velocity which is measured by encoder. By substituting
(3.22) into (3.21), one has:
ẋ 𝑑θ (3.23)
ω= +
𝑟 𝑑𝑡
Now, tilt angle, θ and displacement, x can be calculated as shown in equation (3.27) and (3.28).
(3.28)
𝑀𝑔𝑑𝜃−[𝐽𝑠 + Md(r+d)a]
x = ∫∫ 2𝐽
+ 2rm + (r+d)M
𝑟
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.
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 won’t 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 vehicle’s dynamics, we want to measure motional acceleration only.
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.
TB6612FNG Specifications:
In a typical application, power connections are made on one side of the board and control
connections are made on the other.
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 2560, TB6612FNG motor driver and DC gear motor.
POWER SUPPLY
BLUETOOTH MODULE
RIGHT RIGHT
GYROSCOPE
MOTOR WHEEL
MICRO
CONTROLLER
MOTOR
DRIVER
ACCELEROMETER LEFT LEFT
MOTOR WHEEL
The MPU-6050 shown in figure 5.2 is the world’s 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.
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.8V±5% 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: 5μA
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
Integrated 16-bit ADCs enable simultaneous sampling of accelerometers while requiring
no external multiplexer
Accelerometer normal operating current: 500μA
Low power accelerometer mode current: 10μA at 1.25Hz, 20μA at 5Hz, 60μA at 20Hz,
110μA at 40Hz
Orientation detection and signaling
Tap detection
User-programmable interrupts
Power : The Arduino Mega can be powered via the USB connection or with an external power
supply. The power source is selected automatically. External (non-USB) power can come either
from an AC-to-DC adapter (wall-wart) or battery. The adapter can be connected by plugging a
2.1mm center-positive plug into the board's power jack. Leads from a battery can be inserted in
the Gnd and Vin pin headers of the POWER connector. The board can operate on an external
supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than
five volts and the board may be unstable. If using more than 12V, the voltage regulator may
overheat and damage the board. The recommended range is 7 to 12 volts. The Mega2560 differs
from all preceding boards in that it does not use the FTDI USB-toserial driver chip. Instead, it
features the Atmega8U2 programmed as a USB-to-serial converter.
The power pins are as follows:
● VIN. The input voltage to the Arduino board when it's using an external power source (as
opposed to 5 volts from the USB connection or other regulated power source). You can supply
voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.
● 5V. The regulated power supply used to power the microcontroller and other components on
the board. This can come either from VIN via an on-board regulator, or be supplied by USB or
another regulated 5V supply.
● 3V3. A 3.3 volt supply generated by the on-board regulator. Maximum current draw is 50 mA.
● GND. Ground pins.
Input and Output : Each of the 54 digital pins on the Mega can be used as an input or output,
using pin Mode() , digital Write(), and digital Read() functions. They operate at 5 volts. Each pin
can provide or receive a maximum of 40 mA and has an internal pull-up resistor (disconnected
by default) of 20-50 kOhms. In addition, some pins have specialized functions:
● Serial: 0 (RX) and 1 (TX); Serial 1: 19 (RX) and 18 (TX); Serial 2: 17 (RX) and 16 (TX);
Serial 3: 15 (RX) and 14 (TX). Used to receive (RX) and transmit (TX) TTL serial data. Pins 0
and 1 are also connected to the corresponding pins of the ATmega8U2 USB-to-TTL Serial chip.
● External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20
(interrupt 3), and 21 (interrupt 2). These pins can be configured to trigger an interrupt on a low
value, a rising or falling edge, or a change in value. See the attach Interrupt() function for details.
● PWM: 0 to 13. Provide 8-bit PWM output with the analog Write() function.
● SPI: 50 (MISO), 51 (MOSI), 52 (SCK), 53 (SS). These pins support SPI communication using
the SPI library. The SPI pins are also broken out on the ICSP header, which is physically
compatible with the Uno, Duemilanove and Diecimila.
● LED: 13. There is a built-in LED connected to digital pin 13. When the pin is HIGH value,
the LED is on, when the pin is LOW, it's off.
● I2C: 20 (SDA) and 21 (SCL). Support I2C (TWI) communication using the Wire library
(documentation on the Wiring website). Note that these pins are not in the same location as the
I2C pins on the Duemilanove or Diecimila. The Mega2560 has 16 analog inputs, each of which
provide 10 bits of resolution (i.e. 1024 different values). By default they measure from ground to
5 volts, though is it possible to change the upper end of their range using the AREF pin and
analog Reference() function.
There are a couple of other pins on the board:
● AREF. Reference voltage for the analog inputs. Used with analog Reference().
● Reset. Bring this line LOW to reset the microcontroller. Typically used to add a reset button to
shields which block the one on the board.
Communication : The Arduino Mega2560 has a number of facilities for communicating with a
computer, another Arduino, or other microcontrollers. The ATmega2560 provides four hardware
UARTs for TTL (5V) serial communication. An ATmega8U2 on the board channels one of these
over USB and provides a virtual com port to software on the computer (Windows machines will
need a .inf file, but OSX and Linux machines will recognize the board as a COM port
automatically. The Arduino software includes a serial monitor which allows simple textual data
to be sent to and from the board. The RX and TX LEDs on the board will flash when data is
being transmitted via the ATmega8U2 chip and USB connection to the computer (but not for
serial communication on pins 0 and 1). A SoftwareSerial library allows for serial communication
on any of the Mega2560's digital pins. The ATmega2560 also supports I2C (TWI) and SPI
communication. The Arduino software includes a Wire library to simplify use of the I2C bus; see
the documentation on the Wiring website for details. For SPI communication, use the SPI
library.
Physical Characteristics and Shield Compatibility : The maximum length and width of the
Mega2560 PCB are 4 and 2.1 inches respectively, with the USB connector and power jack
extending beyond the former dimension. Three screw holes allow the board to be attached to a
surface or case. Note that the distance between digital pins 7 and 8 is 160 mil (0.16"), not an
even multiple of the 100 mil spacing of the other pins. The Mega2560 is designed to be
compatible with most shields designed for the Uno, Diecimila or Duemilanove. Digital pins 0 to
13 (and the adjacent AREF and GND pins), analog inputs 0 to 5, the power header, and ICSP
header are all in equivalent locations. Further the main UART (serial port) is located on the same
pins (0 and 1), as are external interrupts 0 and 1 (pins 2 and 3 respectively). SPI is available
through the ICSP header on both the Mega2560 and Duemilanove / Diecimila. Please note that
I2C is not located on the same pins on the Mega (20 and 21) as the Duemilanove / Diecimila .
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.
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)
than the BJT-based Hbridges used in older drivers such as the L298N and Sanyo’s LB1836M,
which allows more current to be delivered to the motors and less to be drawn from the logic
supply (the LB1836 still has the TB6612 beat for really low-voltage applications). Our little
breakout board gives you direct access to all of the features of the TB6612FNG and adds power
supply capacitors and reverse battery protection on the motor supply (note: there is no reverse
protection on the Vcc connection).
In a typical application, power connections are made on one side of the board and control
connections are made on the other. All of the control inputs are internally pulled low. Each of the
two motor channels has two direction control pins and a speed control pin that accepts a PWM
input with a frequency of up to 100 kHz. The STBY pin must be driven high to take the driver
out of standby mode.
TB6612 Specifications:
• Recommended motor voltage (VMOT): 4.5 – 13.5 V
• Logic voltage (VCC): 2.7 – 5.5 V
• Output current maximum: 3 A per channel
• Output current continuous: 1 A per channel (can be paralleled to deliver 2 A continuous)
• Maximum PWM frequency: 100 kHz
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
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.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-
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.
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
downward (negative) acceleration of the z-axis. The tilt angle can be determined based on a
combination of the accelerometer and gyroscope readings. The accelerometer readings return the
linear acceleration for each of the three axis. Axis defined when tilted by an angle is shown in
figure 5.8.
As the robot tilts forward by an angle of θ, gravity exerts a force on the y and z aspects of
the accelerometer. After projecting the force of gravity along those axes, we can express the z-
axis acceleration Az is shown in equation 5.1.
For angles, less than 30 degrees (our intended control range for the robot), the angle in
radians can be approximated within 1% or less by using the sine of the angle as a close
approximation of the actual angle is shown in equation 5.2.
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.
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 2560 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.
The ATmega microcontroller receives the control signal and processes it and sends the
required control signal to the DC Motor Driver () 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
kd NT Decrease Decrease NT
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 it’s 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
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.
CHAPTER 6
PROJECT IMPLEMENTATION
6.1. PHASES
Phase 1:
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 2560. For this we have done PCB circuit design
and then finally using soldering we connected the circuits between various components.
COMPONENT PRICE
Battery Rs.130
Cost estimation is shown in table 6.1 and estimated price is about Rs. 3200.
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
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
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.
CHAPTER 8
8.1. ADVANTAGES
LOW
REDUCES
CARB
GLOBAL
WARMING
ON
EMISS
IONS
AVOI
NO FUEL
DS
CONSUMP
TRAF
TION
FIC
HELPS IN
MULTITAS
KING
Figure 8.1: Advantage loop
8.2. DISADVANTAGES
2. Does not exactly say how far the system will go with objects of different masses.
CHAPTER 9
APPLICATIONS
CHAPTER 10
10.1 EVALUATION
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.
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
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.
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.