balancing robot atmega328
TRANSCRIPT
-
8/18/2019 Balancing Robot ATMEGA328
1/52
1
TWO WHEEL BALANCING ROBOT USING
MICROCONTROLLER ATMEGA 328P
A DISSERTATION
Submitted to
Faculty of Engineering and Technology
For the award of degree of
Bachelor of Technology
(Electronics and Communication Engineering)
Supervisor:
Er. INDERPREET SINGH Submitted by:
MITUL TAKIAR
(2011ECA1760)
PRANAV SHARMA
(2011ECA1069)
Department of Electronics TechnologyGuru Nanak Dev University
Amritsar – 143005
India
-
8/18/2019 Balancing Robot ATMEGA328
2/52
2
DECLARATION
We hereby declare that the project work entitled as “TWO WHEEL BALANCING
ROBOT USING MICROCONTROLLER ATMEGA 328P” is an authentic record of our own
work carried out at Guru Nanak Dev University, Amritsar as required for the six months project
semester for the award of degree of B.Tech (Electronics and Communication Engineering), under
the guidance of Er. Inderpreet Singh, during Jan 2014 to April 2014.
Date:
-
8/18/2019 Balancing Robot ATMEGA328
3/52
3
ACKNOWLEDGEMENT
Acknowledgement is not a mere formality but a genuine attempt to remember all those people without
whose cooperation we would not have been able to complete our project.
We want to thank the Department of Electronics Technology, Guru Nanak Dev University, Amritsar
for giving us such a golden opportunity to commence this project in the first instance. We express our
sincere gratitude to Dr. Maninder Lal Singh, Head of the department, Electronics Technology who
helped us turn this opportunity into true results.
We extend our thanks to ”Er. Inderpreet Singh” who encouraged us to go ahead with our project.
Without his able guidance and counsel it would have been impossible for us to complete this project.
We would like to thank GOD, the Almighty, for having made everything possible by giving us strength
and courage to do this work. Lastly, we wish to express our sincere appreciation to our parents for their
patience and encouragement during this work .
-
8/18/2019 Balancing Robot ATMEGA328
4/52
4
ABSTRACT
The project is designed to build a two wheel balancing robotic vehicle using
MPU6050 for its movement. A microcontroller of AVR family is used to achieve the
desired operation.
A robot is a machine that can perform task automatically or with guidance. Robotics
is generally a combination of computational intelligence and physical machines
(motors). Computational intelligence involves the programmed instructions.
The balancing robot platform proved to be an excellent test bed for sensor fusion
using the Kalman filter . An indirect Kalman filter configuration combining a piezo
rate gyroscope sensor and an accelerometer is implemented to obtain an accurate
estimate of the tilt angle and its derivative.
Depending on the input signal received, the microcontroller redirects the robot to
move in an alternate direction by actuating the motors interfaced to it through a motor
driver IC.
-
8/18/2019 Balancing Robot ATMEGA328
5/52
5
TABLE OF CONTENTS
Declaration...................................................................................................................... 02
Acknowledgement............................................................................................................. 03
Abstract ............................................................................................................................ 04
List of figures..................................................................................................................... 07
List of tables ........................................................... ........................................................... 07
1. Introduction ..............................................................................................................08
1.1. Project Description .............................................................................................08
1.2. Applications ........................................................................................................08
2. Literature Review .....................................................................................................09
2.1. Complementary Filter..........................................................................................09
2.2. Kalman Filter............................................................... ........................................11
2.3. PID Controller.............................................................................................. .......14
2.3.1. PID controller theory..............................................................................15
2.3.2. Limitations of PID controller.................................................................17
3. Components Review .................................................................................................19
3.1. ATmega328.........................................................................................................19
3.1.1. Block Diagram........................................................................................20
3.1.2. Pin Diagram............................................................................................21
3.1.3. Features...................................................................................................23
3.2. MPU6050.............................................................................................................24
3.3. Bidirectional level converter................................................................................27
3.3.1. Circuit.....................................................................................................27
3.3.2. Features...................................................................................................27
3.4. L293D......................................................................................................... .........29
3.4.1. Block Diagram........................................................................................29
3.4.2. Pin Diagram............................................................................................30
3.4.3. Features...................................................................................................31
3.4.4. Circuit Diagram......................................................................................31
3.5. LM7805................................................................................................. ...............32
3.5.1. Pin Description........................................................................................32
3.5.2. Circuit......................................................................................................32
3.6. LM317................................................................................................... ...............33
3.6.1. Features....................................................................................................33
-
8/18/2019 Balancing Robot ATMEGA328
6/52
6
3.6.2. Circuit......................................................................................................34
4. Assembling the Robot ................................................................................................35
5. Programming the robot................................................................................................39
6. Testing the robot..........................................................................................................44
6.1. PID Control Unit...................................................................................................44
6.2. Motor Speed Control.............................................................................................45
6.3. Sensor Check.............................................................................................. ..........47
Bibliography ............................................................................................................................52
-
8/18/2019 Balancing Robot ATMEGA328
7/52
7
LIST OF FIGURES
Figure no. Caption Page no.
1. Principle of complementary filter........................................................................................09
2. Kalman Filter in inertial navigation.....................................................................................12
3. PID Controller block diagram.............................................................................................14
4. Plot of PV vs time for three values of K p (Ki and Kd held constant)………………….….16
5. Plot of PV vs time for three values of Ki ( Kp and Kd held constant)…………………....16
6. Plot of PV vs time for three values of Kd ( Ki and Kp held constant)…………………....17
7. ATmega328.........................................................................................................................19
8. ATmega328 block diagram.................................................................................................20
9. ATmega328 pin diagram.....................................................................................................21
10. MPU6050............................................................................................................................2411. Bidirectional level converter...............................................................................................27
12. I2C using MOSFET.............................................................................................................28
13. L293D block diagram..........................................................................................................29
14. L293D pin diagram..............................................................................................................30
15. L293D Circuit diagram.........................................................................................................31
16. LM7805................................................................................................................................32
17. LM7805 Connection diagram...............................................................................................32
18. LM317...................................................................................................................................33
19. LM317 Circuit Diagram.......................................................................................................34
20. Creating a new AVR Studio-4 project..................................................................................39
21. Creating a new AVR Studio-4 project..................................................................................40
22. Building a project with AVR Studio.....................................................................................40
23. Connecting to the programmer with AVR Studio............... ...................... ........................ ....41
24. AVR Studio-4’s programmer selection dialog box..................... .................... ...................... .41
25. Selecting the device for ISP programming.................... ........................ ..................... ...........42
26. Reading the device signature.................................................................................................42
27. AVR Studio’s program ISP tab.............................................................................................43
LIST OF TABLES
Table no. Caption Page no.
1. Comparison among ATmega variants.............................................................................19
2. Pin description of L293D................................................................................................30
3. Pin description of LM7805..............................................................................................32
-
8/18/2019 Balancing Robot ATMEGA328
8/52
8
CHAPTER 1
INTRODUCTION
1.1 Project Description
The research on balancing robot has gained momentum over the last decade in a number of
robotics laboratories around the world. This is due to the inherent unstable dynamics of the
system. Such robots are characterised by the ability to balance on its two wheels and spin on
the spot. This additional manoeuvrability allows easy navigation on various terrains, turn
sharp corners and traverse small steps or curbs. These capabilities have the potential to solve a
number of challenges in industry and society.
A balancing robot is built as a platform to investigate the use of a Kalman filter for sensorfusion. The Kalman filter approach to sensor fusion is unprecedented. This would be a new
avenue to explore the filter for future potential applications of the Kalman filter.
Apart from the above, this thesis will delve into the suitability and performance of linear state
space controllers namely the Linear Quadratic Regulator (LQR) and a Pole placement
controller in balancing the system. The robot utilises a Proportional-Integral- Derivative (PID)
controlled differential steering method for trajectory control. A gyroscope and inclinometer is
used to measure the tilt of the robot and the encoders on the motors to measure the wheel’s
rotation.
1.2 Applications
A motorised wheelchair utilising this technology would give the operator great
manoeuvrability and thus access to places most able-bodied people take for granted.
Climbing up the staircase can be accomplished by using this robot to balance on two
wheels.
Small carts built utilising this technology allows humans to travel short distances in a
small area or factories as opposed to using cars or buggies which is more polluting.
-
8/18/2019 Balancing Robot ATMEGA328
9/52
9
CHAPTER 2
LITERATURE REVIEW
2.1 Complementary Filter
Complementary filters are defined in mathematical terms and in the context of Weiner and Kalman
filters. The derivation of common forms is explored, and it is shown why a Kalman filter is often used
within a complementary filter structure. An example of the design of a complementary filter for a
practical application is presented in detail.
Introduction
The term “complementary filter” is often casually used in the literature to refer to any digital algorithm
that serves to “blend” or “fuse” similar or redundant data from different sensors to achieve a robust
estimate of a single state variable. For example, in aerospace navigation systems, a complementary
filter is often utilized to estimate the position in space of an airframe by combining the high resolution
position information obtained from integrating acceleration and velocity data with the low resolution
position information obtained directly from the GPS satellite network. The data available from an
inertial navigation systems is very good information for a short period of time. However, as integration
errors grow in an unbounded fashion, they can no longer be tolerated. On the other hand, the position
errors associated with GPS data, though quite large, are bounded and well characterized. A
complementary filter combines the excellent high frequency position information derived from the
integration of inertial sensor data with the good lowfrequency position information from GPS data, while rejecting the errors peculiar to each method. The
reader should note that complementary filters are in a class by themselves. While filters in general act
on a signal, the complementary filter does not. It acts only on the different kinds of noise associated
with different kinds of measurements of the same signal. It is a solution waiting for a very special
problem - that of estimating a state variable from data from multiple sources, which exhibit noise with
different frequency content.
Mathematical definition
The complementary filter is a frequency domain filter. In its strictest sense, the definition of a
complementary filter refers to the use of two or more transfer functions, which are mathematical
complements of one another. Thus, if the data from one sensor is operated on by G(s), then the data
from the other sensor is operated on by I-G(s), and the sum of
the transfer functions is I, the identity matrix. In the case of a one-dimensional filter as will be
described in this paper, the identity matrix reduces to the scalar number one.
In a typical two -input system, one input will provide information with high frequency noise, and is
thus low-pass filtered. The other input provides information with low frequency noise, and is high-pass
filtered. If the low-pass and high-pass filters are mathematical complements, then the output of the
-
8/18/2019 Balancing Robot ATMEGA328
10/52
10
filter is the complete reconstruction of the variable being sensed, minus the noise associated with the
sensors.
A block diagram illustrating this process with “perfect” 1st-order low-pass and high-pass filters is
shown below:
Figure 1 Principle of complementary filter
A simple estimation technique that is often used in the flight control industry to combine measurements
is the complementary filter . This filter is actually a steady state Kalman filter (i.e., a Wiener filter) for
a certain class of filtering problems. This relationship does not appear to be well known by many
practitioners of either complementary or Kalman filtering. One exception is the tutorial paper by
Brown which discusses this relationship without going into the mathematical details. The
complementary filter users do not consider any statistical description for the noise corrupting the
signals, and their filter is obtained by a simple analysis in the frequency domain. The proponents of the
Kalman filtering approach work in the time domain and do not pay much attention to the transfer
function or frequency domain (Wiener filter) approach to the filtering problem, since it is a less general
approach to the filtering problem. The Wiener filter solution to this class of multiple-input estimation
problems appeared in the literature, well before Kalman published his classic paper. This paper reviews
complementary filtering and shows how this technique is related to Kalman and Wiener filtering. Since
both Kalman and complementary filtering are under consideration for use in the Space Shuttle Reentry
and Landing Navigation System, the relationship between them should be well understood.
-
8/18/2019 Balancing Robot ATMEGA328
11/52
11
2.2 Kalman Filter
Kalman filters, as they are used in navigation systems, are based on the complementary filtering
principle. The basic block diagram is given in Fig. 5, although, as in the previous cases, the actual
implementation may be different. Note the similarity between Fig.5 and Fig.1(B). The complementary
constraint means that the filter just operates on the noise and is not affected by actual signals that are to
be estimated. The advantages and disadvantages of removing this constraint are discussed as follows:
In applying Kalman filtering to the problem of combining noisy measurements, the philosophy used is
that the processing of one class of measurements defines the basic process equations. The other
measurements, sometimes referred to as augmenting measurements, define the measurement equations
for the filter. After discussing the basic equations, the two examples of the previous section are
reworked using the steady-state Kalman filter approach. These examples can also be solved by the
Wiener filter approach using spectrum factorization. The relationship between the steady-state or
stationary Kalman filter and the Wiener filter is discussed in the book by Sage and Melsa [6].
Basically, there are two measurements, one of which serves as an input to a differential equation which
serves as the process model. The ideal equations are
xI = FxI + gu (process)
zI = hxI (measurement)
where u is one noiseless measurement and zI is the other. F, g, h, and x are n*n, n*1, 1*n, and n*1
matrixes, respectively; zj and u are scalars. In actuality, we have two noisy measurements, so that the
equations are
x = Fx + g(u + w)
z =hxI + v
where w and v are zero-mean, white, Gaussian noise.
The error equations are
-
8/18/2019 Balancing Robot ATMEGA328
12/52
12
where 6x is the error vector.
The Kalman filter equation is
Figure 2 Typical application of the Kalman filter in inertial navigation
where 6k is the estimate of the error vector and k is the Kalman filter gain. k, an n*1 matrix, is obtained
from the equations
where P, the n*n error covariance matrix, is the solution of the Riccati equation
in which R = u2 is the variance of the measurement noise and Q = u2 is the variance of the process
noise. The stationary Kalman filter is obtained by setting P = 0 in the Riccati equation. The actual
estimates of the signals are
In order to show the relationship with the complementary filters, the above equations can be
manipulated to produce a differential equation for directly:
As is shown below, this equation is identical to the differential equations of the complementary filters
for the example under consideration.
-
8/18/2019 Balancing Robot ATMEGA328
13/52
13
Example 1
The process equation from Fig. 2(A) is
Therefore, F = 0, g = 1, and h = 1, so that the algebraic Riccati equation is
The filter equation is obtained by substituting into above:
This equation is identical to the equation of the complementary filter in Fig. 2(B), where the time
constant of the filter is now Note that a time constant of four, as in the complementary
filter, means that the barometric signal is assumed to be much noisier than the accelerometer signal. In
the complementary filter, the time constant is chosen to get most of the information from the
accelerometer signal and use the barometric information only as along-term reference.
-
8/18/2019 Balancing Robot ATMEGA328
14/52
2.3 PID Controller
A proportional-integral-derivative
mechanism (controller) widely
Controllers, SCADA systems, Re
as the difference between a meas
to minimize the error in outputs by
The PID controller algorithm in
sometimes called three-term
denoted P, I, and D. Simply put,
the present error, I on the accumul
current rate of change. The weig
control element such as the positi
element.
In the absence of knowledge o
considered to be the best controlle
controller can provide control acti
controller can be described in ter
which the controller overshoots th
the PID algorithm for control does
Some applications may require usi
This is achieved by setting the oth
controller in the absence of the
derivative action is sensitive to
prevent the system from reaching i
14
controller (PID controller) is a control lo
used in industrial control systems (Programma
ote Terminal Units etc). A PID controller calculates an "
red process variable and a desired set point. The control
adjusting the process control inputs.
olves three separate constant parameters, and is
control: the proportional, the integral and deriv
hese values can be interpreted in terms of time: P
ation of past errors, and D is a prediction of future error
ted sum of these three actions is used to adjust the p
on of a control valve, a damper, or the power supplied
the underlying process, a PID controller has histor
. By tuning the three parameters in the PID controller al
on designed for specific process requirements. The resp
s of the responsiveness of the controller to an error, t
set point, and the degree of system oscillation. Note th
not guarantee optimal control of the system or system st
igure 3 PID controller block diagram
g only one or two actions to provide the appropriate sys
r parameters to zero. A PID controller will be called a P
espective control actions. PI controllers are fairly co
easurement noise, whereas the absence of an integra
ts target value due to the control action.
p feedback
le Logic
error" value
ler attempts
accordingly
tive values,
depends on
s, based on
ocess via a
o a heating
ically been
orithm, the
onse of the
e degree to
t the use of
bility.
em control.
, PD, P or I
mon, since
l term may
-
8/18/2019 Balancing Robot ATMEGA328
15/52
2.3.1 PID controller theory
The PID control scheme is na
manipulated variable (MV). The
the output of the PID controller.
algorithm is:
where
: Proportional gain, a
: Integral gain, a tuni
: Derivative gain, a t
: Error
: Time or instantaneous
: Variable of integratio
SP: Set point
PV: Process Variable
Proportional Term
The proportional term produces a
proportional response can be adjus
gain constant.
The proportional term is given by:
A high proportional gain results i
proportional gain is too high, the
small output response to a large i
proportional gain is too low, th
disturbances. Tuning theory and in
the bulk of the output change.
15
ed after its three correcting terms, whose sum con
roportional, integral, and derivative terms are summed
Defining as the controller output, the final form
tuning parameter
g parameter
uning parameter
time (the present)
; takes on values from time 0 to the present .
n output value that is proportional to the current error
ted by multiplying the error by a constant K p, called the
a large change in the output for a given change in the
system can become unstable. In contrast, a small gain
nput error, and a less responsive or less sensitive contr
e control action may be too small when responding
dustrial practice indicate that the proportional term shoul
stitutes the
to calculate
of the PID
value. The
roportional
error. If the
results in a
oller. If the
to system
d contribute
-
8/18/2019 Balancing Robot ATMEGA328
16/52
Figure 4Plot of PV
Integral Term
The contribution from the integr
duration of the error. The integral
and gives the accumulated offset t
then multiplied by the integral gai
The integral term is given by:
The integral term accelerates the
steady-state error that occurs wit
responds to accumulated errors fr
value
Figure 5Plot of PV
16
vs time, for three values of Kp (Ki and Kdheld constant)
l term is proportional to both the magnitude of the er
in a PID controller is the sum of the instantaneous erro
at should have been corrected previously. The accumul
( ) and added to the controller output.
ovement of the process towards set point and eliminates
a pure proportional controller. However, since the i
m the past, it can cause the present value to overshoot t
vs time, for three values of Ki (Kp and Kdheld constant)
ror and the
r over time
ted error is
the residual
tegral term
he set point
-
8/18/2019 Balancing Robot ATMEGA328
17/52
Derivative Term
The derivative of the process erro
multiplying this rate of change b
derivative term to the overall contr
The derivative term is given by:
Derivative action predicts syste
system. An ideal derivative is n
additional low pass filtering f
noise. Derivative action is seldom
controllers - because of its variable
Figure 6Plot of PV
2.3.2 Limitations of PID co
While PID controllers are appli
without any improvements or only
not in general provide optimal co
feedback system, with constant pa
performance is reactive and a co
without a model of the process, b
the process without resorting to an
PID controllers, when used alone,
so that the control system does no
also have difficulties in the presen
17
is calculated by determining the slope of the error ov
the derivative gain K d . The magnitude of the contrib
ol action is termed the derivative gain, K d .
behaviour and thus improves settling time and stab
t causal, so that implementations of PID controllers
r the derivative term, to limit the high frequenc
used in practice though - by one estimate in only 20%
impact on system stability in real-world applications.
vs time, for three values of Kd (Kp and Kiheld constant)
troller
able to many control problems, and often perform s
coarse tuning, they can perform poorly in some applicati
ntrol. The fundamental difficulty with PID control is
ameters, and no direct knowledge of the process, and
promise. While PID control is the best controller in
tter performance can be obtained by overtly modelling
observer.
can give poor performance when the PID loop gains mus
t overshoot, oscillate or hunt about the control set point
ce of non-linearities, may trade-off regulation versus res
er time and
tion of the
ility of the
include an
gain and
of deployed
atisfactorily
ons, and do
that it is a
hus overall
n observer
the actor of
be reduced
value. They
ponse time,
-
8/18/2019 Balancing Robot ATMEGA328
18/52
18
do not react to changing process behaviour (say, the process changes after it has warmed up), and have
lag in responding to large disturbances.
The most significant improvement is to incorporate feed-forward control with knowledge about the
system, and using the PID only to control error. Alternatively, PIDs can be modified in more minor
ways, such as by changing the parameters (either gain scheduling in different use cases or adaptively
modifying them based on performance), improving measurement (higher sampling rate, precision, and
accuracy, and low-pass filtering if necessary), or cascading multiple PID controllers.
Linearity
Another problem faced with PID controllers is that they are linear, and in particular symmetric. Thus,
performance of PID controllers in non-linear systems (such as HVAC systems) is variable. For
example, in temperature control, a common use case is active heating (via a heating element) but
passive cooling (heating off, but no cooling), so overshoot can only be corrected slowly – it cannot be
forced downward. In this case the PID should be tuned to be over damped, to prevent or reduce
overshoot, though this reduces performance (it increases settling time).
Noise in derivative
A problem with the derivative term is that it amplifies higher frequency measurement or
process noise that can cause large amounts of change in the output. It does this so much, that a physical
controller cannot have a true derivative term, but only an approximation with limited bandwidth. It is
often helpful to filter the measurements with a low-pass filter in order to remove higher-frequency
noise components. As low-pass filtering and derivative control can cancel each other out, the amount of
filtering is limited. So low noise instrumentation can be important. A nonlinear median filter may be
used, which improves the filtering efficiency and practical performance. In some cases, the differential
band can be turned off with little loss of control. This is equivalent to using the PID controller as a PI
controller.
-
8/18/2019 Balancing Robot ATMEGA328
19/52
19
CHAPTER 3
COMPONENTS REVIEW
3.1 ATmega 328
A highly integrated chip that contains all the components comprises a controller. Typically this
includes a CPU, RAM, some form of ROM, I/O ports, and timers. Unlike a general-purpose computer,
which also includes all of these components, a microcontroller is designed for a very specific task; to
control a particular system. As a result, the parts can be simplified and reduced, which cuts down on
production costs.
Figure 7ATmega 328
Microcontrollers are sometimes called embedded microcontrollers. This just means that they are part of
an embedded system; that is, one part of a larger device or system. Microcontrollers are used in
automatically controlled products and devices, such as automobile engine control systems, implantable
medical devices, remote controls, office machines, appliances, power tools, toys and other embedded
systems. The first integrated circuit was developed by Jack Kilby of Texas Instruments and Robert
Noyce of Fairchild Semiconductor in 1950.
Comparison between ATmega48PA, ATmega88PA,ATmega168PA and ATmega328P
The ATmega48PA, ATmega88PA, ATmega168PA and ATmega328P differ only in memory sizes,
boot loader support, and interrupt vector sizes. Table summarizes the different memory and interrupt
vector sizes for the three devices.
Device Flash EEPROM RAM Interrupt Vector Size
ATmega48PA 4K Bytes 256 Bytes 512 Bytes 1 instruction word/vector
ATmega88PA 8K Bytes 512 Bytes 1K Bytes 1 instruction word/vector
ATmega168PA 16K Bytes 512 Bytes 1K Bytes 2 instruction words/vector
ATmega328P 32K Bytes 1K Bytes 2K Bytes 2 instruction words/vector
Table 1
-
8/18/2019 Balancing Robot ATMEGA328
20/52
20
3.1.1 Block Diagram:
The AVR 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 throughputs up to ten times faster than conventional CISC
microcontrollers.
Figure 8 ATmega328 block diagram
-
8/18/2019 Balancing Robot ATMEGA328
21/52
21
3.1.2 Pin Diagram:
Figure 9 ATmega328 pin diagram
VCC
Digital supply voltage.
GND
Ground.
Port B (PB7:0) XTAL1/XTAL2/TOSC1/TOSC2
Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port
B output buffers have symmetrical drive characteristics with both high sink and source capability. As
inputs, Port B pins that are externally pulled low will source current if the pull-up resistors are
activated. The Port B pins are tri-stated when a reset condition becomes active, even if the clock is not
running. Depending on the clock selection fuse settings, PB6 can be used as input to the inverting
Oscillator amplifier and input to the internal clock operating circuit. Depending on the clock selection
fuse settings, PB7 can be used as output from the inverting Oscillator amplifier. If the Internal
Calibrated RC Oscillator is used as chip clock source, PB7..6 is used as TOSC2..1input for the
Asynchronous Timer/Counter2 if the AS2 bit in ASSR is set.
Port C (PC5:0)
Port C is a 7-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The PC5..0
output buffers have symmetrical drive characteristics with both high sink and source capability. As
inputs, Port C pins that are externally pulled low will source current if the pull-up resistors are
-
8/18/2019 Balancing Robot ATMEGA328
22/52
22
activated. The Port C pins are tri-stated when a reset condition becomes active, even if the clock is not
running.
PC6/RESET
If the RSTDISBL Fuse is programmed, PC6 is used as an I/O pin. Note that the electrical
characteristics of PC6 differ from those of the other pins of Port C. If the RSTDISBL Fuse isunprogrammed, PC6 is used as a Reset input. A low level on this pin for longer than the minimum
pulse length will generate a Reset, even if the clock is not running.
Port D (PD7:0)
Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port
D output buffers have symmetrical drive characteristics with both high sink and source capability. As
inputs, Port D pins that are externally pulled low will source current if the pull-up resistors are
activated. The Port D pins are tri-stated when a reset condition becomes active, even if the clock is not
running.
AVCC
AVCC is the supply voltage pin for the A/D Converter, PC3:0, and ADC7:6. It should be externally
connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC
through a low-pass filter. Note that PC6..4 use digital supply voltage, VCC.
AREF
AREF is the analog reference pin for the A/D Converter.
-
8/18/2019 Balancing Robot ATMEGA328
23/52
23
3.1.3 FEATURES
Manufacturer: Atmel
Product Category: 8-bit Microcontrollers - MCU
Core: AVR
Data Bus Width: 8 bit
Maximum Clock Frequency: 20 MHz
Program Memory Size: 32 kB
Data RAM Size: 2 kB
On-Chip ADC: Yes
Operating Supply Voltage: 1.8 V to 5.5 V
Maximum Operating Temperature: + 85 C
Package / Case: PDIP-28
Mounting Style: Through Hole
A/D Bi t Si ze: 10 bit
A/D Channels Availab le: 8
Brand: Atmel
Data Ram Type: SRAM
Data ROM Size: 1 kB
Data Rom Type: EEPROM
Interface Type: I2C, SPI, USART
Minimum Operating Temperature: - 4 0 C
Number of Progr ammable I/Os: 23
Number of Timers: 3
Packaging: Tube
Processor Series: megaAVR
Product Category: Microcontrollers - AVR
Program Memory Type: Flash
Series: ATMEGA328
Supply Voltage - Max: 5.5 V
Supply Voltage - Min: 1.8 V
-
8/18/2019 Balancing Robot ATMEGA328
24/52
24
3.2 MPU6050
Figure 10 MPU 6050
Motion Interface is becoming a “must-have” function being adopted by smart phone and tablet
manufacturers due to the enormous value it adds to the end user experience. In smartphones , 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 power consumption, high accuracy and repeatability, high
shock tolerance, and application specific performance programmability – all at a low consumer price
point.
The MPU-60X0 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-60X0 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-60X0 is also designed to
interface with multiple non-inertial digital sensors, such as pressure sensors, on its auxiliary I2C port.
The MPU-60X0 is footprint compatible with the MPU-30X0 family.
The MPU-60X0 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.
-
8/18/2019 Balancing Robot ATMEGA328
25/52
25
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-60X0 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-60X0 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.
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-60X0 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-60X0 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.
The MPU-6000 and MPU-6050 are identical, except that the MPU-6050 supports the I 2C serial
interface only, and has a separate VLOGIC reference pin. The MPU-6000 supports both I2C and SPI
interfaces and has a single supply pin, VDD, which is both the device’s logic reference supply and the
analog supply for the part.
Features
Gyroscope FeaturesThe triple-axis MEMS gyroscope in the MPU-60X0 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
-
8/18/2019 Balancing Robot ATMEGA328
26/52
26
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-60X0 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
High-G interrupt
User self-test
Additional Features
The MPU-60X0 includes the following additional features:
9-Axis MotionFusion by the on-chip Digital Motion Processor (DMP)
Auxiliary master I2C bus for reading data from external sensors (e.g., magnetometer)
3.9mA operating current when all 6 motion sensing axes and the DMP are enabled
VDD supply voltage range of 2.375V-3.46V
Flexible VLOGIC reference voltage supports multiple I2C interface voltages (MPU-6050
only)
Smallest and thinnest QFN package for portable devices: 4x4x0.9mm
Minimal cross-axis sensitivity between the accelerometer and gyroscope axes
1024 byte FIFO buffer reduces power consumption by allowing host processor to read the
data in bursts and then go into a low-power mode as the MPU collects more data
Digital-output temperature sensor
User-programmable digital filters for gyroscope, accelerometer, and temp sensor
10,000 g shock tolerant
400kHz Fast Mode I2C for communicating with all registers
1MHz SPI serial interface for communicating with all registers (MPU-6000 only)
-
8/18/2019 Balancing Robot ATMEGA328
27/52
27
3.3 Bidirectional level converter
Bi-directional level converter is a small device that safely steps down either 5volt signals to 3.3volt or
steps up 3.3volt to 5volt. This level converter also works with 2.8volt and 1.8volt devices. Each level
converter has the capability of converting 4 pins on the high side to 4 pins on the low side with two
inputs and two outputs provided for each side. One input on each side is positive voltage and the other
is ground.
The level converter is very easy to use. The board needs to be powered from the two voltages sources
(high voltage and low voltage) that your system is using. High voltage (5V for example) to the 'HV'
pin, low voltage (2.8V for example) to 'LV', and ground from the system to the 'GND' pin.
This revision of the Logic Level Converter fixes the issue with the board not stepping down from 5V to
3.3V correctly.
3.3.1 Circuit:
Figure 11 Bidirectional level converter
3.3.2 Features:
Minimum Voltage: 3.3V and Maximum Voltage: 5V
Bi-directional Logic Level conversion is possible.
BreadBoard friendly.
-
8/18/2019 Balancing Robot ATMEGA328
28/52
28
Bi-Directional MOSFET Voltage Level Converter 3.3V to 5V
When connecting 3.3V devices and 5V devices voltage level conversion is required. The following
circuit will allow this to be done bi-directionally:
Figure 12 I2C using MOSFET
Low Side Control
When the low side (3.3V) device transmits a '1' (3.3V), the MOSFET is tied high (off), and the high
side sees 5V through the R2 pull-up resistor. When the low side transmits a '0' (0V), the MOSFET
source pin is grounded and the MOSFET is switched on and the high side is pulled down to 0V.
High Side Control
When the high side transmits a '0' (0V) the MOSFET substrate diode conducts pulling the lowside
down to approx 0.7V, this is also low enough to turn the MOSFET on, further pulling the low side
down. When the high side transmits a '1' (5V) the MOSFET source pin is pulled up to 3.3V and the
MOSFET is OFF.
This works with I2C.
-
8/18/2019 Balancing Robot ATMEGA328
29/52
29
3.4 L293D
The L293 and L293D are quadruple high-current half-H drivers. The L293 is designed to provide
bidirectional drive currents of up to 1 A at voltages from 4.5 V to 36 V. The L293D is designed to
provide bidirectional drive currents of up to 600-mA at voltages from 4.5 V to 36 V. Both devices are
designed to drive inductive loads such as relays, solenoids, dc and bipolar stepping motors, as well as
other high-current/high-voltage loads in positive-supply applications.
All inputs are TTL compatible. Each output is a complete totem-pole drive circuit, with a Darlington
transistor sink and a pseudo Darlington source. Drivers are enabled in pairs, with drivers 1 and 2
enabled by 1,2EN and drivers 3 and 4 enabled by 3,4EN. When an enable input is high, the associated
drivers are enabled, and their outputs are active and in phase with their inputs. When the enable input is
low, those drivers are disabled, and their outputs are off and in the high-impedance state. With the
proper data inputs, each pair of drivers forms a full-H (or bridge) reversible drive suitable for solenoid
or motor applications.
3.4.1 Block Diagram
Figure 13 L293D Block Diagram
-
8/18/2019 Balancing Robot ATMEGA328
30/52
30
3.4.2 Pin Diagram:
Figure 14 L293D Pin Diagram
Pin Description:
Table 2
-
8/18/2019 Balancing Robot ATMEGA328
31/52
31
3.4.3 Features:
Driver Case Style:DIP
Motor Type:Half-H
No. of Outputs:4
No. of Pins:16
Operating Temperature Max:70°C
Operating Temperature Min:0°C
Output Current:600mA
Output Voltage:36V
Supply Voltage Max:36V
Supply Voltage Min:4.5V
Supply Voltage Range:4.5V to 36V
3.4.4 Circuit Diagram
Figure 15 L293D Circuit Diagram
-
8/18/2019 Balancing Robot ATMEGA328
32/52
32
3.5 LM7805
A voltage regulator is a circuit that supplies a constant voltage regardless of changes in load current.
7805 is a voltage regulator integrated circuit. It is a member of 78xx series of fixed linear voltage
regulator ICs. The voltage source in a circuit may have fluctuations and would not give the fixed
voltage output. The voltage regulator IC maintains the output voltage at a constant value. The xx in
78xx indicates the fixed output voltage it is designed to provide. 7805 provides +5V regulated power
supply. Capacitors of suitable values can be connected at input and output pins depending upon the
respective voltage levels.
Figure 16 LM7805
3.5.1 Pin description:
Pin No Function Name1 Input voltage (5V-18V) Input
2 Ground (0V) Ground
3 Regulated output; 5V (4.8V-5.2V) Output
Table 3
3.5.2 Circuit:
Proper operation requires a common ground between input and output voltages. The difference
between input and output voltages is called dropout voltage. Acapacitorof 0.33µF is required if the
regulator is located at an appreciable distance from the power supply filter. Even though capacitor of
0.1 µF is not needed, it may be used to improve the transient response of the regulator.
Figure 17 LM7805 Connection Diagram
-
8/18/2019 Balancing Robot ATMEGA328
33/52
33
3.6 LM317
The LM317 is an adjustable 3−terminal positive voltage regulator capable of supplying in excess of 1.5
A over an output voltage range of 1.2 V to 37 V. This voltage regulator is exceptionally easy to use and
requires only two external resistors to set the output voltage. Further, it employs internal current
limiting, thermal shutdown and safe area compensation, making it essentially blow−out proof. The
LM317 serves a wide variety of applications including local, on card regulation. This device can also
be used to make a programmable output regulator, or by connecting a fixed resistor between the
adjustment and output, the LM317 can be used as a precision current regulator.
Figure 18 LM317
3.6.1 Features
Output Current in Excess of 1.5 A
Output Adjustable between 1.2 V and 37 V
Internal Thermal Overload Protection
Internal Short Circuit Current Limiting Constant with Temperature
Output Transistor Safe−Area Compensation
Floating Operation for High Voltage Applications
Available in Surface Mount D2PAK −3, and Standard 3−Lead
Transistor Package
NCV Prefix for Automotive and Other Applications Requiring
Unique Site and Control Change Requirements; AEC−Q100
Qualified and PPAP Capable
Eliminates Stocking many Fixed Voltages
These are Pb−Free Devices
-
8/18/2019 Balancing Robot ATMEGA328
34/52
34
3.6.2 Circuit
Figure 19 LM317 Circuit Diagram
*_Cin is required if regulator is located an appreciable distance from power supply filter.
**_CO is not needed for stability, however, it does improve transient response.
Since IAdj is controlled to less than 100 A, the error associated with this term isnegligible in most applications.
-
8/18/2019 Balancing Robot ATMEGA328
35/52
35
CHAPTER 4
ASSEMBLING THE ROBOT
Block Diagram for balancing robot
Chassis
-
8/18/2019 Balancing Robot ATMEGA328
36/52
36
Tyres
Assembling the motors with chassis
-
8/18/2019 Balancing Robot ATMEGA328
37/52
37
Assembling the wheels
Circuit designing on PCB
-
8/18/2019 Balancing Robot ATMEGA328
38/52
38
Final Structure
-
8/18/2019 Balancing Robot ATMEGA328
39/52
4.1 AVR STUDIO
AVR Studio is used by embe
Atmel microprocessors such
assembly programming for th
debugging. Beginning with v
readily used in conjunction wi
All Atmel AVR microcontrol
software, you can use an inteIDE contains everything you
your code straight into the on
components.
STEPS TO PROGRA
1. Open AVR Studio and c
project name and initia
“BlinkLED” and elected
file “BlinkLED.c”. Click
“Finish”, you will not b
going to the “Project” me
Figu
39
CHA
PROGRAMMING THE
ded programmers for programming and debugging for
as the Atmega8 or even the Atmega128. While it has
ose who prefer to use higher languages, it uses the cof
ersion 4 AVR Studio has now moved to dwarf2, and c
th the open source gcc based compiler WinAVR.
lers require some software to be useful. To create and
rated development environment (IDE), such as Atmeleed to create, compile and debug code, and it will let yo
chip Flash of the AVR microcontroller - without any ot
lick New Project. Select AVR GCC for the project typ
l file name. In the screenshot below, we named
to have a folder called “C:\BlinkLED” created containi
Next >>. DO NOT click “Finish” yet. If you do accid
able to perform step 2 and will instead have to set th
u and selecting “Configuration Options”.
re 20 Creating new AVR Studio-4 project
PTER 5
OBOT
any of the
support for
format for
an be more
debug this
tudio. Thisu download
er software
. Enter the
our project
g the blank
ntally click
e device by
-
8/18/2019 Balancing Robot ATMEGA328
40/52
2. Select AVR Simulator a
target AVR. For an Ora
ATmega328P, ATmega3
your Orangutan or 3pi Ro
Figu
3. Write your program in Bl
on the toolbar (or press F
Figu
40
the debug platform and then select the appropriate dev
gutan or 3pi Robot, this will either be ATmega48,
24PA, ATmega644P, or ATmega1284P depending on
bot has. Click Finish.
re 21 Creating new AVR Studio-4 Project
nkLED.c as seen in the screen shot below and click the
).
re 22 Building a project with AVR Studio
ce for your
Tmega168,
which chip
uild button
-
8/18/2019 Balancing Robot ATMEGA328
41/52
4. Make sure your USB AV
B cable and then click th
accomplish this by going
Figure 23
5. This will bring up a prog
AVR programmer uses A
this is not the same as A
what it is, or select Auto
You can determine your p
of your Device Manage
“Connect…” to bring up t
Figure 24 A
If the ISP window does n
the programmer. Please s
If AVR Studio brings
programmer’s firmware,
prevent this dialog from
programmer’s hardware a
41
programmer is connected to your computer via its US
Display the ‘Connect’ Dialog button on the toolbar. Y
to the “Tools” menu and selecting Program AVR > Con
onnecting to the programmer with AVR studio
rammer selection dialog. Select AVRISP as the platfor
VR ISP version 2, which is written as AVRISPv2. Plea
R ISP mkII. Select the port name of your programmer i
nd AVR Studio will try all the ports unti l it detects the p
rogrammer’s port name by looking in the “Ports (COM
for “Pololu USB AVR Programmer Programming
he ISP window.
VR Studio-4's programmer selection dialog box
ot appear when you click “Connect…”, your computer c
e Troubleshooting for help identifying and fixing the pro
p a dialog asking if you want to upgrade (or down
click Cancel to ignore the message and use your prog
appearing in the future, use the Configuration Utilit
nd software version numbers.
A to mini-
ou can also
nect….
. The USB
se note that
f you know
rogrammer.
LPT)” list
ort”. Click
nnot detect
blem.
rade) your
ammer. To
change the
-
8/18/2019 Balancing Robot ATMEGA328
42/52
6. Select the Main tab. In t
you selected when you c
be ATmega48, ATmega1
Figure
7. If you have not done so
ISP cable. Make sure the
your target device! You
the Read Signature butt
signature. If everything
If the signature does no
selected (or possibly you
please see Troubleshootin
Figure 26 Readi
8. Now it is time to progr
File in the Flash section program. You can brows
If you navigate to your p
Click the Program butto
“EEPROM” or “ELF Pro
42
e dropdown box that lists AVR models, select the same
reated the project. For an Orangutan or 3pi Robot, this
68, or ATmega328P.
25Selecting the device for ISP programming
lready, connect the programmer to the target device usi
cable is oriented so that pin 1 on the connector lines up
can test the connection by going to the Main tab a
n. This sends a command to the target AVR asking fo
orks correctly, you should see “Signature matches selec
match the selected device, you probably have the w
r target device is turned off). If reading the signature f
g for help getting your connection working.
ng the device signature in AVR studio's main ISP tab
m your target device. Select the Program tab. Your I
needs to be the hex file that was generated when yofor this using the "..." button to the right of the input fi
oject’s folder, you should find it as “default\.hex”.
one in the
-
8/18/2019 Balancing Robot ATMEGA328
43/52
F
43
igure 27 AVR Studio's program ISP tab
-
8/18/2019 Balancing Robot ATMEGA328
44/52
44
CHAPTER 6
TESTING THE ROBOT
Prior to programming the robot with final program, several test programs were burned in the
microcontroller to verify various discrete segments of the hardware structure. The robot was tested to
verify the functioning of the following segments for proper operation:
Regulated 5V dc output from LM7805
Regulated 3.13V dc power output from LM317 regulator.
Level conversion from bidirectional level converter.
PID control unit
Motor assembly
Sensor Check
6.1. PID Control unit
Working of PID control unit was tested by varying the brightness of an LED connected at pin no.
16 of the microcontroller. Whenever the control knob of potentiometer is rotated, the brightness
of the LED varies from maximum to off state. This indicated the proper functioning of the PID
unit.
Code for PID Check:
int Led=10;
intanalog=A1;
intval=0;
void setup()
{
pinMode(Led, OUTPUT);
pinMode(analog, INPUT);
-
8/18/2019 Balancing Robot ATMEGA328
45/52
45
}
void loop()
{
val = analogRead(analog);
analogWrite ( Led, val/4);
}
6.2. Motor Speed Control
While balancing the robot on two wheels, it is necessary to adjust the speed of the motor in
accordance with instability of the system. If the system is highly unstable i.e. far away from it’s
balanced position, then the motor should work on higher speed.
But if the robot is slightly misaligned, then the speed of the motor should be slow. In case the
motor provides the same higher speed, robot may encounter a jerk in the opposite direction and
thus result in imbalance in the other direction.
The speed of the motor is controlled by using analog output from PID unit through
potentiometers. The PWM pins of microcontroller are connected to enable pins of motor driver(
pins 1 and 9).
Code for Speed Check:
int Led=10;
intanaloga=A1;
int Motor1a = 0;
int Motor1b = 1;
int Motor2a = 2;
int Motor2b = 3;
intMotorEnable=5;
int MotorEnable2=6;
intanalog=A2;
intval=0;
voidMotorSetup()
{
pinMode(Motor1a, OUTPUT);
-
8/18/2019 Balancing Robot ATMEGA328
46/52
46
pinMode(Motor1b, OUTPUT);
pinMode(Motor2a, OUTPUT);
pinMode(Motor2b, OUTPUT);
}
voidmForward()
{
digitalWrite(Motor1a, HIGH);
digitalWrite(Motor1b, LOW);
digitalWrite(Motor2a, HIGH);
digitalWrite(Motor2b, LOW);
}
void setup()
{
pinMode(Led, OUTPUT);
pinMode(analoga, INPUT);
pinMode(MotorEnable, OUTPUT);
pinMode(analog, INPUT);
pinMode(MotorEnable2, OUTPUT);
digitalWrite(MotorEnable2, LOW);
MotorSetup();
mForward();
}
void loop()
{
val = analogRead(analoga);
analogWrite ( Led, val/4);
// val = analogRead(analog);
analogWrite ( MotorEnable, val/4);
}
-
8/18/2019 Balancing Robot ATMEGA328
47/52
47
6.3. Sensor Check
Output from MPU6050 was observed. Movement of the robot in three axis resulted in change of
current coordinates which indicated that the sensor was properly connected and performing the
desired operation.
Sensor check code:
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"
#include "MPU6050.h"
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 accelgyro;
//MPU6050 accelgyro(0x69); //
-
8/18/2019 Balancing Robot ATMEGA328
48/52
48
// for a human.
//#define OUTPUT_BINARY_ACCELGYRO
#define LED_PIN 13
boolblinkState = false;
void setup()
{
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
// initialize serial communication
// (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
// it's really up to you depending on your project)
Serial.begin(38400);
// initialize device
Serial.println("Initializing I2C devices...");
accelgyro.initialize();
// verify connection
Serial.println("Testing device connections...");
Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050
connection failed");
// use the code below to change accel/gyro offset values
/*
Serial.println("Updating internal sensor offsets...");
// -76 -2359 1688 0 0 0
Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
-
8/18/2019 Balancing Robot ATMEGA328
49/52
49
Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
Serial.print("\n");
accelgyro.setXGyroOffset(220);
accelgyro.setYGyroOffset(76);
accelgyro.setZGyroOffset(-85);
Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
Serial.print("\n");
*/
// configure Arduino LED for
pinMode(LED_PIN, OUTPUT);
}
void loop()
{
// read raw accel/gyro measurements from device
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
// these methods (and a few others) are also available
//accelgyro.getAcceleration(&ax, &ay, &az);
//accelgyro.getRotation(&gx, &gy, &gz);
#ifdef OUTPUT_READABLE_ACCELGYRO
// display tab-separated accel/gyro x/y/z values
Serial.print("a/g:\t");
Serial.print(ax); Serial.print("\t");
Serial.print(ay); Serial.print("\t");
-
8/18/2019 Balancing Robot ATMEGA328
50/52
50
Serial.print(az); Serial.print("\t");
Serial.print(gx); Serial.print("\t");
Serial.print(gy); Serial.print("\t");
Serial.println(gz);
#endif
#ifdef OUTPUT_BINARY_ACCELGYRO
Serial.write((uint8_t)(ax>> 8)); Serial.write((uint8_t)(ax& 0xFF));
Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
Serial.write((uint8_t)(az>> 8)); Serial.write((uint8_t)(az& 0xFF));
Serial.write((uint8_t)(gx>> 8)); Serial.write((uint8_t)(gx& 0xFF));
Serial.write((uint8_t)(gy>> 8)); Serial.write((uint8_t)(gy& 0xFF));
Serial.write((uint8_t)(gz>> 8)); Serial.write((uint8_t)(gz& 0xFF));
#endif
// blink LED to indicate activity
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
}
-
8/18/2019 Balancing Robot ATMEGA328
51/52
51
Output Graphs:
-
8/18/2019 Balancing Robot ATMEGA328
52/52
BIBLIOGRAPHY
http://www.instructables.com/id/2-Wheel-Self-Balancing-Robot-by-using-Arduino-and-/
http://en.wikipedia.org/wiki/Kalman_filter
http://forum.arduino.cc/index.php?topic=58048.0
http://www.instructables.com/id/PCB-Quadrotor-Brushless/step15/IMU-Part-
2-Complementary-Filter/
http://en.wikipedia.org/wiki/PID_controller
http://www.atmel.in/devices/ATMEGA328P.aspx
http://www.invensense.com/mems/gyro/mpu6050.html
http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter
http://www.ti.com/lit/ds/symlink/l293d.pdf
http://www.ti.com/lit/ds/symlink/lm317.pdf
http://www.engineersgarage.com/tutorials/avr-studio4-working
http://stackoverflow.com/tags/avr-studio4/info
http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter
http://www.atmel.in/tools/atmelstudio.aspx