final year project thesis_full

70
I SELF - BALANCING ROBOT USING IMU AS A FEEDBACK ELEMENT AUTHORS FAISAL ALI 2012-EE-404 SOHAIB ARSHAD 2012-EE-419 AHSAN RAFIQ 2012-EE-426 PROJECT ADVISOR DR. FAIZAN DASTGEER ASSISTANT PROFESSOR UNIVERSITY OF ENGINEERING AND TECHNOLOGY, LAHORE (FAISALABAD CAMPUS) MAY, 2016

Upload: sohaib-arshad

Post on 21-Feb-2017

298 views

Category:

Documents


15 download

TRANSCRIPT

Page 1: FINAL YEAR PROJECT THESIS_Full

I

SELF - BALANCING

ROBOT USING IMU AS A FEEDBACK ELEMENT

AUTHORS

FAISAL ALI 2012-EE-404

SOHAIB ARSHAD 2012-EE-419

AHSAN RAFIQ 2012-EE-426

PROJECT ADVISOR

DR. FAIZAN DASTGEER

ASSISTANT PROFESSOR

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, LAHORE

(FAISALABAD CAMPUS)

MAY, 2016

Page 2: FINAL YEAR PROJECT THESIS_Full

II

[Intentionally kept Blank]

Page 3: FINAL YEAR PROJECT THESIS_Full

III

Self-Balancing Robot Using IMU as a Feedback Element

Authors

Faisal Ali Sohaib Arshad Ahsan Rafiq

2012-EE-404 2012-EE-419 2012-EE-426

A thesis submitted in partial fulfilment of the requirement

for the degree of

B.Sc. Electrical Engineering

Thesis Supervisor:

Dr. Faizan Dastgeer

Assistant Professor, Department of Electrical

Engineering, UET (Fsd. Campus)

External Examiner’s Signature: ____________________________________

Thesis Supervisor’s Signature: _____________________________________

DEPARTMENT OF ELECTRICAL

ENGINEERING

UNIVERSITY OF ENGINEERING AND

TECHNOLOGY LAHORE

May, 2016

Page 4: FINAL YEAR PROJECT THESIS_Full

IV

[Intentionally kept Blank]

Page 5: FINAL YEAR PROJECT THESIS_Full

V

ABSTRACT

This project deals with the stability issue to a mobile robot that has to

balance itself onto a two-wheeled supporting structure for its regular operation. To

resolve this issue we have designed two versions of Robot, Classic Version contains

a mechanical structure with low center of gravity and it was simulated to be stable

one, but it had unsymmetrical distribution of mass across its whole structure that’s

why we made the second version “the Charm” which resolved this issue. The core

of the project lies in an Inertial Measurement Unit or IMU, which consists of a 3-

axis accelerometer plus a 3-axis gyroscope aided by a Digital Motion Processor or

DMP. This GY-521 board processes every disturbance caused to the system and

inputs those coordinate changes to the Arduino Uno board (having an AVR

controller Atmega 328p) which processes that information on the basis of C

language code burnt inside it and activates the actuators to drive DC motors

accordingly to and fro in order to cause an anti-disturbance motion and producing

an opposite torque by accelerating in the falling direction. This disturbance is

reduced by damped oscillations using dual PID controller, tuned using classical

way of tuning. WBS was based on building a prototype of the Robot and then

building on the Actual Segway Robot that is able to carry a surveillance equipment

or it can be made to provide navigation to or from a remote place. Building a

success story here, would encourage us to work onto that higher level, and make

that assistance robot at an affordable price.

Keywords: Segway Robot, COG, IMU, DMP, AVR, DC motors, PID, WBS

Page 6: FINAL YEAR PROJECT THESIS_Full

VI

[Intentionally kept Blank]

Page 7: FINAL YEAR PROJECT THESIS_Full

VII

UNDERTAKING

We certify that research work titled “Self-Balancing Robot with IMU as a

Feedback Element” is our own work. The work has not been presented elsewhere

for assessment. Wherever material has been used from other sources it has been

properly acknowledged / referred.

Faisal Ali

2012-EE-404

Sohaib Arshad

2012-EE-419

Ahsan Rafiq

2012-EE-426

Page 8: FINAL YEAR PROJECT THESIS_Full

VIII

[Intentionally kept Blank]

Page 9: FINAL YEAR PROJECT THESIS_Full

IX

ACKNOWLEDGEMENTS

In accomplishing this project we would like to acknowledge the work of

GeekmomProjects website owner and an Instructables account holder named

Ufactory. Their work has really helped us completing our project efficiently.

Lastly and more importantly, we acknowledge the efforts of our project advisor

Dr. Faizan Dastgeer for his instructions for the work-break down structure of the

project as well as compiling our results.

Page 10: FINAL YEAR PROJECT THESIS_Full

X

[Intentionally kept blank]

Page 11: FINAL YEAR PROJECT THESIS_Full

XI

Table of Contents

ABSTRACT ............................................................................................................ V

UNDERTAKING ................................................................................................. VII

ACKNOWLEDGEMENTS ................................................................................... IX

Table of Contents ................................................................................................... XI

Table of Figures ................................................................................................... XIII

Chapter 1 ................................................................................................................................................................................ 17

1.1 Background .................................................................................................. 17

1.2 Problem Statement ....................................................................................... 17

1.3 Project Objectives ........................................................................................ 18

1.4 Project Scopes .............................................................................................. 18

1.5 Literature Review ........................................................................................ 18 1.5.1 Terms to Remember ............................................................................................................ 18

1.5.1.1 Robot ........................................................................................................................... 18 1.5.1.2 Mobile Robot ............................................................................................................... 19 1.5.1.3 MPU 6050 ................................................................................................................... 19

1.5.1.3.1 IMU ................................................................................................................... 19 1.5.1.3.2 DMP .................................................................................................................. 19

1.5.1.4 Dual H-Bridge ............................................................................................................. 20 1.5.1.5 Arduino Uno ................................................................................................................ 20

1.5.2 Previous Case Study............................................................................................................ 20 1.5.3 PID Controller ..................................................................................................................... 22 1.5.4 IMU Implementation........................................................................................................... 22

1.5.4.1 Gyroscope .................................................................................................................... 22 1.5.4.2 Accelerometer .............................................................................................................. 22

1.5.5 Mathematical Modelling ..................................................................................................... 22

1.6 Overview of Project .......................................................................................... 23

Chapter 2 ................................................................................................................................................................................ 27

2.1 Components ...................................................................................................... 27 2.1.1 Arduino Uno R3 .................................................................................................................. 27 2.1.2 Inertial Measurement unit (IMU) ........................................................................................ 28 2.1.3 DC Gear Motors .................................................................................................................. 30 2.1.4 Batteries .............................................................................................................................. 31 2.1.5 H-Bridge DC motor Driver ................................................................................................. 31 2.1.6 Bluetooth Module HC-05 .................................................................................................... 32 2.1.7 Real-time PID Tuner ........................................................................................................... 32

2.2 Software ............................................................................................................ 33 2.2.1 Fritzing ................................................................................................................................ 33 2.2.2 Proteus 8.2 .......................................................................................................................... 34

2.2.2.1 VSM Studio ................................................................................................................. 34 2.2.2.2 Live Net-listing ............................................................................................................ 35 2.2.2.3 3D Viewer ................................................................................................................... 35 2.2.2.4 Bill of Materials ........................................................................................................... 35 2.2.2.5 Selection of Proteus 8.2 ............................................................................................... 35 2.2.3.1 Design without boundaries .......................................................................................... 36 2.2.3.2 Integrated electrical and mechanical design ................................................................ 36

Page 12: FINAL YEAR PROJECT THESIS_Full

XII

2.3 Mechanical Structure ........................................................................................ 37 2.3.1 Earlier Design Stages (Classic/ ver. 1.0) ............................................................................. 37 2.3.2 Final Design (Charm Design /ver. 2.0) ............................................................................... 38

2.3.2.1 Design Considerations ................................................................................................. 38 2.3.2.2 Designing Process and Simulation Results .................................................................. 38

Chapter 3 ................................................................................................................................................................................ 43

3.1 Implemented Designs ....................................................................................... 43 3.1.1 Classic Structure of SBR ..................................................................................................... 43 3.1.2 Charm Design of SBR......................................................................................................... 43

3.2 Features ............................................................................................................. 44 3.2.1 Classic Design of SBR ........................................................................................................ 44 3.2.2 Charm Design of SBR......................................................................................................... 44

3.3 Flaws in Classic ver. of SBR. ........................................................................... 44

3.4 Remedies to the flaws in Charm ver. of SBR, .................................................. 45

3.5 Working of the Charm ver. of SBR .................................................................. 46

Chapter 4 ................................................................................................................................................................................ 49

4.1 Algorithm .......................................................................................................... 49

4.2 Step-wise Implementation ................................................................................ 50 4.2.1 I2C Initialize ........................................................................................................................ 50 4.2.2 Serial Initialization .............................................................................................................. 50 4.2.3 If (I2C & Serial initialize) ................................................................................................... 50 4.2.4 Initialize DMP ..................................................................................................................... 50 4.2.5 While Loop ......................................................................................................................... 51 4.2.6 Termination ......................................................................................................................... 52

4.3 Applications ...................................................................................................... 53

4.4 Recommendations for Future Work on SBR .................................................... 53

References .................................................................................................................. 1

Appendix A .............................................................................................................................................................................. 1

Robot Firmware ........................................................................................................ 1

Appendix B .................................................................................................................................................................................i

Technical Data (Drawing sheets) of Robot .............................................................. i

Appendix C ............................................................................................................................................................................. iii

Technical Details of PMDC-Gear Motors ZGB37RB ............................................ iii

Page 13: FINAL YEAR PROJECT THESIS_Full

XIII

Table of Figures

Figure 1| A manipulator robot MA-2010 [1] ................................................................... 17 Figure 2| A mobile robot- 510 PackBot [2] ..................................................................... 17 Figure 3| Switches based H-Bridge for driving a DC motor both ways (FWD/ BWD) .. 20 Figure 4| Arduino Uno R3 Board [3] .............................................................................. 27

Figure 5| Arduino Board elaborative model, [4] ............................................................. 27 Figure 6| IMU MPU 6050 Circuit Board GY-521 6DOF, [5] ........................................ 29 Figure 7| Configuring IMU with Arduino Uno Fritzing screenshot ................................ 30 Figure 8|DC motor used for this project without gearbox. .............................................. 30 Figure 9| DC motor with gearbox .................................................................................... 30

Figure 10| DC Gear motor 12v, 300 rpm ........................................................................ 30 Figure 11| GEB Cells used for this project. ..................................................................... 31 Figure 12| H bridge using 3904 and 3906 ....................................................................... 31

Figure 13| L293D based H-Bridge, [6] ............................................................................ 32 Figure 14| L298n IC with pin description ....................................................................... 32 Figure 15| L298 IC based dual-H-Bridge Module, [7] .................................................... 32 Figure 16| HC_05 Bluetooth Module. ............................................................................. 32

Figure 17| PID Tuning Circuitry in current model .......................................................... 33 Figure 18| Fritzing trademark logo .................................................................................. 33 Figure 19| Circuit representation in fritzing, a screenshot image .................................... 33 Figure 20| Screen Shot to illustrate the workspace of Proteus 8.2 .................................. 34

Figure 21| Autodesk prototyping experience, [8] ............................................................ 35 Figure 22| Self Balancing Robot’s Ready-to-go design with custom IBL Environment,

screenshot. Image. .......................................................................................... 36 Figure 23| Design with more stability and relatively lower Center of Gravity. .............. 37

Figure 24| The Ready-to-go Assembly design, with more elegance and simplicity. ...... 37 Figure 25| Design Principle for the Structure Designing Process ................................... 38

Figure 26|3D Model of newly purchased motors ............................................................ 39 Figure 27| Beta Version of the Charm Design using ABS plastic .................................. 39 Figure 28| Acrylic Sheet Deign with tinted acrylic sheet (unavailable in market) ......... 39

Figure 29| Final Version "Charm" of the SBR, with Transparent Acrylic Sheet, and

Arduino Boards on top ................................................................................... 39 Figure 30| The Front view of the Implemented Charm version of SBR ......................... 40

Figure 31| Classic Design with minimum structural cost of 300 PKR ............................ 43 Figure 32| 3D Model of the current robotic structure, with low CG. .............................. 43

Figure 33| Curtesy KYSAN, Zheng Motors [9] ............................................................... iii

Page 14: FINAL YEAR PROJECT THESIS_Full

XIV

[Intentionally kept Blank]

Page 15: FINAL YEAR PROJECT THESIS_Full

XV

Chapter 1 Introduction

Contents

Background

Problem Statement

Project Objective

Project Scopes

Literature Review

Overview of thesis.

Page 16: FINAL YEAR PROJECT THESIS_Full

XVI

[Intentionally kept Blank]

Page 17: FINAL YEAR PROJECT THESIS_Full

17

Chapter 1

Introduction

1.1 Background

In today’s scenario, Robots are inevitable in mass production industries due to

their agility and efficient performance as cannot be imagined a few decades earlier.

Modern era of robotics comprises of more compact robotic structure, that is more

efficient and have even faster processing with wide range of applications from home-

based appliances to industrial CNC machines and from war-crafts to intelligent

surveillance robots. Robots have been widely used in automobile industries by the end

of late 20th century for precise cutting, welding, placing and carrying purposes.

Robotics has achieved its greatest success to date in the world of industrial

manufacturing. Robot arms, or manipulators, comprise a 2 billion dollar industry.

Bolted at its shoulder to a specific position in the assembly line, the robot arm can

move with great speed and accuracy to perform repetitive tasks such as spot welding

and painting.

In the electronics industry, manipulators place surface-mounted components

with superhuman precision, making the portable telephone and laptop computer

possible. Yet, for all of their successes, these commercial robots suffer from a

fundamental disadvantage: lack of mobility.

A fixed manipulator has a limited range of motion that depends on the location

where it is bolted down. In contrast, a mobile robot would be able to travel throughout

the manufacturing plant, flexibly applying its talents wherever it is most effective.

Figure 1| A manipulator robot MA-2010

[1]

Figure 2| A mobile robot- 510 PackBot

[2]

1.2 Problem Statement

This project is based upon the one of the fundamental problems a mobile

robot experiences: Self-balancing. The robot has to be based upon such an electro-

mechanical structure that balances itself onto a pair of wheels while standing tall.

If the platform itself is not balanced, which means it keeps falling-off away from

the vertical axis, then a gyro chip is needed to provide the angular position of the

robot base and input into the controller, which is then programmed in a balancing

Page 18: FINAL YEAR PROJECT THESIS_Full

18

algorithm. The PID controller then provides a type of feedback signal through a

PWM control signal to turn the dc-motor clockwise or anticlockwise, thus

balancing the platform. These two measurements are summed and fed-back to the

actuator which produces the counter torque required to balance the robot.

The robot has to be made mobile upon any sort of surface, leveled or rough,

based upon the maximum torque that its wheel can provide with the help of two

dedicated DC/Servo motors, one for each single wheel (in our case DC-motors

have been used). Other problems are locomotion, autonomy and risk assessment

for an autonomous self-balanced mobile robot, so their ability to maintain a sense

of position and to navigate without human intervention is a paramount.

1.3 Project Objectives

The aim of this project is to implement PID controller to a mobile robot to

maintain its flatness moving onto a platform. The objectives of this project are

as follows:

a) To design and develop proposed mobile 3D structural models for the

robot.

b) To choose easily accessible models for the project.

c) To design a PID controller to maintain the robot flatness

d) To simulate the controller using Matlab and analyse its performance.

e) To integrate the modelled controller into the mobile robot.

1.4 Project Scopes

The scopes of study are as follows:

a) Using MPU-6050 Inertial Measurement Unit (IMU) available in market

for stability

b) Using DC-motors for the cause of stability and linear acceleration instead

of Servo motors.

c) Using Dual-H-Bridge L298 as DC motor driver.

d) Using Arduino Uno as the mainboard of the mobile robot.

e) Using PID as the flatness controller.

f) Using Autodesk Inventor to design all mechanical 3D models of the

system.

g) Using Mobile development kits for GUI design of Bluetooth based

control.

h) Using Opto-isolators

i) Making this prototype robot within 15,000 PKRs budget.

1.5 Literature Review

1.5.1 Terms to Remember

1.5.1.1 Robot

Word robot* was coined by a Czech novelist Karel Capek in a 1920 play

titled Rassum’s Universal Robots (RUR). Robot in Czech is a word for

worker or servant.

Page 19: FINAL YEAR PROJECT THESIS_Full

19

A robot is a reprogrammable, multifunctional manipulator designed to

move material, parts, tools or specialized devices through variable

programmed motions for the performance of a variety of tasks: Robot

Institute of America, 1979.

1.5.1.2 Mobile Robot

A mobile robot needs locomotion mechanisms that enables it to move

unbounded throughout its environment. Robots with mobile bases are

typically platforms with wheels or tracks attached. Instead of wheels or

tracks, some robots employ legs in order to move about.

1.5.1.3 MPU 6050

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

output. 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. 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. Communication with all registers of the device is

performed using either I2C at 400 kHz or SPI at 1MHz (MPU-6000 only

Additional features include an embedded temperature sensor and an on-

chip oscillator with ±1% variation over the operating temperature range.

1.5.1.3.1 IMU

An inertial measurement unit (IMU*) is an electronic device

that measures and reports a body's specific force, angular rate, and

sometimes the magnetic field surrounding the body, using a

combination of accelerometers and gyroscopes, sometimes also

magnetometers. IMUs are typically used to manoeuvre aircraft,

including unmanned aerial vehicles (UAVs), among many others,

and spacecraft, including satellites and landers. Recent

developments allow for the production of IMU-enabled GPS

devices. An IMU allows a GPS receiver to work when GPS-signals

are unavailable, such as in tunnels, inside buildings, or when

electronic interference is present.

1.5.1.3.2 DMP

The embedded Digital Motion Processor (DMP*) is located

within the MPU-60X0 and offload computation of motion processing

algorithms from the host processor. The DMP acquires data from

accelerometers, gyroscopes, and additional 3rd party sensors such as

magnetometers, and processors which process the data. The resulting data

can be read from the DMP’s registers, or can be buffered in a FIFO. The

DMP has access to one of the MPU’s external pins, which can be used

for generating interrupts. The purpose of the DMP is to offload both

Page 20: FINAL YEAR PROJECT THESIS_Full

20

timing requirements and processing power from the host processor.

Typically, motion processing algorithms should be run at a high rate,

often around 200Hz, in order to provide accurate results with low latency.

This is required even if the application updates at a much lower rate; for

example, a low power user interface may update as slowly as 5Hz, but

the motion processing should still run at 200Hz. The DMP can be used

as a tool in order to minimize power, simplify timing, simplify the

software architecture, and save valuable MIPS on the host processor for

use in the application.

1.5.1.4 Dual H-Bridge

The term H-Bridge is derived from the typical graphical

representation of such a circuit. An H bridge* is built with four switches

(solid-state or mechanical). Since the IC packaging contains two set of H-

Bridges, hence the name “Dual H-Bridge”. When the switches S1 and S4

are closed (and S2 and S3 are open) a positive voltage will be applied

across the motor. By opening S1 and S4 switches and closing S2 and S3

switches, this voltage is reversed, allowing reverse operation of the motor.

Figure 3| Switches based H-Bridge for driving a DC motor both ways (FWD/ BWD)

Using the nomenclature above, the switches S1 and S2 should never

be closed at the same time, as this would cause a short circuit on the input

voltage source. The same applies to the switches S3 and S4. This condition

is known as shoot-through.

1.5.1.5 Arduino Uno

Arduino is an open-source computer hardware and software

company, project and user community that designs and manufactures

microcontroller-based kits for building digital devices and interactive

objects that can sense and control objects in the physical world. Arduino

comes in variety of sizes and IO pins with multiple modes, the type we are

using in this project is Arduino Uno R3* which is based on Atmel’s Atmega

328p micro-controller and have a UART communication port alongside 6

analog IO pins, 13 digital IO pins and 6 PWM pins with on-board supply

regulators for 5VDC and 3.3VDC as output for various small projects.

*Note: All these terms will be widely used in this project and their working will

be explained in later chapters.

1.5.2 Previous Case Study

Conducting initial review research is very critical in understanding self-

balancing platform control techniques. The review of research about related

literature conducted in this project summarizes some of topics related to the

Page 21: FINAL YEAR PROJECT THESIS_Full

21

techniques used for the balancing of platform based on Dc motor position.

Comparisons between the present project and the related topics of existing

information will also be discussed. The methodologies and the techniques used by

other researchers around the globe on the balancing platform topic will also be

reviewed.

Meena et al. (2011) proposed a design for a servo motor controller in

discrete-time system to obtain the transfer function of the PID controller design.

MATLAB / Simulink has been used to confirm the effectiveness of this new design

method, which provides a simple and powerful way to design a speed controller

for servo motor. It also extracted a DC servo motor mathematical model and

equations and there were three different motion controllers that were designed and

simulated to control the velocity of the motor.

Popescu et al. (2011) did a comparison between PID and Fuzzy controllers

used in mobile robot control. There is a significant problem for fuzzy controllers

in which computing time is longer than the PID because a lot of complex

operations such as requiring fuzzification, inference, and defuzzification.

Masakazu et al. (2005) proposed a tuning method for PID controller that

considers changes in system characteristics. It is about the concept of using the

optimization of PID controller tuning, depending on the obstacles on the control

input derivatives and considering model uncertainties caused by changes in the

system dynamics. Partial model matching method was used to evaluate

performance and control while the reference referred to interference and

repression compared to the tracking properties.

Arpit et al. (2012) proposed a performance comparison of PID and Fuzzy

logic controller using different defuzzification techniques for positioning control

of dc motors. The result of the fine-tuned PID controller gives relatively less

overshoot and settling time with no steady state error. The fuzzy logic controller

with different defuzzification techniques gives zero % overshoot and lesser

settling time.

In a paper titled ‘Attitude Estimation Using Low Cost Accelerometer and

Gyroscope’ written by Young Soo Suh (2003), it shows two different sensors

which are the accelerometer and gyroscope that exhibit poor results when used

separately to determine the attitude which is referred as the pitch angle or roll

angle. However, the gyroscope can combine with accelerometer to determine the

pitch or roll angle with much better result with the use of Kalman filter.

Tomislav et al. (2012) proposed self-balancing mobile robot tilter. It

provides a summary of work done in the field of electronic, mechanical design,

software design, system characterization and control theory. Robotic system

model and simulation results of various control methods required for the

stabilization of the system were studied. Dynamic effects become increasingly

important in assessing performance limits in robotic. The processes where the

project was carried out including design and production of certain parts of the

integration section, electronic, mechanical and software.

Hany Ferdinando et al. (2001) proposed a paper titled Developing

Mathematical Model of DC Servo Motor Using Bond Graph. Bond graph can

serve as a tool in the modelling of some plants. The plant was DC servo motor

Page 22: FINAL YEAR PROJECT THESIS_Full

22

with all parameter is unity. Simulink and 20-Sim was used for the simulation

procedure.

The use of plant transfer function had several performances, such as using

a step response and unit impulse function, the parameters change, how to control

the torque and speed using the input voltage and current.

1.5.3 PID Controller

This project concerns the development of a mobile robot with a platform,

which can be levelled using PID controller. The main objective is to control the

flatness of the platform efficiently with a low cost hardware without limiting the

strength and performance of the whole system. There are various stages that have

been used to stabilize the platform such as modelling the system, obtaining the

data from sensors and determining how the control algorithms will be

implemented. V.J. Van Doren (2009) suggested a two wheeled robot to perform

the balancing and control of mobile robots. In this project the Proportional,

Integral, Derivative (PID) has been implemented to control the flatness of a mobile

robot platform. PID has proven to be popular among the control engineering

community.

As stated by the author of article Vance J. VanDoren (2009), “For more

than 60 years after the introduction of Proportional-Integral-Derivative

controllers, remain the workhorse of industrial process control”.

1.5.4 IMU Implementation

1.5.4.1 Gyroscope

A gyroscope is a device that measures angular rate around an axis.

Tilt angle can be obtained by integrating angular rate over sampled time. The

gyroscope modifies a servo control signal by an amount proportional to its

measure of angular velocity. An estimate of angular displacement is obtained

by integrating the velocity signal over time. The Inclinometer outputs an

analogue signal, proportional to the angular displacement of the sensor

Braun, T., Sutherland, and Alistair (2002).

1.5.4.2 Accelerometer

As stated by A. Warnasch, and A. Killen (2002), the tool that

measures the inertial force in the opposite direction of free fall acceleration

vector in terms of g-force is acceleration. So, gravity acceleration shows 0g

power during free fall down constantly at 1g. It will be supported by the

ground with a force equivalent of 1g, when the accelerometer is at rest on

the surface of the earth. Because of that, it will show a constant downward

force perpendicular to the ground 1g rest. To obtain the tilt angle using the

Pythagorean Theorem can also use these features. Readers are referred to

Chapter 3 for more on accelerometer.

1.5.5 Mathematical Modelling

Modelling is the process of identifying the principal physical dynamic effects

to be considered in analysing a system, writing the differential and algebraic

Page 23: FINAL YEAR PROJECT THESIS_Full

23

equations from the conservation laws and property laws of the relevant discipline,

and reducing the equations to a convenient differential equation model (Robert,

1999). In order to develop the control system, mathematical model is established

to predict the behaviour before applied into real system. Actually, the dynamics

refer to a situation which is varying with time (Ernest, 1972). The dynamic

performance of a balancing robot depends on the efficiency of the control

algorithms and the dynamic model of the system.

1.6 Overview of Project

Chapter 1 covers the introduction of the project with project

objectives, its scope and literature review covering previous works on this

robot and some terms that will help determining the sense in which they will

be used throughout this literature.

Chapter 2 covers the experimental setup including the brief

description of the components used in the project and their mesh-up with

each other alongside the software that were used in this project for circuit

simulation, PCB designing and 3D mechanical modelling with the project

firmware.

Chapter 3 covers the hardware implementation that includes all

versions of the robot till the current stage, the flaws in the previous versions

and their proposed solutions, implemented in the current version and the

working of Current Model to eradicate those flaws.

Chapter 4 covers the algorithm and the code of Robot Program, with

stage wise elaboration of each level of hierarchy. Moreover, it features the

recommendations for future work, providing steps inching towards the

ultimate goal and providing some possible ideas of extensions that could be

made in future to make its scope utility specific.

Page 24: FINAL YEAR PROJECT THESIS_Full

24

[Intentionally kept Blank]

Page 25: FINAL YEAR PROJECT THESIS_Full

25

Chapter 2 Experimental Setup

Contents

Components

Software

Structure Designing

Page 26: FINAL YEAR PROJECT THESIS_Full

26

[Intentionally kept Blank]

Page 27: FINAL YEAR PROJECT THESIS_Full

27

Chapter 2 Experimental Setup

2.1 Components

In this section the specific components that were utilized during the

experimentation and testing process are described with their principles of operation in

the same order they were tested.

2.1.1 Arduino Uno R3

Arduino is a brand that produces development boards, kits and open source

software for the small and commercial projects. It is used widely around the Globe.

We selected Arduino to meet our low cost requirement with reusability and market

trust as major factors. There are other project boards available in market like

Raspberrypi, STM development kits, TI Cortex M3/M4 boards having more IO’s

than Arduino Uno board we used, but since we don’t require that much large

number or IO’s for our project and this was more cost effective than the rest with

variety of libraries and codes available at its community forums, providing us more

ease to complete this project, Arduino was our foremost choice.

Figure 4| Arduino Uno R3 Board [3]

Looking at the board from the top down, this is an outline of what you will see

(parts of the board you might interact with in the course of normal use are

highlighted):

Figure 5| Arduino Board elaborative model, [4]

Page 28: FINAL YEAR PROJECT THESIS_Full

28

Starting clockwise from the top centre:

Analog Reference pin (orange)

Digital Ground (light green)

Digital Pins 2-13 (green)

Digital Pins 0-1/Serial In/Out - TX/RX (dark green) - These pins cannot

be used for digital I/O (digitalRead and digitalWrite) if you are also using

serial communication (e.g. Serial.begin).

Reset Button - S1 (dark blue)

In-circuit Serial Programmer (blue-green)

Analog In Pins 0-5 (light blue)

Power and Ground Pins (power: orange, grounds: light orange)

External Power Supply In (9-12VDC) - X1 (pink)

Toggles External Power and USB Power (place jumper on two pins closest

to desired supply) - SV1 (purple)

USB (used for uploading sketches to the board and for serial

communication between the board and the computer; can be used to power

the board) (yellow)

Operating Voltage 5V

Input Voltage (recommended) 7-12V

Input Voltage (limit) 6-20V

Digital I/O Pins 14 (of which 6 provide

PWM output)

PWM Digital I/O Pins 6

Analog Input Pins 6

DC Current per I/O Pin 20 mA

DC Current for 3.3V Pin 50 mA

SSFlash Memory 32 KB (ATmega328P)

of which 0.5 KB used

by bootloader

SRAM 2 KB (ATmega328P)

EEPROM 1 KB (ATmega328P)

Clock Speed 16 MHz

Length 68.6 mm

Width 53.4 mm

Weight 25 g

Table 1| General details for ATmega328 (used on most recent boards)

2.1.2 Inertial Measurement unit (IMU)

The MPU-60X0 is the world’s first integrated 6-axis MotionTracking

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 MotionFusion™ output. The MPU-60X0

MotionTracking device, with its 6-axis integration, on-board MotionFusion™,

and run-time calibration firmware, enables manufacturers to eliminate the costly

and complex selection, qualification, and system level integration of discrete

Page 29: FINAL YEAR PROJECT THESIS_Full

29

devices, guaranteeing optimal motion performance for consumers. The MPU-

60X0 is also designed to interface with multiple no inertial digital sensors, such

as pressure sensors, on its auxiliary I2C port.

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.

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

in portable applications with reduced processing requirements for the system

processor. By providing an integrated MotionFusion output, the DMP in the

MPU-60X0 offloads the intensive MotionProcessing 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. 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 I2C 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.

Figure 6| IMU MPU 6050 Circuit Board GY-521 6DOF, [5]

Page 30: FINAL YEAR PROJECT THESIS_Full

30

Figure 7| Configuring IMU with Arduino Uno Fritzing screenshot

2.1.3 DC Gear Motors

DC motors used in the Classic version of the robot were of 2400 rpm

without gearbox and 141 rpm with gearbox with a rated voltages of 6 Volts and

rated no-load current of 1 ampere. When old battery source was replace with a 12

V source, this motor couldn’t give a bearable response and its speed used to shoot-

up and IMU and Arduino got hanged in response. As a remedy to this problem we

used another set of motors explained briefly in the following.

Figure 8|DC motor used for this project without

gearbox.

Figure 9| DC motor with gearbox

DC gear motors have been used in Charm model of this project possess a

maximum of 5000 rpm when run ungeared on no load, while with the gear

assembly the speed is reduced down to 300 rpm at 12 V input and a rated current

of 1.32 ampere. It can provide a max. Torque of 230 mN-m with rated power

supply.

Figure 10| DC Gear motor 12v, 300 rpm

Page 31: FINAL YEAR PROJECT THESIS_Full

31

2.1.4 Batteries

In the early testing phase of the project the battery that was used for the

purpose of supplying power to the robot was of 6V 4500 mAh with weight over

700 grams, that was still in the carrying range but since reduced weight of these

batteries was in favour of our structural stability in the mechanical design so,

compact and rechargeable Li-ion batteries replaced that bulky volume with just a

180 grams weight, making the robot more compact.

With these 3-cell 4.0 Ah batteries with each cell contributing 1.5 A, the

robot can be powered for over 4 hours, with nominal loads of 700 ~ 1000 grams.

Figure 11| GEB Cells used for this project.

2.1.5 H-Bridge DC motor Driver

For a DC motor to operate both forward and backward we have to use some

bridged switching circuitry to operate motor in either direction. In the early testing

phase of the project a bridge circuitry consisting of LM 3904 and LM3906 bipolar

transistor for the purpose of switching because that circuit was capable to provide

1A load current and +3.7V and -3.8V as output voltages.

Figure 12| H bridge using 3904 and 3906

Since the output voltages were not 5V as expected and the sideline drops

were greater so another H-bridge was utilized consisting of L293 IC, but it didn’t

solve the problem.

Page 32: FINAL YEAR PROJECT THESIS_Full

32

Figure 13| L293D based H-Bridge, [6]

Finally, a dual H bridge readily available in the market was utilized and

the problem we were experiencing is solved as this H- bridge is capable of

providing +5 and -5 volts with a maximum of 2.5 A as load current. Moreover,

this Bridge circuit module is capable of driving two motors simultaneous with a

single module based upon L298 IC.

Figure 14| L298n IC with pin

description

Figure 15| L298 IC based dual-H-

Bridge Module, [7]

2.1.6 Bluetooth Module HC-05

Bluetooth Module HC-05 features a Bluetooth TM 2.0 Technology. This

module has been used to provide a remote monitoring of the behaviour of the

Robot’s pitch angle and for the controlled locomotion of the robot (to be featured

in future).

Figure 16| HC_05 Bluetooth Module.

2.1.7 Real-time PID Tuner

This tuner consists of three variable resistors to adjust the gains Kp, Ki ,

and Kd respectively (from top to bottom). This tuning circuit basically adjusts the

gains generated by the Arduino corresponding to the load requirements of the tilted

robot and adds more flexibility to the adjustment modes.

Page 33: FINAL YEAR PROJECT THESIS_Full

33

Figure 17| PID Tuning Circuitry in current model

2.2 Software

2.2.1 Fritzing

Fritzing is an open source software initiative to support designers and

artists ready to move from physical prototyping to actual product. It was developed

at the University Of Applied Sciences Of Potsdam.

Figure 18| Fritzing trademark logo

The software is created in the spirit of the Processing programming

language and the Arduino microcontroller and allows a designer, artist, researcher,

or hobbyist to document their Arduino-based prototype and create a PCB layout

for manufacturing. The associated website helps users share and discuss drafts and

experiences as well as to reduce manufacturing costs.

Figure 19| Circuit representation in fritzing, a screenshot image

Fritzing can be seen as an electronic design automation (EDA) tool for

non-engineers: the input metaphor is inspired by the environment of designers (the

breadboard-based prototype), the output is offering nearly no options and is

Page 34: FINAL YEAR PROJECT THESIS_Full

34

focused on accessible means of production. As of December 2, 2014 Fritzing has

made a code view option, where one can modify code and upload it directly to an

Arduino device

2.2.2 Proteus 8.2

The ISIS and ARES modules share a common database (CDB) which

contains information about all the parts and elements in the project. Parts represent

the physical components on the PCB whilst elements represent the logical

components on the schematic.. The upshot of all this is that changes to one element

(e.g PACKAGE property) of a multi-element part can now be reflected to the other

elements automatically whilst changes to the part (in ARES) can be reflected to

all the elements

Proteus 8 stores the design (DSN), layout (LYT) and common database in

a single project file (PDSPRJ) which can also contain a VSM Studio (firmware)

project and the associated source code files.

Figure 20| Screen Shot to illustrate the workspace of Proteus

8.2

2.2.2.1 VSM Studio

As with ISIS and ARES, the VSM Studio IDE is now an integral part

of the single Proteus application. This has the following benefits:

Firmware is automatically loaded into the target processor(s) after

a successful compile.

The new project wizard can both place and wire up basic

connections (power, reset etc.) for the chosen target processor

Debugging can take place from within *either* the IDE or the

schematic.

Additionally, Proteus 8 introduces the concept of 'Active Popups'.

These are regions of the schematic (e.g. LCD display, or processor pins) that

we wish to see whilst debugging the code.

Co

mp

on

ents

bar

Working

boundary

Par

ts/L

ibra

ry b

row

ser

Simulation Panel

Modes Panel (simulation, PCB Design, 3D Viewer, and VSM

)

Page 35: FINAL YEAR PROJECT THESIS_Full

35

2.2.2.2 Live Net-listing

Proteus 8 maintains a 'live' netlist enabling changes made on the

schematic to be reflected in ARES, Design explorer and the Bill of Materials

in real time. Changes to the PCB are shown in such a way that they can still

be rejected before components and tracking are actually removed from the

layout

2.2.2.3 3D Viewer

A similar live update mechanism now operates between ARES and

the 3D Viewer such that changes to the PCB are automatically reflected into

the 3D view.

2.2.2.4 Bill of Materials

Proteus 8 includes a completely new Bill of Materials module. This

operates in its own application window with a WYSIWYG view of the BOM.

This BOM is exportable to Excel or PDF files.

2.2.2.5 Selection of Proteus 8.2

The Proteus 8.2 release expanded on Proteus V8.1 with a strong focus

on library parts in both the schematic and the layout modules. Our other main

development thrust was on documentation and report generation with the

introduction of a new module in Project Notes and a major rework of the Bill

of Materials module. On the Proteus VSM front, we have been working hard

on the Arduino product as well as introducing support for new Atmel®,

Arduino™, AVR®, Cortex™-M3, PIC16 and PIC18 processor variants.

2.2.3 Autodesk Inventor Professional 2016

Autodesk inventor is world renowned professional software to design

mechanical, civil, architecture, electrical structures in 3D form with the facility to

simulate their 3D mechanical design and custom animation studio.

Figure 21| Autodesk prototyping experience, [8]

Page 36: FINAL YEAR PROJECT THESIS_Full

36

2.2.3.1 Design without boundaries

With a broad set of easy-to-use, interoperable design tools, your

engineering design teams can work more creatively and manage their processes

more efficiently. As ideas move from concept to engineering, the need to remodel

concepts is minimized as engineers can work from conceptual designs. And with

everyone using a common set of tools, you improve collaboration across all phases

of development.

2.2.3.2 Integrated electrical and mechanical design

Product Design Suite helps mainstream manufacturers realize the full

benefits of mechatronics by enabling them to quickly create and easily maintain a

single, digital model. This model connects mechanical and electrical teams by

bringing together design data from all phases of development for use across all

disciplines. Because the digital model simulates the complete product, engineers

can better visualize, optimize, and manage their design before producing a

physical prototype.

Professional’s Remarks about Autodesk

“It’s allowed us to build bigger, faster, higher output machines and they’ve helped us

to keep on the cutting edge and build the best machines in the world right now.”

-Richard Mueller

Executive Vice President/Partner

Osgood Industries.

Figure 22| Self Balancing Robot’s Ready-to-go design with custom IBL

Environment, screenshot. Image.

Workspace

Taskbar

Page 37: FINAL YEAR PROJECT THESIS_Full

37

2.3 Mechanical Structure

2.3.1 Earlier Design Stages (Classic/ ver. 1.0)

The Robot has to look smarter, compact, easy to be configured and easier

to re-assemble while transporting for some exhibition. Moreover, it should have a

very economical, balanced weight and stable structure as well. In very early stage

of the project designing two proposed mechanical structures were designed using

Autodesk Inventor Professional. One with more stable and low height design could

have provide a very elegant look, but it was relatively difficult to assemble and

that caused us to design another version with a ready to go assembling feature, but

that had got some extra height as well, which can cause stability issues as moment

of inertia increases with the height while the lower end motors acting as pivots. So

we have to compromise between the two, we opted the stability over re-assembling

feature to ease up the success towards our main goal.

Figure 23| Design with more stability and relatively lower Center of Gravity.

Figure 24| The Ready-to-go Assembly design, with more elegance and simplicity.

The first design was implemented using the toy material as the base and the

following motors as the driving unit of the Robot but, due to lack of some high

tech mechanical equipment and some economic issues that model couldn’t be

Page 38: FINAL YEAR PROJECT THESIS_Full

38

fabricated as per requirement. It has got an out-centered Center of Gravity and

mechanical play or (sag) in the low cost plastic geared DC Motors which was

causing unbearable technical problems to the Robot. Which ultimately urged us to

make a third effort to re-think and remodel the whole structure with high durability

and high precision in CG, working on the following design principle.

Figure 25| Design Principle for the Structure Designing Process

2.3.2 Final Design (Charm Design /ver. 2.0)

This design version has to be made considering all the failures and set-

backs faced during the implementation of the previous version, i.e. High Center

of Gravity, low disturbance immunity, low weight handling capacity and out-

Centered Weight etc.

2.3.2.1 Design Considerations

Following were the design consideration that were incorporated while

designing the new structure.

To design a structure which would have center of gravity lower than the

line of action of torque so that the natural stability of the robot is

increased.

The choice of the material should be based upon its economical and

durable characteristics.

The supporting structure should be strong enough to handle the weight of

the base and top plates including the loads weighing a minimum of 3kg.

The selection of motor should be done according to the height of the

Robot and the net weight of the material of the final assembly, to provide

sufficient amount of torque to the Robot for the purpose of restoring its

initial coordinates.

The Tires should be modified in-order to increase the road grip and to

support the new structure.

Considering the above design considerations the final design have been prepared

and simulated for the durability under specific loads and jerk frequencies.

2.3.2.2 Designing Process and Simulation Results

New designs that were made are follows:

Page 39: FINAL YEAR PROJECT THESIS_Full

39

Figure 26|3D Model of newly purchased motors

Figure 27| Beta Version of the Charm Design using ABS plastic

Figure 28| Acrylic Sheet Deign with tinted acrylic sheet (unavailable in market)

Figure 29| Final Version "Charm" of the SBR, with Transparent Acrylic Sheet,

and Arduino Boards on top

Page 40: FINAL YEAR PROJECT THESIS_Full

40

This final version could not be implemented as it is due to some further

improvements suggested to further lowering the CG which otherwise is located on

the lower middle side of the base plate. So the full and final “Charm version” in

implemented form is as under.

Figure 30| The Front view of the Implemented Charm version of SBR

Page 41: FINAL YEAR PROJECT THESIS_Full

41

Chapter 3 Hardware Implementation

Contents

Designs

Features

Flaws

Solutions

Working

Page 42: FINAL YEAR PROJECT THESIS_Full

42

[Intentionally kept Blank]

Page 43: FINAL YEAR PROJECT THESIS_Full

43

Chapter 3

Hardware Implementation

3.1 Implemented Designs

The following couple of designs have been implemented till the current standing

structure of the Self-Balancing Robot.

3.1.1 Classic Structure of SBR

The Robot’s structural design means a lot to the stability of the robot from

material, weight and height perspective. There were two implementations that we

made, first one was implemented using the toy structure and small sized, low speed,

high torque DC motors which had plastic gears. That model had three levels, so

making the net height of greater than 8 inches as a whole. Which raised the CG level

of the Robot quite higher than expected. The Stability with that model could not be

achieved as remarkably as was required, that’s why the current model of the Robot

was restructured.

Figure 31| Classic Design with minimum structural cost of 300 PKR

3.1.2 Charm Design of SBR

The current structure is made using acrylic sheet, as base plates and aluminum

sheet as supporting structure along with M3 screws of 2” length. This new structure is

based upon high torque, relatively higher rotational speed, and metallic gearbox. This

structure has brought more stability to our robot.

Figure 32| 3D Model of the current robotic structure, with low CG.

Page 44: FINAL YEAR PROJECT THESIS_Full

44

3.2 Features

3.2.1 Classic Design of SBR

Classic design of SBR possessed the following features;

Low cost structure

High top plate

Sneaky small size

Linear plus angular displacement measurement using accelerometer and

homemade-rotary encoder.

Pitch Angle measurement using Kalman Filter, with a tolerance of +/-5o

Autonomous Unit with Dedicated Battery –bank 0f 1730 mAh.

3.2.2 Charm Design of SBR

Charm deign of SBR contains the following features;

Elegant looks

Low Top plate

Low Center of Gravity

High durability and dependability

More stable than its predecessor

Pitch angle measurement using Digital Motion Processor unit built in the

IMU.

Runtime PID tuning Circuitry for manual tuning

Autonomous Unit with a battery span over 1hour.

Quick ON/ OFF Manual/ On OFF

Less Jerk Sensitive.

Runtime Graphing of Pitch angle display over Android mobile using

Bluetooth Module HC-05.

3.3 Flaws in Classic ver. of SBR.

The Classic version has certain setbacks over the new design “Charm” as stated

in the following;

Higher Center of Gravity

Turbulent random data generation from IMU

I2C Protocol and Arduino got hanged and motor used to start rotating at full

speed

IMU used to turn-off and noise is generated instead.

Vibrations in the whole structure due to measurable mechanical play in the

plastic gears of the dc-motors used earlier.

Less Durable Structure towards high loads.

Relatively Low torque and low speed as compared to the current design.

Autonomous power supply was adding extra burden to the motors, weakening

the recovery mode.

Structure couldn’t actually get stabilized despite using rotary encoders for the

angular displacement measurements.

PID Tuning was done using classic way of tuning (by hit and trial method).

Page 45: FINAL YEAR PROJECT THESIS_Full

45

3.4 Remedies to the flaws in Charm ver. of SBR,

The following remedies helped eradicating the flaws in the Charm Deign version

of the self-balancing robot;

Re-Structuring the whole model such as to have components with most weight

at the lower base plate, such as new DC-Motors (Zheng ZBG37RG) and the

Arduino Uno board with all top level plates’ weight converging on to a single

line of action of weight to make CG lower than it was in Classic version.

Data coming out of IMU was having a communication protocol problem using

I2C, which is changed to SPI mode now.

I2C protocol in the IMU used with 10k pull-up resistors at SDA and SCL

terminals, which resulted no good, then Opto-isolators were used with 3-4

design modifications as initially it was causing electro-magnetic nose to the

power signal of motoring system. It worked fine after those modifications with

Opto-isolators.

This problem occurred due to the reason that the 2 PID loops were both

operated in the different time space causing a synchronization problem to the

Arduino (controller) and due to that miss-match that problem was arising.

Which is resolved by simultaneous operation of both PID loops in parallel

fashion which resulted in same transition time between the two PID loops.

Tightening the plates firmly with the check-nuts (above and below) with the

replacement of old plastic geared motors with the metallic geared high power

DC motors with more control over speeds has almost eradicated those

vibrations.

Thick Acrylic Sheets of 5 mm have increased the load bearing ability of the

Robot to about 200% of what could be bearable in the Classic version. (roughly

2.5 kg)

New Motors has increased the restoring power due to increase in the rated

torque and top-speed as compared with the Classic version.

The Supply (although now has reduced the timing) can now be accommodated

easily with the increased load carrying and lifting ability of the SBR, due to

high nominal torque motors.

Structure can now be tuned so as to stabilize itself over medium level of

external hindrance caused to the stability of the robot and restores its

equilibrium state almost immediately due to low settling time.

PID Tuning is done using re-calculated Mathematical model and tuning that

model in Matlab, moreover, it can be tuned further using manual tuning

circuitry mounted aside the top-plate for even smoother stabilization. Dual PID

balancing was used, first one for the angle balancing and the second one for

the position restoring which was done using homemade quadrature rotary

encoder (made by ourselves) giving away 16 steps of transitions while

completing one cycle of rotation at the tires which are not enough but that

helped us saving position in the earlier version (not utilized in the charm

version, at the moment).

By-pass Capacitors have been added in parallel with the output ports of the

LM-298 motor driver to smoothen the edges of the PWM generated by the

Arduino to reduce the possibility of drawing high current in sagging modes.

Although the cost of the new version of the SBR is quite higher than its

predecessor and its ability to sense the linear and angular motion has been

withdrawn from the current model, yet it can stabilize itself more quickly than the

Page 46: FINAL YEAR PROJECT THESIS_Full

46

previous model due to a better structure, smoother and more dependable PID

motor control, which was our prime target.

3.5 Working of the Charm ver. of SBR

The Working of the Charm version of SBR consists of the following stages;

Sensing the Coordinates

Communicating co-ordinates changes with the Central Processing Unit

(Arduino Uno Board)

Generating controlled PWM in response of the observed co-ordinate

changings.

Distributing the smoothened PWM over the two motors using the L298

Module (Dual-Full Bridge Rectifier).

Re-monitoring the co-ordinates changes as compared to the reference state,

in-order to get stabilized after cancellation of the effect of external turbulence

or disturbance.

Working details are briefly described in the following.

When the Robot is switched ON the first step that is taken by the Arduino is that

the initial coordinates are fetched to match with the reference coordinates set inside

the controller. This communication is done using I2C protocol which is operated at

400 kHz using Opto-isolators and gives a rush of coordinates with as much as 6 digit

precision after the decimal point.

The bulk of data is difficult to respond to, as the decisions taken by the controller

are not that rapid and if it is assumed to be possible even then it would have raised the

net work load of motor to 100%, which is not at all feasible. So a filter is used in-order

to take the running sum of these values at a rate of 100 kHz and then take their average

to impose one decision for the trend observed in data on the motoring system.

The motor driver is provided with a PWM signal from the Arduino as a result of

detection of the direction of motion from the difference of coordinates obtained from

the IMU. This PWM signal contains the information of on-time and off-times of motor

in the form of varying duty. According to this variation motor is turned ON/ OFF with

the help of L298m dual-H-Bridge module in forward or backward direction as per

required.

When the rotation has taken place, the coordinates of the IMU, in the meanwhile,

have also been updated, so the Arduino re-processes upon those newly obtained

coordinates as previously explained, and slowly slows down the duty in the PWM

signal as over-ruled by the PID Controller, implemented to the pitch angle and the

position of the robot separately, until it completely vanishes down to 0 duty.

Coordinates

[IMU]

Comparator

[Arduino]

PWM

[Arduino]

Motor Driver [L298]

Motoring

[Zheng Motors]

Page 47: FINAL YEAR PROJECT THESIS_Full

47

Chapter 4 Algorithm and Coding

Contents

Algorithm

Step-wise Elaboration

Applications

Recommendations for

Future Work

Page 48: FINAL YEAR PROJECT THESIS_Full

48

[Intentionally kept Blank]

Page 49: FINAL YEAR PROJECT THESIS_Full

49

Chapter 4 Algorithm and Coding

4.1 Algorithm

Algorithm is the basic approach to describe the process flow of a program or a

logic implementation. It includes a high level approach, close to human understanding,

to describe the processes involved in a Project or a Program in the order they have to

be executed in the proposed project or program. This approach is commonly called,

“Flow Chart or Process Flow Diagram of a Project or a Program.”

The process flow diagram of our project is as follows;

Initialization of

Communication

Protocols

Page 50: FINAL YEAR PROJECT THESIS_Full

50

4.2 Step-wise Implementation

4.2.1 I2C Initialize

// initialize device

Serial.println(F("Initializing I2C devices..."));

mpu.initialize();

4.2.2 Serial Initialization

// initialize serial communication

Serial.begin(115200);

4.2.3 If (I2C & Serial initialize)

// verify connection

Serial.println(F("Testing device connections..."));

Serial.println(mpu.testConnection() ? F("MPU6050 connection

successful") : F("MPU6050 connection failed"));

// wait for ready

Serial.println(F("\nSend any character to begin DMP programming and

demo: "));

// while (Serial.available() && Serial.read()); // empty buffer

// while (!Serial.available()); // wait for data

// while (Serial.available() && Serial.read()); // empty buffer again

4.2.4 Initialize DMP

// load and configure the DMP

Serial.println(F("Initializing DMP..."));

devStatus = mpu.dmpInitialize();

// supply your own gyro offsets here, scaled for min sensitivity

mpu.setXGyroOffset(220);

mpu.setYGyroOffset(76);

mpu.setZGyroOffset(-85);

mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

// make sure it worked (returns 0 if so)

if (devStatus == 0)

{

// turn on the DMP, now that it's ready

Serial.println(F("Enabling DMP..."));

mpu.setDMPEnabled(true);

// enable Arduino interrupt detection

Page 51: FINAL YEAR PROJECT THESIS_Full

51

Serial.println(F("Enabling interrupt detection (Arduino

external interrupt 0)..."));

attachInterrupt(0, dmpDataReady, RISING);

mpuIntStatus = mpu.getIntStatus();

// set our DMP Ready flag so the main loop() function knows

it's okay to use it

Serial.println(F("DMP ready! Waiting for first interrupt..."));

dmpReady = true;

// get expected DMP packet size for later comparison

packetSize = mpu.dmpGetFIFOPacketSize();

} else

{

// ERROR!

// 1 = initial memory load failed

// 2 = DMP configuration updates failed

// (if it's going to break, usually the code will be 1)

Serial.print(F("DMP Initialization failed (code "));

Serial.print(devStatus);

Serial.println(F(")"));

}

// if programming failed, don't try to do anything

if (!dmpReady) return;

4.2.5 While Loop

while (!mpuInterrupt && fifoCount < packetSize)

{

consKp=analogRead(1)*0.04887585;

consKi=analogRead(2)*0.1955*2;

consKd=analogRead(3)*5/1023.0;

if(c==1)

if(abs(ypr[1])>=0.1)

{

Serial.print( (String)"A0 " + (bat_average*100) + "\n" );

Serial.print( (String)"A1 " + (ypr[1]*100+1000) + "\n" );

Input= ypr[1];

myPID.SetTunings(consKp, consKi, consKd);

myPID.Compute();

if(Output>0)

{

digitalWrite(13, 1);

forward12();

int frwd=(Output+60);

analogWrite(6,frwd);

analogWrite(5,frwd);

}

Page 52: FINAL YEAR PROJECT THESIS_Full

52

else if(Output<0)

{

digitalWrite(13, 1);

backward12();

neg = (-1*Output+60);

analogWrite(6,(neg));

analogWrite(5,(neg));

}

c=0;

}

else

{ digitalWrite(13, 0);

stop12();

Serial.print( (String)"A0 " + (bat_average*100) + "\n" );

Serial.print( (String)"A1 " + (ypr[1]*100+1000) + "\n" );

c=0;

}

}

4.2.6 Termination

// reset interrupt flag and get INT_STATUS byte

mpuInterrupt = false;

mpuIntStatus = mpu.getIntStatus();

// get current FIFO count

fifoCount = mpu.getFIFOCount();

// check for overflow (this should never happen unless our code is

too inefficient)

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

// reset so we can continue cleanly

mpu.resetFIFO();

Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should

happen frequently)

} else if (mpuIntStatus & 0x02) {

// wait for correct available data length, should be a VERY

short wait

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

// read a packet from FIFO

mpu.getFIFOBytes(fifoBuffer, packetSize);

// track FIFO count here in case there is > 1 packet available

// (this lets us immediately read more without waiting for an

interrupt)

fifoCount -= packetSize;

Page 53: FINAL YEAR PROJECT THESIS_Full

53

4.3 Applications

The utility of a project is defined by the type and value of the applications

associated to it either directly or indirectly. Our project is a very fine example of real-

time PID based control system implementation by observing the live effect of manual

PID tuning. It provides stable base for several stability based applications, some of

them are listed below;

Surveillance Robot, with a camera, an ultra-sonic sensor, a heat-sensor, a laser

tracker, a RADAR , a LADAR or a SONAR system mounted on the top plate

of SBR.

Clearance Robot, with cutting tools like; Pliers, wire-cutters, or heat-gun

mounted on the top plate of SBR with a robotic arm.

Automated Target Destruction Robot, with a Sentry Gun, a Missile Launcher,

a Fire-Extinguisher mounted onto the top plate of SBR.

Stabilized Video Recording Robot, with a movie-camera or a camcorder

mounted on top plate of SBR.

Stable base for the launching of small satellites from remote places such as

Mars, Moon etc, where low gravity could make it real difficult for a normal

launcher to stabilize its position for the targeted trajectory.

A Serving Robot in a restaurant, with its top plate expanded to carry dishes

upon its surface.

Horizontal Distance/ Area Measuring Robot, with its accelerometer recording

the coordinates in a log file and then adding the x-coordinates and y-

coordinates on runtime for distance and afterwards for area calculations.

Level Sensing Robot, with its 3-axis accelerometer acting as a source of hurdle

coordinates by calculating the sudden z-axis differences and giving either a log

file or an alarm on the basis of that decision. Etc…

Its applications can be extended into enormous examples where there is a

requirement of stable base.

4.4 Recommendations for Future Work on SBR

In order to provide assistance to the persons who would like to remake or extend

this work, the following things are recommended for them to successfully implement

their future goals with SBR.

Height of the Robot plays a key role towards the stability of the SBR,

increasing the height unnecessarily is strongly not recommended.

Achieving low Centre of Gravity is the ultimate goal that may or may not

depend upon the actual height of the robot depending upon the type of structure

designed.

Keeping the Centre of Gravity lower than the axis of torque Tm, helps

improving natural stability of the system and hence reducing the work-load of

the motors and improving its ability of restoring the equilibrium position for

larger magnitudes of disturbances.

Structures that would most likely to provide a stable structure require

conscious efforts and professional experience to implement the structure as it

was designed and most recommended approach is to design those structural

parts on a precise machine such as CNC Lathe Machine.

Page 54: FINAL YEAR PROJECT THESIS_Full

54

Motors with plastic gears are not recommended for such type of robots as

mechanical losses such as frictional losses in case of fast transitions of speeds

and direction of rotation cause excessive heat losses that cause physical

damage to the teeth of the these plastic gears which introduce slip in the

motoring action and make it more difficult to recover to its equilibrium state.

Since there are rapid transitions in the PWM signal generated by the Arduino

Controller Board, so those square waved have very sharp edges at transition

points which may can cause harmonic interference to the motoring system and

may result in IMU turn-off or a halted status of Arduino or continuously

vibrating motors due to extra peaks generated by those harmonic contents. So

coupling capacitors are recommended at the output terminals of the dual H-

bridge L298 for smooth working of the motors and the control system.

Quadrature Rotary Encoders are recommended for restoring original

coordinates in the real plane as they can be used to count the degrees of rotation

that has occurred during the internal or external disturbance in the coordinates,

and using those numbers original position can be re-gained with a precision

inversely proportional to twice the number of slits in the rotary encoder (bright

+ dark fringes).

While placing the components on the plates the symmetry of the weight should

be kept in mind to meet the line of action of weight so as to maintain balance

between the loads of both sides.

Building a prototype is strongly recommended, as the process of Engineering

Design.

Divide and rule works everywhere, so divide the work equally in a

synchronised fashion to take rapid and effective results.

Page 55: FINAL YEAR PROJECT THESIS_Full

1

References

[1] MA-2010, “Motoman,” Yashkawa Robotics, [Online]. Available:

https://www.motoman.com. [Accessed 2014].

[2] iRobot, “PackBot 510,” iRobot, 2010. [Online]. Available:

https://www.irobot.com. [Accessed 2015].

[3] spksoft, “SPKSoft,” [Online]. Available: http://spksoft.co.in. [Accessed

December 2015].

[4] Arduino, “Arduino Uno R3,” Arduino, November 2016. [Online].

Available: https://www.arduino.cc.

[5] JJRobots, “JJRobots,” [Online]. Available: https://jjrobots.com. [Accessed

November 2015].

[6] P.-N. J. Labs, “PNjunctionLabs,” PNJunctionLabs, [Online]. Available:

https://pnjunctionlabs.com. [Accessed December 2015].

[7] Vetco, “Vetco.net,” [Online]. Available: https://www.vetco.net. [Accessed

December 2015].

[8] Autodesk, “Inventor Professional 2016,” Autodesk, 2016. [Online].

Available: https://www.autodesk.com/. [Accessed MAy 2015].

[9] K. Electronics, “Zheng ElectroMotors,” Kysanelectronics.com, US, 2011.

[10] Y. Korren, Robotics for Engineers, Israel: McGraw-Hill Company, 1985.

[11] Ronald Siegwart and Illah R. Nourbakhsh, Introduction to Autonomous

Mobile Robots, Massachusetts: A Bradford Book, The MIT Press,

Cambridge Massachusetts, London, England, 2004.

[12] A. Hughes, Electric Motors and Drives, Oxford, UK: Elsevier, 2006.

[13] Mr. Andrew Blake, Dr. Grahm Winstanley, Dr. William Wilkinson,

“Deriving Diplacement from a 3-Axis Accelerometer,” University of

Birghton CMIS, Watts Building, Lewes Road, Brighton, vol. 1, p. 6, 2010.

[14] R. C. Ooi, “Balancing a two wheeled Autonomous Robot,” The University

of Western Autralia, School of MEchanicla Engineering, NedLands, WA,

2003.

[15] F. T. Christian Sundin, “Autonomous balancing Robot,” Department of

Signals and Systems, Chalmers University of Technology, Gotebrog,

Sweden, 2012.

[16] N. G. P. N. Brian Bonafilia, “Self-Balancing Two-Wheeled Robot,”

Imperical College, London, London, UK, 2012.

[17] K. A. O. I. A. H. M. Q. A. Umar Adeel, “Autonomous Dual Wheel Robot

based on Microcontroller,” Journal of basic and apllied scientific

research, vol. 1, no. ISSN-2090-4304, p. 6, 2013.

[18] M. B. M. Ali, “Development of Self-Balancing Platform on Mobile Robot

using PID Controller,” Faculty of Electrical and Electronic Engineering,

Universiti tun Hussein Onn Malaysia, Malay, Malaysia, June,2013.

[19] A. Castro, “Modeling and Dynamic Analysis of Two Wheeled Inverted

Pendulum,” George W. Woodruff School of Mechanical Engineering,

Georgia Institue of Techonology, Georgia, US, Aug, 2012.

Page 56: FINAL YEAR PROJECT THESIS_Full

2

[20] H. F. a. G. T. N. Bylund, “A Design Process for the Complex Mechanical

Structures Using Property Based Models, with Applications to Car

Bodies,” in International Design Conference,Design 2002, Dubrovnik,

May, 14-17, 2002.

[21] Maker_Studio, “Maker Studio,” Maker Studio, December 2014. [Online].

Available: https://www.indiegogo.com/projects/balanbot-best-arduino-

self-balancing-robot-ever#/. [Accessed November 2015].

[22] MyFirstRobot, “myfirstDrone,” [Online]. Available:

https://www.youtube.com/watch?v=LtocGBngSrA. [Accessed 2015].

[23] S. Exchange, “Robotics.StackExchange,” [Online]. Available:

http://robotics.stackexchange.com/questions/167/what-are-good-

strategies-for-tuning-pid-loops. [Accessed February 2016].

[24] Ufactory, “instructables,” Ufactory, [Online]. Available:

http://www.instructables.com/id/2-Wheel-Self-Balancing-Robot-by-using-

Arduino-and-/?ALLSTEPS. [Accessed February 2016].

[25] Geekmom, “Geek Mom Projects,” Geekmom, [Online]. Available:

http://www.geekmomprojects.com/gyroscopes-and-accelerometers-on-a-

chip/. [Accessed January 2016].

[26] Geekmom, “Geek Mom Projects,” GeekMom, [Online]. Available:

http://www.geekmomprojects.com/the-halfway-a-self-balancing-scooter/.

[Accessed December 2015].

[27] Roboremo, “Robo Remo,” Roboremo, [Online]. Available:

http://www.roboremo.com/esp8266-arduino-adapter.html. [Accessed

April 2016].

Page 57: FINAL YEAR PROJECT THESIS_Full

3

Appendices Contents

Appendix A [CODE]

Appendix B

[DRAWINGS]

Appendix C

[Motor Stats]

Page 58: FINAL YEAR PROJECT THESIS_Full

4

[Intentionally kept Blank]

Page 59: FINAL YEAR PROJECT THESIS_Full

1

Appendix A

Robot Firmware

#include <PID_v1.h>

#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.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 SparkFun breakout and InvenSense

evaluation board)

// AD0 high = 0x69

MPU6050 mpu;

//MPU6050 mpu(0x69); // <-- use for AD0 high

// pitch/roll angles (in degrees) calculated from the quaternions

coming

// from the FIFO. Note this also requires gravity vector calculations.

// Also note that yaw/pitch/roll angles suffer from gimbal lock (for

// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)

#define OUTPUT_READABLE_YAWPITCHROLL

bool c=0;

// MPU control/status vars

bool dmpReady = false; // set true if DMP init was successful

uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU

uint8_t devStatus; // return status after each device operation (0

= success, !0 = error)

uint16_t packetSize; // expected DMP packet size (default is 42

bytes)

uint16_t fifoCount; // count of all bytes currently in FIFO

uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars

Quaternion q; // [w, x, y, z] quaternion container

VectorInt16 aa; // [x, y, z] accel sensor

measurements

VectorInt16 aaReal; // [x, y, z] gravity-free accel

sensor measurements

VectorInt16 aaWorld; // [x, y, z] world-frame accel

sensor measurements

Page 60: FINAL YEAR PROJECT THESIS_Full

2

VectorFloat gravity; // [x, y, z] gravity vector

float euler[3]; // [psi, theta, phi] Euler angle container

float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll

container and gravity vector

//smooting variables

const int numReadings = 30;

int readings[numReadings]; // the readings from the analog input

int readIndex = 0; // the index of the current reading

int total = 0; // the running total

float bat_average = 0; // the average

float bal_point=0;

double bal_average=0;

int bal_check=0;

// ================================================================

// === motor direction and speed controls ===

// ================================================================

bool D11=0,D12=0,D21=0,D22=0;

int neg;

// ================================================================

// === PID vairables ===

// ================================================================

//Define Variables we'll be connecting to

double Setpoint=0, Input, Output;

//Define the aggressive and conservative Tuning Parameters

double aggKp=20, aggKi=30, aggKd=.8;

//double consKp=1, consKi=0.05, consKd=0.25;

//double consKp=9, consKi=20, consKd=.0625;

double consKp=11.73, consKi=4.49, consKd=.41;

//Specify the links and initial tuning parameters

PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

// ================================================================

// === INTERRUPT DETECTION ROUTINE ===

// ================================================================

volatile bool mpuInterrupt = false; // indicates whether MPU

interrupt pin has gone high

void dmpDataReady()

{

mpuInterrupt = true;

}

Page 61: FINAL YEAR PROJECT THESIS_Full

3

// ================================================================

// === MOTOR FUNCTIONS ===

// ================================================================

void forward1()

{

digitalWrite(9,1);

digitalWrite(3,0);

}

void forward2()

{

digitalWrite(7,1);

digitalWrite(8,0);

}

void backward1()

{

digitalWrite(9,0);

digitalWrite(3,1);

}

void backward2()

{

digitalWrite(7,0);

digitalWrite(8,1);

}

void forward12()

{

digitalWrite(9,1);

digitalWrite(3,0);

digitalWrite(7,1);

digitalWrite(8,0);

}

void backward12()

{

digitalWrite(9,0);

digitalWrite(3,1);

digitalWrite(7,0);

digitalWrite(8,1);

}

void stop12()

{

digitalWrite(9,1);

digitalWrite(7,1);

digitalWrite(3,1);

digitalWrite(8,1);

analogWrite(6,0);

Page 62: FINAL YEAR PROJECT THESIS_Full

4

analogWrite(5,0);

}

// ================================================================

// === INITIAL SETUP ===

// ================================================================

void setup() {

// join I2C bus (I2Cdev library doesn't do this automatically)

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE

Wire.begin();

TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)

#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE

Fastwire::setup(400, true);

#endif

// initialize serial communication

Serial.begin(115200);

while (!Serial);

// initialize device

Serial.println(F("Initializing I2C devices..."));

mpu.initialize();

// verify connection

Serial.println(F("Testing device connections..."));

Serial.println(mpu.testConnection() ? F("MPU6050 connection

successful") : F("MPU6050 connection failed"));

// wait for ready

Serial.println(F("\nSend any character to begin DMP programming and

demo: "));

// while (Serial.available() && Serial.read()); // empty buffer

// while (!Serial.available()); // wait for data

// while (Serial.available() && Serial.read()); // empty buffer

again

// load and configure the DMP

Serial.println(F("Initializing DMP..."));

devStatus = mpu.dmpInitialize();

// supply your own gyro offsets here, scaled for min sensitivity

mpu.setXGyroOffset(220);

mpu.setYGyroOffset(76);

mpu.setZGyroOffset(-85);

mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

// make sure it worked (returns 0 if so)

if (devStatus == 0)

Page 63: FINAL YEAR PROJECT THESIS_Full

5

{

// turn on the DMP, now that it's ready

Serial.println(F("Enabling DMP..."));

mpu.setDMPEnabled(true);

// enable Arduino interrupt detection

Serial.println(F("Enabling interrupt detection (Arduino

external interrupt 0)..."));

attachInterrupt(0, dmpDataReady, RISING);

mpuIntStatus = mpu.getIntStatus();

// set our DMP Ready flag so the main loop() function knows

it's okay to use it

Serial.println(F("DMP ready! Waiting for first interrupt..."));

dmpReady = true;

// get expected DMP packet size for later comparison

packetSize = mpu.dmpGetFIFOPacketSize();

} else

{

// ERROR!

// 1 = initial memory load failed

// 2 = DMP configuration updates failed

// (if it's going to break, usually the code will be 1)

Serial.print(F("DMP Initialization failed (code "));

Serial.print(devStatus);

Serial.println(F(")"));

}

for (int thisReading = 0; thisReading < numReadings; thisReading++)

readings[thisReading] = 0;

pinMode(13,OUTPUT); // configure LED for output

pinMode(9, OUTPUT); // motor1 D11

pinMode(3, OUTPUT); // motor1 D12

pinMode(7, OUTPUT); // motor2 D21

pinMode(8, OUTPUT); // motor2 D22

// PID MOde

myPID.SetOutputLimits(-190,190);

myPID.SetSampleTime(9);

myPID.SetMode(AUTOMATIC);

// delay(10000);

}

// ================================================================

// === MAIN PROGRAM LOOP ===

// ================================================================

void loop()

{

Page 64: FINAL YEAR PROJECT THESIS_Full

6

// if programming failed, don't try to do anything

if (!dmpReady) return;

// wait for MPU interrupt or extra packet(s) available

while (!mpuInterrupt && fifoCount < packetSize)

{

consKp=analogRead(1)*0.04887585;

consKi=analogRead(2)*0.1955*2;

consKd=analogRead(3)*5/1023.0;

if(c==1)

if(abs(ypr[1])>=0.1)

{

Serial.print( (String)"A0 " + (bat_average*100) + "\n" );

Serial.print( (String)"A1 " + (ypr[1]*100+1000) + "\n" );

Input= ypr[1];

myPID.SetTunings(consKp, consKi, consKd);

myPID.Compute();

if(Output>0)

{

digitalWrite(13, 1);

forward12();

int frwd=(Output+60);

analogWrite(6,frwd);

analogWrite(5,frwd);

}

else if(Output<0)

{

digitalWrite(13, 1);

backward12();

neg = (-1*Output+60);

analogWrite(6,(neg));

analogWrite(5,(neg));

}

c=0;

}

else

{ digitalWrite(13, 0);

stop12();

Serial.print( (String)"A0 " + (bat_average*100) + "\n" );

Serial.print( (String)"A1 " + (ypr[1]*100+1000) + "\n" );

c=0;

}

}

// reset interrupt flag and get INT_STATUS byte

mpuInterrupt = false;

mpuIntStatus = mpu.getIntStatus();

// get current FIFO count

Page 65: FINAL YEAR PROJECT THESIS_Full

7

fifoCount = mpu.getFIFOCount();

// check for overflow (this should never happen unless our code is

too inefficient)

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

// reset so we can continue cleanly

mpu.resetFIFO();

Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should

happen frequently)

} else if (mpuIntStatus & 0x02) {

// wait for correct available data length, should be a VERY

short wait

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

// read a packet from FIFO

mpu.getFIFOBytes(fifoBuffer, packetSize);

// track FIFO count here in case there is > 1 packet available

// (this lets us immediately read more without waiting for an

interrupt)

fifoCount -= packetSize;

/* #ifdef OUTPUT_READABLE_QUATERNION

// display quaternion values in easy matrix form: w x y z

mpu.dmpGetQuaternion(&q, fifoBuffer);

Serial.print("quat\t");

Serial.print(q.w);

Serial.print("\t");

Serial.print(q.x);

Serial.print("\t");

Serial.print(q.y);

Serial.print("\t");

Serial.println(q.z);

#endif

*/

#ifdef OUTPUT_READABLE_YAWPITCHROLL

// display Euler angles in degrees

mpu.dmpGetQuaternion(&q, fifoBuffer);

mpu.dmpGetGravity(&gravity, &q);

mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

// ypr[0] = ypr[0] * 180/M_PI;

ypr[1] = ypr[1] * 180/M_PI-bal_point;

// ypr[2] = ypr[2] * 180/M_PI;

if(bal_check>=30) // Balance point

calculation for removing offset

{

bal_check=0;

Page 66: FINAL YEAR PROJECT THESIS_Full

8

bal_average=bal_average/30;

bal_point=bal_average;

}

bal_average=bal_average+ypr[1];

// Serial.print("ypr\t");

// Serial.print(ypr[0]);

// Serial.print("\t");

// Serial.println(ypr[1]);

// Serial.print("\t");

// Serial.print(ypr[2]);

// if(Serial.available())

// consKi=Serial.parseInt();

total = total - readings[readIndex];

readings[readIndex] = analogRead(0); // read from the

sensor:

total = total + readings[readIndex]; // add the reading

to the total:

readIndex = readIndex + 1; // advance to the

next position in the array:

if (readIndex >= numReadings) // if we're at the

end of the array...

readIndex = 0; // wrap around to the

beginning:

bat_average = total / numReadings; // calculate the

average:

bat_average = bat_average*0.01818543;

c=1;

#endif

}

delay(1);

}

Page 67: FINAL YEAR PROJECT THESIS_Full

i

Appendix B

Technical Data (Drawing sheets) of Robot

Following are the drawing sheets of SBR base-plate, top-plate, motor-supports and

the tightening screws respectively, that were used in this project. Material used for base

and the top plate is 5 mm thick Clear Acrylic Sheet, and 3 mm thick 2 inches wide

Aluminium Strip of length 1 foot.

Page 68: FINAL YEAR PROJECT THESIS_Full

ii

Page 69: FINAL YEAR PROJECT THESIS_Full

iii

Appendix C

Technical Details of PMDC-Gear Motors ZGB37RB

Figure 33| Curtesy KYSAN, Zheng Motors [9]

Page 70: FINAL YEAR PROJECT THESIS_Full

iv