0% found this document useful (0 votes)
245 views

The Control of A Self-Balancing Robot

The document summarizes a graduation project report on building a self-balancing robot. It describes the main components used, including stepper motors, an MPU-6050 sensor, Arduino, and lithium-ion battery. It discusses testing the components, designing the mechanical structure in AutoCAD, fabricating parts using CNC, and designing the electric circuit and PCB. It also covers designing a Bluetooth mobile app for wireless control of the robot.

Uploaded by

Abdo Hesham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
245 views

The Control of A Self-Balancing Robot

The document summarizes a graduation project report on building a self-balancing robot. It describes the main components used, including stepper motors, an MPU-6050 sensor, Arduino, and lithium-ion battery. It discusses testing the components, designing the mechanical structure in AutoCAD, fabricating parts using CNC, and designing the electric circuit and PCB. It also covers designing a Bluetooth mobile app for wireless control of the robot.

Uploaded by

Abdo Hesham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 95

Cairo University

Faculty of Engineering
Electrical Power Department

Graduation Project Spring 2022-2023


Control of Self-balancing Robot

By
Amr salah Abdullah Abdel-rahem
Asmaa Mohamed Ahmed Saed
Nadine Hatem Mohamed El-Mahdi
Omar Abdullah Hassan Ahmed

Supervised by
Prof. Abdel-Latif Elshafei

A Graduation Project Report Presented To


Electrical Power Engineering Department
Cairo University
Faculty of Engineering
Electrical Power Engineering Department

Graduation Project Spring 2022-2023


Control of Self-balancing Robot

By
Amr salah Abdullah Abdel-rahem
Asmaa Mohamed Ahmed Saed
Nadine Hatem Mohamed El-Mahdi
Omar Abdullah Hassan Ahmed

Supervised by
Prof. Abdel-Latif Elshafei

A Graduation Project Report Presented To


Electrical Power Engineering Department
Acknowledgment

A special thanks and great appreciation are given to everyone who assisted us in
accomplishing this project through valuable help, advice, and guidance. This
acknowledgment is dedicated to our graduation project’s supervisor Dr. Abd-EL Latif. The
team members want also to express their gratitude for the sincere advice and unconditional
help from the department’s T.A.s especially Eng. Sherif Fath-Allah and fellow colleagues
in the other teams.

Team members,

I
Abstract

This report describes the detailed steps for constructing a self-balancing robot. The self-
balancing robot is based on the concept of the inverted pendulum on a moving cart. The
robot is inherently unstable. Using a micro-controller, gyroscope to determine angle of
inclination and two stepper motors which act as an actuator, the system can be balanced
by applying a suitable control mechanism. An additional feature was added to our robot
that allows us to control our robot wirelessly via Bluetooth app that receives commands
from a customized-made app on a smart phone. The proportional-derivative-integral
control mechanism is the most popular and was chosen to balance our robot. The chapters
of the report discuss in detail the steps of constructing the robot starting from chapter 1
that includes an introduction to the problem and the motivation behind choosing this
project. Chapter 2 discusses the main components used in our robot including their
working principles, advantages, disadvantages, and alternatives. Chapter 3 discusses
various tests done on the components individually and other tests done when interfacing
these components together in order to fully understand its capabilities and limitations.
Chapter 4 discusses the topics related to the mechanical structure starting with comparing
different materials to build the robot with and choosing the suitable one and finishing with
assembling the parts together using nails, screws and bolts passing through designing the
mechanical structure on AutoCAD, and estimating whether the motors’ torque will be
sufficient enough to withstand the robot’s weight. Chapter 5 discusses designing the
electric circuit and the PCB. Chapter 6 is concerned with the blue-tooth application, the
justification behind choosing an app over any other media to control the robot and
designing the app. Chapter 7 can be considered as a troubleshooting manual which
explains the different problems and obstacles that our team faced during the different
stages of the project and how these problems were fixed. Chapter 8 discusses in detail the
proportional-integral-derivative approach for effective control of the robot including
tuning techniques. Chapter 9 explains the mechanical model which was simulated in
SIMULINK. This chapter includes an explanation about the functions of each block and
steps to build the model. Chapter 10 continues with the SIMULINK model and how it was
used for system identification in order to obtain the transfer function of the system. In
chapter 11, the Arduino codes are explained in detail. The Arduino codes discussed in this
chapter are not limited to those used in the final project, but it also includes the codes that
were used for troubleshooting to make sure that the different components are working as
intended. Chapter 12, the last chapter, summarizes the project and suggests future
improvements which can be applied to the motor.

II
Table of Contents
Chapter 1 Introduction ........................................................................................................ 1
1.1 Overview: ............................................................................................................. 1
1.2 Problem Description ............................................................................................. 1
1.3 Inverted Pendulum Theory ................................................................................... 1
1.4 Project Motivations .............................................................................................. 2
1.5 Project Main Idea and Stages: .............................................................................. 3
Chapter 2 Main Components .............................................................................................. 4
2.1 Stepper Motors ..................................................................................................... 4
2.2 MPU-6050: ........................................................................................................... 6
2.2.1 MEMS Accelerometer .................................................................................. 7
2.2.2 MEMS Gyroscope ........................................................................................ 7
2.3 Arduino NANO .................................................................................................... 8
2.4 Rechargeable Lithium-ion Battery ....................................................................... 9
2.4.1 Construction .................................................................................................. 9
2.4.2 Theory of Operation ...................................................................................... 9
2.4.3 Advantages and Disadvantages..................................................................... 9
2.5 DRV8825 Stepper Motor Driver ........................................................................ 10
2.6 Components Interfacing ..................................................................................... 12
2.6.1 Stepper motors test ...................................................................................... 12
2.6.2 Acquisition of MPU-6050 Readings ........................................................... 14
2.6.3 Using MPU-6050 As a Level Meter ........................................................... 14
2.6.4 Integrating MPU-6050 With Stepper Motor ............................................... 14
2.6.5 Bluetooth module with stepper motors ....................................................... 15
Chapter 3 Mechanical Structure........................................................................................ 18
3.1 Structure Requirements ...................................................................................... 18
3.2 Material Used: Acrylic ....................................................................................... 18
3.3 System Estimation .............................................................................................. 20
3.4 Mechanical Structure Design ‘AutoCAD’ ......................................................... 21
3.5 Mechanical Structure CNC Fabrication ............................................................. 22
3.6 Connecting Parts ................................................................................................ 23

III
3.7 Choosing the Wheels .......................................................................................... 24
Chapter 4 Electric Circuit Design ..................................................................................... 26
4.1 Schematic Design ............................................................................................... 26
4.2 Breadboard Test Setup ....................................................................................... 28
4.3 Printed Circuit Board (PCB) Design .................................................................. 29
Chapter 5 wireless Control Application:........................................................................... 31
5.1 Why Use a Mobile Application .......................................................................... 31
5.2 MIT APP Inventor .............................................................................................. 32
5.3 Application Versions .......................................................................................... 32
5.3.1 Application Version 4 ................................................................................. 32
5.3.2 Application version 8 .................................................................................. 33
5.3.3 Application version 14 ................................................................................ 33
5.3.4 The Final Application Version.................................................................... 34
5.4 Application Block Diagrams in MIT App Inventor ........................................... 35
5.4.1 Main Control Screen ................................................................................... 35
Battery Indicator ....................................................................................................... 36
Chapter 6 How To Balance a Self-Balancing Robot ........................................................ 37
6.1 Mechanical Requirements And Limitations ....................................................... 37
6.1.1 Weight And Torque Limitations ................................................................. 37
6.1.2 Height .......................................................................................................... 37
6.1.3 Wheels......................................................................................................... 38
6.1.4 Center of Gravity ........................................................................................ 38
Chapter 7 Control Method: PID Controller ...................................................................... 42
8.1 PID Controller in Our Application: .................................................................... 42
8.2 Tuning Techniques ............................................................................................. 44
8.2.1 Trial and Error............................................................................................. 44
8.3 Mechanical System Simulink Model ................................................................. 45
8.3.1 Blocks Definition ........................................................................................ 46
8.3.2 Steps To Build a Model .............................................................................. 46
8.4 System Identification Toolbox ........................................................................... 49
Chapter 8 Arduino Codes Used This Project .................................................................... 51
9.1 MPU-6050 Calibration Code ............................................................................. 51

IV
9.2 Hardware Troubleshooting Tests Code .............................................................. 52
9.3 Main Code of The Self-Balancing Robot ........................................................... 53
9.3.1 The Initial Parameters And PID Gains ....................................................... 53
9.3.2 The Void Setup And Interruption Sub Routine .......................................... 54
9.3.3 The Main Void Loops ................................................................................. 55
Chapter 9 Conclusion and Future work ............................................................................ 60
10.1 Conclusion ...................................................................................................... 60
10.2 Future Work .................................................................................................... 60
10.2.1 Better Alternative for The Used Components ............................................ 60
10.2.2 TMC2208 Motor Mriver: ............................................................................ 60
10.2.3 ESP8266 WI-FI Module: ............................................................................ 61
10.2.4 Mechanical Structure Improvements .......................................................... 61
10.2.5 Better Electrical Circuit And PCB Design Techniques ............................. 62
10.2.6 Different Control Algorithms ..................................................................... 65
Appendix ........................................................................................................................... 67
10.3 The MPU Calibration Code ............................................................................ 67
10.4 Main Control System Code ............................................................................ 70
10.5 Self-Balancing Robot Costs of Production. .................................................... 80
References ......................................................................................................................... 82

V
List of Figures
Figure 1: Inverted pendulum free body diagram. [47] ........................................................ 2
Figure 2: NEMA 17-stepper motor. .................................................................................... 4
Figure 3: Hybrid stepper motor. [7] .................................................................................... 5
Figure 4: Micro-stepping. [7] .............................................................................................. 5
Figure 5: Unipolar stepper motor. [37] ............................................................................... 6
Figure 6: Bi-polar stepper motor. [37] ................................................................................ 6
Figure 7: MPU-6050 module. [39] ..................................................................................... 6
Figure 8: MEMS accelerometer. [38] ................................................................................. 7
Figure 9: Arduino NANO pin layout. [40] ......................................................................... 8
Figure 10: Rechargeable lithium-ion battery. [41] ............................................................. 9
Figure 11: DRV8825 stepper driver pin diagram. [12]..................................................... 10
Figure 12: HC-05 pin module. [13] .................................................................................. 11
Figure 13 Stepper motor connected to motor driver and Arduino .................................... 12
Figure 14 Set step and direction pins to pin 3 and pin 2 ................................................... 13
Figure 15 Setup Step and direction pins as output ............................................................ 13
Figure 16 Code of clockwise one revolution at low speed ............................................... 13
Figure 17 Code of counterclockwise two revolution at high speed .................................. 13
Figure 18 Connection of MPU6050 and Arduino UNO ................................................... 14
Figure 19 MPU6050 as a level meter ............................................................................... 14
Figure 20 MPU as a level meter with stepper motors ....................................................... 15
Figure 21 Connection of Bluetooth module to Arduino which used in our test ............... 15
Figure 22 different thickness of acrylic sheets ................................................................. 20
Figure 23 First rack of self-balancing robot ..................................................................... 21
Figure 24 Second rack of the self-balancing robot ........................................................... 21
Figure 25 Third rack of the self-balancing robot .............................................................. 21
Figure 26 Final printed acrylic racks ................................................................................ 22
Figure 27 L-channel stepper motor holder........................................................................ 23
Figure 28 metal screw Rods used in the Project .............................................................. 23
Figure 29 Normal wheels .................................................................................................. 25
Figure 30 Off road wheels ................................................................................................ 25
Figure 31 Mecanum wheels .............................................................................................. 25
Figure 32 Omni wheel ...................................................................................................... 25
Figure 33 SBR schematic diagram ................................................................................... 26
Figure 34 breadboard schematical representation............................................................. 28
Figure 35 PCB final design inside EasyEDA software .................................................... 29
Figure 36 PCB after assembly .......................................................................................... 30
Figure 37 physical connection representation................................................................... 31
Figure 38 non-chuck controller ......................................................................................... 31
Figure 39 the designer tap page of the MIT App inventor website .................................. 32
Figure 40 application version 4......................................................................................... 32

VI
Figure 41 Application version 8 ....................................................................................... 33
Figure 42 Application version 14 ..................................................................................... 33
Figure 43 Final Application version ................................................................................. 34
Figure 44 Bluetooth connection blocks ............................................................................ 35
Figure 45 direction key-pad block diagram. ..................................................................... 35
Figure 46 Speed mode switchers ...................................................................................... 36
Figure 47 our self-balancing robot. ................................................................................... 37
Figure 48. In a motorcar, the weight of the vehicle at each wheel and measuring the
wheelbase. ......................................................................................................................... 40
Figure 49. Block Diagram of PID Controller ................................................................... 42
Figure 50. The control mechanism used in self-balancing robot. ..................................... 42
Figure 51. The closed loop control system of the self-balancing robot. [27] ................... 43
Figure 52. Closed-loop step response of PI control system. line 1: the response from the
original structure; line 2: response from the alternative structure. ................................... 44
Figure 53. The mechanical system of a two-wheeled self-balancing robot. ..................... 45
Figure 54. Setting the body element dimensions to simulate the real-life wheel. ............ 46
Figure 55. A subsystem for the left wheel and tire. .......................................................... 47
Figure 56. Cart subsystem where there are two stepper motors connected with the wheels.
........................................................................................................................................... 47
Figure 57. Chassis subsystem and the connection of rods and racks using the rigid
transform block. ................................................................................................................ 48
Figure 58. Revolute joint block setting its sensing to position ......................................... 48
Figure 59. Prismatic joint block setting its actuation force to be provided as an input. ... 48
Figure 60. Setting the PID block to a proportional controller. ......................................... 49
Figure 61 the MPU calibration code serial monitor’s output ........................................... 51
Figure 62 ED printed model of a two-wheeled self-balancing robot................................ 61
Figure 63 better Schematic design .................................................................................... 62
Figure 64 Recommended PCB layout............................................................................... 63
Figure 65 Recommended Arduino configuration. on the PCB ......................................... 63
Figure 66 Recommended MPU-6050 position on the PCB. ............................................. 64
Figure 67 Pluggable terminal block 2 pins connected to an adaptor on a mini breadboard.
........................................................................................................................................... 64
Figure 68 LM3914 recommended circuit from datasheet................................................. 65

VII
Introduction Overview:

Chapter 1 Introduction
1.1 Overview:
Robotics is the field of designing, constructing, and using robots to perform tasks which
were usually done by humans. These tasks are characterized by repetitiveness such as the
automobile industry or of hazardous nature that subject humans to injury. Many aspects of
robotics involve artificial intelligence. Robots are provided with sensors that are meant to
simulate human senses such as vision, touch, and the ability to sense temperature. Current
robotics research is directed to develop robots with a degree of self-sufficiency which will
make them capable of simple decision making in unfamiliar environments. Most industrial
robots do not resemble human beings but are designed for specific applications and
situations such as robotic arms which are tasked with welding and screwing in automotive
industries. As a result of the current robotics research, huge improvements in micro-
controllers, accurate sensors and diverse controlling methods were achieved in the last few
decades resulting in the development of many advanced applications such as self-balancing
robots [1].
A self-balancing robot is a two-wheeled robot which balances itself to prevent itself from
falling. This concept is like that of a unicycle in which the rider balances himself by moving
in the same direction as the inclination. Self-balancing robots use a closed feed-back
control system where real time data from sensors (gyroscope) is used to control stepper
motors to compensate for any tilting and keep the robot upright. The concept behind self-
balancing robot can be found in many applications such as autonomous trolleys, balancing
level of ships and Segways. [2]

1.2 Problem Description


Self-balancing robot is an unstable system by nature which has multiple variables and
characterized by non-linearity. The principle behind the self-balancing robot is the same as
that of the inverted pendulum. Both systems are naturally unbalanced, and both need an
effective control system for stabilization by keeping the position upright. There are
different control methods to achieve stabilization such as proportional, integral, derivative
control (PID), linear quadratic control (LQR), fuzzy logic control just to name a few. To
control the self-balancing robot, values of the angle and robot’s position should be supplied
to the microcontroller accurately and with a fast rate to get a fast, correct action to bring
the system back to stability.

1.3 Inverted Pendulum Theory


The inverted pendulum has its center of mass above its pivot point. The vertical rod is
placed on a moving cart that can only move back and forth. The inverted pendulum is a
common example found in control system references. The pendulum is unstable without
control and will fall if the cart doesn’t move to balance it. The control system should apply
force to the cart in order to keep the pendulum balanced. [3] To implement an effective

1|Page
Introduction Project Motivations

control system, all important variables such as forces acting on the inverted pendulum must
be determined to deduce the transfer function of the pendulum which will be used in the
design of the controller.

Figure 1: Inverted pendulum free body


diagram. [47]

Self-balancing robots have a lot in common with the inverted pendulum. Both systems are
unstable and need a control system to apply force to maintain stability. However, there are
few differences between the self-balancing robot and the inverted pendulum. Firstly, when
developing the transfer function of the inverted pendulum, the value of friction torque can
be neglected since that the friction coefficient is assumed to be near to zero. However,
friction torque cannot be ignored in self-balancing robot since that the wheels of the self-
balancing robot will be moving on surfaces that have high friction coefficients. Taking the
friction torque into account will give more accurate control actions that help in reaching a
state of stability.
Another difference is the degree of motion. The cart on which the vertical rod is fixed only
moves back and forth while the self-balancing robot moves on all directions since it will
be placed, of course, on a floor plane.

1.4 Project Motivations


Self-balancing robots, as mentioned above, are used in many applications in automation
and industry. They are also used in educational and academic circles to give students a
hands-on experience in implementing control system theories. It also challenges students
to deal with hardware problems and restrictions such as designing protection schemes
against short circuit currents and considering rated current limitations of different
components. The project also exposes students to mechanical issues that must be addressed
such as the maximum weight the stepper motors can manage and determining the suitable
location of the center of gravity to achieve stability.

2|Page
Introduction Project Main Idea and Stages:

1.5 Project Main Idea and Stages:


Our main objective is to balance the robot using Arduino micro-controller, gyroscope to
measure the angle of inclination and stepper motors to give appropriate action and return
the robot back to the reference position if any inclination takes place. A Bluetooth module
will also be used to control the control the motion of the robot using a simple app on a
mobile phone. The self-balancing robot will be designed and constructed from scratch.
The project is divided into five stages. The first stage is testing the components
individually. The second stage is mechanical design. Third stage is the PCB design. Fourth
stage is the Bluetooth app design. The robot should be able to self-balance and receive
instructions from Bluetooth module to control the robot’s motion forward, backward and
around its axis in both directions. The final stage is determining the optimum PID values
to achieve stability.
The first stage is testing the components individually and getting familiar with them. These
tests included the stepper motors, using gyroscope as a level meter and integrating both the
stepper motors and gyroscope together. These tests were helpful in gaining a foothold in
Arduino programming as well as electrical connections between stepper motors, drivers,
gyroscope, and Arduino micro-controller.
The second stage is developing the Bluetooth app. Using the Bluetooth module will enable
us to control the motion of the robot. The Bluetooth module receives data from mobile
phone software (mobile app) and transmits data to Arduino NANO.
The third stage is the design and implementation of the printed circuit board (PCB) and
testing it.
The fourth stage is the design of the mechanical structure. This stage includes choosing the
appropriate material to build the robot and determining the dimensions of the robot to
achieve a robust design. This stage also included choosing suitable wheels that can be
coupled easily with the shaft of the stepper motor and that can withstand the weight of the
robot as well as tolerate uneven, rough surfaces that the robot might move on.
The fifth and last stage includes assembling the self-balancing robot and acquiring the
values of the PID controller. It was decided to use the PID method as a control system. In
this stage, a mechanical simulation was modeled on SIMULINK and tested in order to get
initial values for the proportional, integral and derivative terms. The mechanical
SIMULINK model doesn’t accurately represent the real-life robot; however, it provides
initial guesses for PID values and then a trial-and-error approach is taken until a desired
performance is reached and the robot is self-balanced.

3|Page
Main Components Stepper Motors

Chapter 2 Main Components


2.1 Stepper Motors
The first component to be discussed is the actuator of the project. It was found that DC
motors and stepper motors are the most used types of motors in small robotic application
due to their torque-speed characteristics that best fits the needs of the self-balancing robot
and their sizes that are suitable for such a small-scale project in size. To make a wise choice
between the DC motor and a stepper motor, a comparison had to be made to decide which
type of motor will satisfy the project’s specific needs and requirements. The following table
briefly illustrates the key differences between the two types of motor: [4]
Points of comparison Stepper motor Brushed DC motor
Speed The speed of stepper motor DC motors have moderate
is low, about 200 to 2000 speed range depending on
RPM. the type of motor.
Torque-speed Stepper motors produce DC motors produce high
characteristics maximum torque at low torque at low speeds
speeds. The toque
decreases as speed
increases.
Control mechanism The control mechanism of The control mechanism of
stepper motor needs micro- DC motors is simple and no
controllers. need of extra devices like
micro-controllers.
Efficiency The efficiency of stepper The DC motors have high
motors is low. efficiency around 85%.
Noise Arcs in the brushes will Generates some noise
generate noise especially at low speeds
Cost Moderate Low
Applications Stepper motors are used in DC motors are commonly
various position control used in toys, computers,
applications such as cranes, kitchen appliances,
robotics, printers, hard disc lifts, etc.
drives, etc.

Stepper motors are chosen for their superior torque at low speeds,
accuracy, output characteristics and simple controllability.
Unlike DC motors which rotate in a continuous manner, stepper
motors rotate in increments or steps. Rotating in steps made
stepper motors suitable when very precise positioning and high
torque are required. That is why stepper motors are used in 3D
printers, CNC machines, DVD drives and analog clocks [5]. Figure 2: NEMA 17-
Stepper motors are classified according to the way of magnetic stepper motor.

4|Page
Main Components Stepper Motors

field creation into variable reluctance, permanent magnet, and hybrid synchronous. The
most available type commercial-wise is the hybrid-synchronous which is further classified
into bi-polar and unipolar stepper motors.

2.1.1. Theory of Operation:


Stepper motors include a magnetized gear core that will turn once force is applied to it. The
core is enclosed by a number of coils that act as electro-magnets. The coils are arranged
near the rotor so that magnetic fields within the coil can control the movement of the rotor.
By controlling the value of the current entering these coils via a micro-controller, the rotor
can be controlled to move discrete steps.
The stepper motor working principle is electro-
magnetism. When the current passes through one of the
coils, magnetic field is formed which is perpendicular to
the direction of the current. Each coil is energized one at
a time. The rotor aligns itself with the coil currently
energized in a position which gives field lines the path
with the least reluctance. Using a microcontroller, the
current can be sent as pulses and energize coils one at a
time so that rotor moves in an incremental fashion or Figure 3: Hybrid stepper motor. [7]
steps. The number of coils determines the size of each
step. The NEMA 17 stepper motor has a step size of 1.8o. [6]
Micro-controllers can be programmed to allow micro-stepping. If equal magnitudes of
current are supplied to two coils at the same time, the rotor will align itself at a position
half-way between the two coils. By extending this principle, the ratio of current between
two coils can be manipulated to allow very precise movement that can reach a resolution
of a fraction of a step. The following figure illustrates the idea of micro-stepping further:

Figure 4: Micro-stepping. [7]


Imax is the maximum current of one phase. Starting from left, IA = Imax while IB = 0. In the
next step, IA = 0.92Imax while IB = 0.38Imax. The magnetic field is rotated by 22.5o compared
to the initial state. Using micro-stepping helps in reaching fully accurate positions without
the need to add more coils. [7]

5|Page
Main Components MPU-6050:

2.1.2. Stepper Motor types:


Unipolar stepper motors have one winding for each phase with a center
tap at each winding. This gives six connections, however, the center
taps of the two windings can be connected to give five connections. In
unipolar stepper motors, current flows in one direction hence the name.
Fixed direction of current allows simple control as there is no need to
reverse the direction of the current. Control of unipolar stepper motor
is done by using four MOSFETs in a half-bridge configuration.
However, the unipolar motor uses only half of its coil at a time which
means less efficiency and less output torque, but they have greater max Figure 5: Unipolar
speed than bi-directional motors. [8] stepper motor. [37]

Bi-polar stepper motors also have one winding for each phase but no
center taps. This gives four connections, two per phase. In bi-polar
stepper motors, current flows bi-directionally. The voltage’s polarity
is reversed to change the magnetic flux poles. This reversal of polarity
requires complex driving circuitry using eight MOSFETs however,
modern ICs and power control devices made it easier to control the
voltage’s polarity and the complexity of controlling bi-directional
stepper motors ceases to be a major issue. Bi-directional motors utilize
all the windings which mean more efficiency and more output torque.
Figure 6: Bi-polar
In this project, speed of the self-balancing robot is not much of a
stepper motor. [37]
concern as the output torque, so, bi-directional stepper motors are
used. [8]

2.2 MPU-6050:
The MPU-6050 is a micro-electrical-mechanical system, MEMS
for short. The MPU contains a 3-axis gyroscope and a 3-axis
accelerometer which enables the MPU to measure velocity,
orientation, displacement just to name a few. The MPU also
contains a digital motion processor (DMP) which is powerful
enough to compute complex calculations which can free up some
load off the microcontroller. In addition to its low cost, MPU-6050
has many materials, resources and libraries hence very easy to use
with Arduino NANO which made it suitable for the self-balancing
robot. [9] Figure 7: MPU-6050
module. [39]

6|Page
Main Components MPU-6050:

The MPU-6050 has 8 pins that are listed below:


2.2.1 MEMS Accelerometer
Pin Name Function
VCC Supply voltage Provides power for the module, Connect to the 5V
pin of the Arduino.
GND Ground Ground Connected to Ground pin of the Arduino.
SCL Serial clock Serial Clock Used for providing clock pulse for I2C
Communication.
SDA Serial data Serial Data Used for transferring Data through I2C
communication.
XDA Auxiliary serial data Auxiliary Serial Data - Can be used to interface other
I2C modules with MPU6050.
XCL Auxiliary serial clock Auxiliary Serial Clock - Can be used to interface
other I2C modules with MPU6050.
AD0 Address Address select pin if multiple MPU6050 modules
are used.
INT Interrupt Interrupt pin to indicate that data is available for
MCU to read.
MEMS accelerometer measures the linear acceleration of the object they are attached to.
Accelerometers work on the principle of the inertia of a mass on a spring. The mass forms
a movable plate and there is another fixed plate that forms a capacitor. When the object to
which the accelerometer is attached is subjected to linear acceleration, the mass tries to
resist the change in its current state which results in inertia. As the mass moves, the distance
between the two plates changes thus the capacitance changes. The change in capacitance
is proportional to the applied acceleration. The change in capacitance is measured by a
high-resolution analog to digital converter and then the acceleration is calculated from the
rate of change of capacitance. This is then converted into readable data and sent to the I2C
master device (Arduino). [9]
2.2.2 MEMS Gyroscope
The working principle behind the MEMS gyroscope is
the Coriolis effect. The Coriolis effect states that when a
mass that is moving with a certain velocity is subjected
to an external angular motion, a force is generated that
causes a perpendicular displacement of the mass. The rate
of displacement is directly proportional to the external
angular motion. The MEMS gyroscope contains four
masses that are kept in continuous oscillatory motion.
When an angular motion is applied, the Coriolis effect
Figure 8: MEMS
causes a change in capacitance between the masses
accelerometer. [38]
depending on the axis of the angular motion. The change
in capacitance is sensed and converted into a reading. [9]

7|Page
Main Components Arduino NANO

2.3 Arduino NANO


Arduino boards are microcontroller boards that are developed based on ATmega
microcontrollers and their applications include embedded systems, robotics, automation,
etc. There are many types of Arduino boards developed by Arduino.cc such as UNO, Mega,
micro, Pro Mini. However, the Arduino NANO will be used for this project. The main
reason behind choosing the NANO type is its small size that won’t occupy much space.
The Arduino NANO is based on the ATmega 328P microcontroller. Unlike the Arduino
UNO, Arduino NANO doesn’t have a DC power jack but is supplied power from a mini-
USB port on the board. [10]
To program the Arduino NANO, an open-source Arduino integrated development
environment (IDE), which is based on C++ programming language, must be downloaded.
Since it is an open source, many materials can be found for programming the Arduino
NANO and many programmers developed libraries, which are a block of code used to do
a specific function. These libraries were used to program Arduino NANO and interface the
different components as will be discussed in detail in the following sections. [10]
The pin diagram of the Arduino NANO and its functions are described below: [10]

Figure 9: Arduino NANO pin layout. [40]


Pin name Description Function
Vin Input volt. Used when an external power source is used
from 7V to 12V.
5v 5v Regulated power supply voltage of the nano
board and it is used to give the supply to the
board as well as components.
3.3v 3.3v Same function as the 5v.
GND Ground The ground pin of the board.
RST Reset Used to reset the microcontroller.
Pins: A0 to A7 Analog pins Used to calculate the analog voltage of the
board within the range of 0V to 5V.
Pins: D0 to Digital pins Used as an I/P otherwise o/p pins. 0V & 5V.
D13
TX and RX Receive and Used to transmit and receive data in serial
transmit communication
Pins: 2,3 Interrupts Used to interrupt the main program and execute
certain instructions in case of emergency.
Pins: PWM Used to provide 8-bit of PWM output.
3,5,6,9,10,11

8|Page
Main Components Rechargeable Lithium-ion Battery

Pins: SPI Used to communicate with sensors and


10,11,12,13 registers that use SPI communication.
Pin:13 Built in LED pin Used to activate the LED that indicates that the
Arduino is working normally i.e., sending, and
receiving data.
A4, A5 I2C protocol A4 is a bidirectional serial data line (SDA).
A5 is Serial clock line SCL.
AREF Reference volt pin Used to give reference voltage to the input
voltage.
2.4 Rechargeable Lithium-ion Battery
2.4.1 Construction
A rechargeable lithium-ion battery is found in many applications
such as cell phones, laptop computers, mp3 players and even
electric vehicles. The rechargeable lithium-ion battery is made of
one or more compartments called cells. Each cell consists of a
positive electrode, a negative electrode, a chemical conductive
substance called an electrolyte between them and a separator. The
positive electrode is usually made of lithium-cobalt oxide or
lithium iron phosphate. The negative electrode is usually made of
carbon (graphite). The electrolyte material varies according to the
manufacturer and type of battery. The separator is a very thin
Figure 10: Rechargeable
sheet of micro-perforated plastic, and it separates the positive and
lithium-ion battery. [41]
negative electrodes while allowing ions to pass through. [11]
2.4.2 Theory of Operation
When the battery is charging up, the positive electrode gives up some of its lithium ions
which move through the electrolyte to the negative electrode and remain there. During this
process, the battery takes in and stores energy. When the battery is discharging, the lithium
ions move from the negative electrode to the positive electrode through the electrolyte.
During this process, the battery is giving away and supplying power to a load. In both
cases, charging and discharging, the electrons flow in the opposite path of the ions around
the outer circuit not through the electrolyte. [11]
2.4.3 Advantages and Disadvantages
Lithium-ion batteries have several advantages such as they are more reliable than the older
battery technologies such as nickel-cadmium batteries as they don’t suffer from memory
effect. Memory effect is a problem present in nickel-cadmium batteries where the battery
must be fully discharged before attempting to recharge it again. The absence of toxic heavy
metals such as cadmium makes lithium-ion batteries much safer for the environment.
However lithium-ion batteries suffer from one major disadvantage which is thermal
runaway. Thermal runway happens when the battery heats up due to overcharging or if an
internal malfunction causes a short circuit. This eventually ends up in an explosion or

9|Page
Main Components DRV8825 Stepper Motor Driver

chemical fire which must be extinguished by using carbon dioxide. However, thermal
runaway is a rare occurrence. [11]

2.5 DRV8825 Stepper Motor Driver


There are various motor drivers available commercially. However, it was found that three
types of motor drivers in particular are suitable for driving the stepper motor. These drivers
are the A4988, DRV8825 and the TMC2208. All these drivers have the same pin diagram.
The table below shows the difference between the drivers: [12]

Due to the simplicity of the stepper motor control and the variety of stepping modes
provided by the DRV8825 driver, it is the ideal stepper driver for applications that require
precise and reliable stepper motor control such as self-balancing robots. The DRV8825 has
a drive voltage capacity of 45V. This means that the NEMA17 bi-polar stepper motor can
be controlled with up to 2.5A per coil. The output current can be regulated by using a
current limiting potentiometer to not exceed the rated current of the stepper motor. The
driver contains six modes of stepping which are: full-step, half-step, quarter-step, eighth-
step, sixteenth step and thirty-second step. Excessive power dissipation from the driver’s
IC causes temperature to rise which may lead to irreversible damage to the driver.
Therefore, DRV8825 drivers usually come with a heat sink. Although the rated current of
the driver is 2.5A per coil, it can only supply 1.5A per coil without overheating. To supply
the full rated current, the heat sink must be installed. [12]

Figure 11: DRV8825 stepper driver pin diagram. [12]

10 | P a g e
Main Components DRV8825 Stepper Motor Driver

The DRV8825 pin diagram is described below:


Pin Function
VMOT, Supply power to the motor. A capacitor of at least 47µF should
GNDMOT be placed across these two pins to protect against voltage spikes.
GNDLOGIC Connected with the Arduino’s ground
M0, M1, M2 Used to pick the one of the six step resolutions.
STEP Controls the micro-steps of the motor. As the pulse frequency
increase, so does the motor’s speed.
DIR Controls the spinning direction of the motor. When it is set HIGH
the motor turns clockwise. When it is set LOW, the motor turns
anti-clockwise.
EN Active low input. When it is LOW, the driver is enabled.
SLP Active low input. When it is LOW, the driver is in sleep mode,
reducing the power consumption to a minimum.
RST Active low input. When it is LOW, all step inputs are ignored.
FAULT Sets to LOW whenever there is an over-current protection or
thermal shutdown.
B1, B2, A1, A2 Output pins connected to the 4-wires of the stepper motor.

2.6. Bluetooth Module HC-05:


The HC-05 Bluetooth module is a popular module that can add full–duplex wireless
communication. Full-duplex means that HC-05 can be either a master or slave device and
can transfer data from and to a microcontroller. HC-05 can be used to communicate
between two microcontrollers like Arduino or any device that is provided with Bluetooth
functionality such as laptops or smart phones. There are many Android and IOS apps that
make this process, (interfacing smart phone with Bluetooth module), much easier. This
module communicates via USART (Universal Synchronous Asynchronous Receiver
Transmitter) which is supported by many microcontrollers including Arduino. [13]

Figure 12: HC-05 pin module. [13]

11 | P a g e
Main Components Components Interfacing

The HC-05 pin module is described below:


Pin number Pin name Function
1 Enable/key Used to toggle between data mode (LOW), which allows
module to send and receive data, and command mode (HIGH),
where the default device settings can be changed such as the
password.
2 Vcc Power source of the module. Connected to +5V source
3 Ground Connected to the ground of the system.
4 TX Transmits everything received via Bluetooth as serial data.
(From smart phone to microcontroller)
5 RX Any serial data sent to this pin will be broadcasted via
Bluetooth. (From microcontroller to smart phone)
6 State Connected to on board LED. Used as feedback to check if the
module is working properly.
7 LED Indicates the state of the module:
1) Blinks once in 2 sec. when in command mode.
2) Repeated blinking: Waiting for connection in data mode.
3) Blinks twice in 1 sec.: Connection successful in data mode.
8 Button Used to control key/enable pin to toggle between data and
command modes.
2.6 Components Interfacing
Once we were acquainted with the main components, we proceeded to conduct a series
of tests to familiarize ourselves with their operation, ensure proper functionality, and
identify any potential limitations or drawbacks. In total, we conducted five tests, which are
detailed below:
2.6.1 Stepper motors test
The motors were programmed to rotate one full turn in a clockwise direction at low
speed, followed by two full turns in a counterclockwise direction at high speed, with this
sequence repeating. To achieve this, we familiarized ourselves with the fundamental
programming functions of Arduino, which enabled us to control the speed and direction of
the stepper motors. Additionally, we learned how to correctly wire the stepper motors to
the Arduino module and motor driver.

Figure 13 Stepper motor connected to motor driver and Arduino

12 | P a g e
Main Components Components Interfacing

This is the code of our experiment:

Figure 14 Set step and direction pins to pin 3 and pin 2

Figure 15 Setup Step and direction pins as output

Figure 16 Code of clockwise one revolution at low speed

Figure 17 Code of counterclockwise two revolution at high speed

13 | P a g e
Main Components Components Interfacing

2.6.2 Acquisition of MPU-6050 Readings


During this test, we effectively utilized the mpu-6050 to measure the angles in a three-
dimensional plane relative to a set point determined by the gyroscope when positioned on
a horizontal plane. However, we initially encountered an issue while attempting to install
the mpu-6050 on the breadboard and supplying it with power proved to be challenging.
Nevertheless, we were able to address this issue by soldering the pins into the gyroscope.

Figure 18 Connection of MPU6050 and Arduino UNO

The code we used in this experiment is in Arduino IDE examples and called MPU_DMP6.
2.6.3 Using MPU-6050 As a Level Meter
In this experiment, we utilized the gyroscope as a level meter, with readings from the MPU-
6050 transmitted to the Arduino. The Arduino was programmed to activate specific LED
lights when the MPU-6050 reading entered a particular range. To accomplish this, we
employed five LED lights, with the middle LED illuminating when the angle was between
-10 to 10 degrees. The LED to the right lit up when the angle was between 10 to 20 degrees,
while the far-right LED lit up when the angle exceeded 20 degrees. The same methodology
was applied to the left and far-left LEDs, but with negative degree values.

Figure 19 MPU6050 as a level meter

2.6.4 Integrating MPU-6050 With Stepper Motor

14 | P a g e
Main Components Components Interfacing

Building on the previous experiment, we utilized the MPU-6050 as a level meter and
incorporated the stepper motor in addition to the LED lights. The motor responded to
different angle values, with no action taken when the angle was between -10 to 10 degrees.
When the angle was between 10 and 20 degrees, the motor rotated in a counter-clockwise
direction, and when the angle exceeded 20 degrees, the motor rotated counter-clockwise at
a higher speed. The same sequence was repeated for negative angle values, but the motor
rotated clockwise. This experiment emulated the robot's efforts to maintain balance, with
the MPU-6050 functioning as a sensor and the stepper motor as an actuator.

Figure 20 MPU as a level meter with stepper motors

2.6.5 Bluetooth module with stepper motors


As part of our ongoing efforts to develop a wirelessly controlled self-balancing robot, we
conducted a test using a Bluetooth module to control the stepper motor wirelessly. To
accomplish this, we developed a basic mobile application with three commands: to rotate
the motor clockwise, anti-clockwise, and to stop the motor.

Figure 21 Connection of Bluetooth module to Arduino which used in our test

This is the code of our experiment, and it will be explained below.

15 | P a g e
Main Components Components Interfacing

In this section we declared:


• Some libraries are important for stepper motor and Bluetooth module.
• Set pins 2 & 3 to be direction and step pins.

In void setup,
• We start the communication with Bluetooth module.
• Setup stepPin and dirPin as outputs.
• Initialize the motor to be stopped.

In void loop, If the Bluetooth module is connected and the data is ‘1’ the motor is
rotated in clockwise direction at high speed.

16 | P a g e
Main Components Components Interfacing

If the data sent from the Bluetooth module is ‘2’, the motor direction will be
counterclockwise at the same speed.

If the data is zero, the motor will be stopped.

Having completed these tests, we have become well-versed in the operation of the
components and are now prepared to utilize them in constructing the self-balancing robot.

17 | P a g e
Mechanical Structure Structure Requirements

Chapter 3 Mechanical Structure


Self-balancing robots are gaining popularity for their ability to maintain stability on
two wheels. The mechanical structure is crucial, as it must support the robot's weight and
provide flexibility for balance. The structure includes a chassis, two wheels, a motor,
battery, and sensors. Sensors detect changes in orientation, used to adjust the motor for
balance. The chassis stabilizes the wheels and motor, while the battery powers them. The
mechanical structure is essential to performance, and this overview provides insight into
designing, building, and operating self-balancing robots.

3.1 Structure Requirements


Designing the mechanical structure of the self-balancing robot is an important stage in
our project, as if it isn’t correct, it will affect negatively the balance of the self-balancing
robot. So, the design of the mechanical structure has some key requirements will be
discussed below:
• Light Weight: the material of the mechanical structure should have light weight for
two reasons
• in order not to overload stepper motors.
• to minimize energy required from batteries so the lifetime of the batteries
increased.
• Weight distribution: the weight of the self-balancing robot should be evenly
distributed across its center to maintain stability of the robot.
• Robustness: the structure of the robot should be robust enough to withstand stresses
and external forces acting on it.
• Formability: the robot isn’t formed as one block it consists of parts, so the material of
the structure of the robot should be formable to be shaped and cut into parts without
losing its stability.
• Cost: The cost of the materials is a crucial consideration and should be appropriate for
the project's needs and the developer's budget.

3.2 Material Used: Acrylic


Choosing the material of the mechanical structure is a crucial factor in the design as
it affects the stability, lightness of weight, robustness of the structure. There are many
materials used to construct self-balancing robots such as plastic, plywood, acrylic, etc.
After searching between the materials used in designing the mechanical structure, we
construct this table which shows a brief review of some materials’ pros and cons.

18 | P a g e
Mechanical Structure Material Used: Acrylic

casing
materials: Advantages Disadvantages

Metals are heavy and their weight will be a


Metals provide extra
great challenge to overcome as it will
Metal [14] protection from mechanical
negatively affect the stability of the robot.
shocks and damage.
Plywood is stronger than
Plywood [15] MDF and can support heavier Harder to moulid.
weights.
medium-
MDFs are easier to mould and
density fiber Can’t support heavier weights and are easy
cheaper than plywood
board (MDF) to damage.
[15]
it can be vulnerable or fragile against
Plastics have light weight; mechanical strikes or rough terrain.
therefore, they don’t need Plastics are not usually used for the outer
Plastics [14]
too much energy to move the casing on the robot, rather, they are used
robot. as layers where PCBs, components, etc. are
placed.
After constructing this table, we found that acrylic is the best choice in our project
which is a type of plastic that is commonly used in the construction of self-balancing robots.
There are several reasons why acrylic is a popular choice for this application:
• Lightweight: Acrylic is a lightweight material that is ideal for building the chassis
and other components of a self-balancing robot. Its low weight helps to minimize
the power required to maintain balance and allows the robot to move and maneuver
more easily.
• Durable: Acrylic is a durable material that can withstand the stresses and forces
that a self-balancing robot may experience during operation. It is resistant to impact
and can maintain its shape even at high temperatures.
• Easy to machine: Acrylic is easy to machine and can be cut, drilled, and shaped
into various forms and sizes. This makes it easy to customize the robot's
components and chassis to fit specific design requirements.
• Cost-effective: Acrylic is a cost-effective material that is readily available and easy
to source. This makes it an attractive option for building self-balancing robots on a
budget.

Overall, acrylic is a versatile and practical material that is well-suited for use in self-
balancing robots. Its lightweight, durable, and other properties make it an excellent choice
for building the robot's chassis and other components.

19 | P a g e
Mechanical Structure System Estimation

Figure 22 different thickness of acrylic sheets

3.3 System Estimation


Once we had identified the requirements for designing the mechanical structure of the
self-balancing robot and selected acrylic as the casing material, our next step was to
determine if the torque generated by the motor would be sufficient to support the weight
of the robot. To accomplish this, we utilized an equation to estimate the required torque
based on estimated values for the robot's parameters.
Tmax = mg*l*sin(θmax) [1.0]
Tmax = 1.5*9.8*0.08*sin(5⁰) = 0.2315 Nm [1.1]
Where:
• Tmax is the maximum torque produced by the motor.
• m is the total mass of the robot.
• g is the constant of gravity.
• l is the height of the center of mass.
• θ is the maximum recovery angle, we choose such a small recovery angle since the
dynamics of the system will be linearized to calculate the control gains of the
system [16].

There are two motors on the robot so, the maximum torque produced by the motor
should be 0.1157 Nm (half of the maximum torque required by the system). Based on our
estimations and using a stepper motor with a torque of 0.38 Nm, we determined that the
motor's torque will be sufficient to support the weight of the robot's body.

20 | P a g e
Mechanical Structure Mechanical Structure Design ‘AutoCAD’

3.4 Mechanical Structure Design ‘AutoCAD’


Once the PCB has been designed and its required dimensions have been calculated,
the mechanical structure is designed using AutoCAD. AutoCAD is a popular software tool
used by mechanical engineers and designers to create detailed designs of self-balancing
robots.
The design consists of three rectangular racks, each measuring 17.5 cm in length, 11.5
cm in width, and 6 mm in depth. The first rack serves as the robot's base, which is connected
to L-channel to fix the stepper motors. The second rack houses the PCB, while the third
rack accommodates the battery.
The figures below show the dimensions of each rack:

Figure 23 First rack of self-balancing robot Figure 24 Second rack of the self-balancing robot

Figure 25 Third rack of the self-balancing robot

21 | P a g e
Mechanical Structure Mechanical Structure CNC Fabrication

3.5 Mechanical Structure CNC Fabrication


Once we completed the design of the mechanical structure, we began researching the most
appropriate fabrication method for our project. We considered two options: 3D printing
and laser cutting (CNC). Laser cutting involves using a laser to vaporize materials,
resulting in a precise cut edge. On the other hand, 3D printing is an additive process that
involves building up layers of material to create a three-dimensional part, which leads to
less material wastage. As part of our investigation into the optimal fabrication approach for
the robot's mechanical structure casing, we have compiled the subsequent table:
Manufacturing
methods for
Advantages Disadvantages
casing:

a. Laser can cut through a. Not fit for complex


Laser cutting: [17] all materials. multidimensional geometry.
b. Works with high b. Produce harmful fumes
accuracy and precision. during production.
a. Flexible and accurate a. Materials such as wood cannot
design be 3D printed because it will burn
3D printing: [18] b. Doesn’t need specific before they can be melted and
tools or several tools to extruded through a nozzle.
execute design.

Based on the information gathered from the table, we concluded that CNC is the optimal
choice for our project's fabrication needs. The figures below illustrate the CNC fabrication
process and the resulting final parts of the robot's body.

Figure 26 Final printed acrylic racks

22 | P a g e
Mechanical Structure Connecting Parts

3.6 Connecting Parts

This section will showcase some of the components utilized in our self-balancing robot.
As illustrated in the figure, the L-channel is
utilized to link the stepper motors with the first
rack. This element provides a stable socket like
holding for the stepper motors to ensure motor
stability. This component is readily available in
the Egyptian market and is priced affordably.

Figure 27 L-channel stepper motor holder


The self-balancing robot racks is connected with
steel screw rods shown in the figure. Steel rods
have diameters of 5mm and 10cm in length (the
best we found on the current market). The steel
rods provide structural integrity to the robot to
help with stand collisions. The rods also offer a
higher range of customization for the racks
spacing that help to control the robots weight
distribution.

Figure 28 metal screw Rods used in the Project

23 | P a g e
Mechanical Structure Choosing the Wheels

3.7 Choosing the Wheels


Wheels are an integral component of self-balancing robots, as they provide the
necessary movement and stability for the robot to operate efficiently. In the following
sections, we will explore some of the key considerations when designing and constructing
wheels for self-balancing robots such as:
• Light weight: It is advantageous for the wheels of a self-balancing robot to be
lightweight. This is because lighter wheels contribute to the overall reduction of the
robot's weight, which is essential for maintaining stability and balance.
Additionally, lighter wheels require less power to rotate, which can lead to
improved battery life and increased operational efficiency.
• Stability: When the wheels are rotating, they should maintain the same speed and
direction as the motor shaft without any deviation. It is crucial to ensure stability as
the wheels are responsible for transferring control action from the motor shafts to
maintain or restore the robot's balance. Therefore, stability is the most critical
requirement for wheels.
• High friction surface: The outer surface of the wheel should be crafted from a
high-friction material, such as rubber, to ensure a firm grip on the surface on which
the robot will travel. This will help maintain traction and prevent slipping, ensuring
the robot's smooth movement.
• Uniformity
• Good Coupling with the motor shaft

Wheel type Advantages Disadvantages

Most common type. Not fit for Off-Road expeditions.


Normal Type Two degrees of freedom. Best fit for smooth terrain.
Wide range of sizes and mounts.

Off Road A variation of the tire wheel. Not fit for precision movement.
wheels Two degrees of freedom. Expensive in comparison to the
Fit for rough environments. alternatives.
Mecanum Multidirectional wheel precision Is a concern.
wheels Fit for indoors and outdoors Not that many sources available with
environments. such use case (self-balancing robot).
Different left and right wheels.
omni wheels Wheels with rollers at 90 degrees. Inapplicable for a self-balancing robot.
Four degrees of freedom. Only works for 4 wheels configs.
Fit for indoors environments. Expensive and hard to find with the
current market.

24 | P a g e
Mechanical Structure Choosing the Wheels

Once we had a clear understanding of the wheel requirements, we conducted market


research to identify several types of wheels that would meet our needs. The resulting table
outlines the wheels we found:
The figures below show types of wheels illustrated in previous part:

Figure 29 Normal wheels Figure 30 Off road wheels

Figure 32 Omni wheel


Figure 31 Mecanum wheels
Upon conducting our market research, we have selected a wheel that meets all the
requirements we identified earlier in the design process. Specifically, we have chosen two
wheels, each with a diameter of 8.5cm and a depth/thickness of 3.4cm. The weight of each
wheel is 50 GM, and the weight of the coupler is 20gm. The following image depicts the
actual wheels that we have selected.

25 | P a g e
Electric Circuit Design Schematic Design

Chapter 4 Electric Circuit Design


4.1 Schematic Design
To design an electric circuit diagram for the robot, a software called EasyEDA was used
due to its simplicity and having a relatively easy to learn curve. It’s also the main program
we used to design the PCB of the robot.

Figure 33 SBR schematic diagram

Our electrical system is a combination of:


• 1x Arduino NANO board.
• 2x DRV8825 stepper motor drivers.
• 1x MPU-6050 Gyroscope.
• 1x HC-05 Bluetooth module.
• 1x 12V-to-5V voltage regulator.
• Multiple protection and regulating elements (diodes, resistors, fuse, capacitors,
…etc.).

26 | P a g e
Electric Circuit Design Schematic Design

The step and direction pins of the drivers are connected to the digital pins (D2, D3, D4,
D5) preferably, the step pins are connected to the analog out capable digital pins for more
smooth and accurate output. However, any other pin can work just fine. The micro-stepping
pins on the drivers (MS0, MS1, MS2) were connected to digital pins (D10, D11, D12)
together to make sure that both motors are running on the same micro-stepping resolution.
The drivers output pins (A2, A1, B1, B2) were connected to 4 female pin headers for easier
connection to the stepper motor coils. Finally, the power pins for the logic of the driver
VDD and GND are connected from a +5V voltage regulator outputted from the Arduino
and the motor power pins VMOT and GND are connected from the external power supply
taking into consideration the capacitors between these two pins to eliminate any unwanted
voltage spikes.
For the MPU-6050 the connections are similar to earlier chapters where the VCC and GND
pins are connected from the voltage regulator while the SCL and SDA pins are connected
to the analog pins A5 and A4 in the Arduino, respectively. Only A5 and A4 pins will work
as they are designed to be responsible for the I2C protocol.
For the HC-05 Bluetooth module, the Tx and Rx pins are connected to Digital pins D6 and
D7 (despite the recommend connections - direct connection to the Arduino’s Tx and Rx
pins- from online sources due to a noticeable unwanted behavior from the Arduino), the
5V pin is connected to the Voltage regulator output, and the GND pin to the system’s main
ground path.
For the regulator, the input voltage is directly fed from the system 12V supply after the
protection layers, the ground is the same as the supply, and the output 5V are connected
the MPU-6050, the HC-05 Bluetooth module, and the Vin pin on the Arduino to insure no
overvoltage spikes to the main components.
The system includes five layers of protection for the power circuit to help counter any
potential mishaps, these protections include:
• a 2200uF capacitor to counter input supply voltage ripples.
• a Switch to turn on and off the system.
• A diode to counter reverse polarity (in case of reverse polarity of the input supply).
• A DC fuse to protect against over current (up to 3 Amps).
• A voltage divider circuit to check for the current supply voltage output.

27 | P a g e
Electric Circuit Design Breadboard Test Setup

4.2 Breadboard Test Setup


The next step was to test out the system output relative to the design schematic to ensure
the system reliability to provide the expected outputs.
Using breadboards helps during the testing phase to indicate connections issues and for
easier replacement of any broken or unwanted connections before finalizing the system
design.

Figure 34 breadboard schematical representation

However, the breadboard is not the best option for the finished system due to its lack of
stable connections and bad mounting to sensitive components like the MPU-6050 as any
small tilt in the module will lead to an offset error in the readings that will be translated to
an inaccurate decision by the PID controller.

28 | P a g e
Electric Circuit Design Printed Circuit Board (PCB) Design

4.3 Printed Circuit Board (PCB) Design


The PCB was designed in EasyEDA (standard edition) v6.5.22. using the finalized
schematic from the testing phase in order to eliminate any possible human error (in terms
of connections and mounting issues).

Figure 35 PCB final design inside EasyEDA software

The material used is FR4 sheets as they are electrical insulators with high dielectric strength
[19]. They also feature a high strength-to-weight ratio and are lightweight and resistant to
moisture. Add this to their relative temperature resistance, and FR4 material can perform
well in most environmental conditions [19].

The PCB dimensions are 135mm by 75mm (101.25cm2). The dimensions were made
relative to the mechanical structure design to ensure a more centered weight distribution.
All control circuit traces are made with trace width of 1.5 mm to withstand up to 2 Amps
of current with the copper layer thickness of 2 oz/ft2. While the power traces width is 2 mm
to withstand 3-4 Amps. There is a clearance between each trace of about 0.5mm to insure
no shorting between traces during the printing stage.
The PCB was plated with soldering mask to protect the system against possible shorts
between close pins during the soldering phase.
The PCB utilizes double layers in terms of having the back layer mainly for grounding.

29 | P a g e
Electric Circuit Design Printed Circuit Board (PCB) Design

The traces routing was made automatically using the EasyEDA software to find the best
copper route, sometimes the auto tracing might fail due to bad positioning of the elements
of the circuit, with slight repositioning the auto router can finish routing successfully.
The software is capable of producing 2D and 3D images to preview the expected PCB
output from the printing stage.

After finalizing the design, a GERBER file is generated using the software to send off to a
PCB manufacturing company to be printed (usually takes around 2 – 15 business days).

Figure 36 PCB after assembly

30 | P a g e
wireless Control Application: Why Use a Mobile Application

Chapter 5 wireless Control Application:


5.1 Why Use a Mobile Application
The next step was to decide in which way we would communicate with the robot in order
to control its motion. Some options suggest a direct connection between a device (i.e.,
laptop, …) and writing out a command output using the serial monitor in the Arduino IDE
software.

Figure 37 physical connection representation.

However, this option is quite limiting as it requires a stable physical connection between
the Arduino micro-controller and a commanding device (i.e., laptop, …). So, it’s best suited
only for testing and uploading the main Code on the Arduino microcontroller.
Another method is using a nun chuck controller to communicate with the robot Bluetooth
module, using this method will help remove any physical connection with the balancing
robot granting us a more stable and wider range of motion for our needs.

Figure 38 non-chuck controller

Sadly, this method has its downsides as it requires more hardware to collect the nun chuck
position data, encode it down to a byte layer, and to transfer this data to the robot which
add a higher degree of complexity that is hard to manage.
This leads us to best option we found and that’s building a mobile application that mitigate
all the complexity of the nun chuck while fully utilizing a much simpler, easy to modify,
adapt, and use by any phone with a Bluetooth connection.

31 | P a g e
wireless Control Application: MIT APP Inventor

5.2 MIT APP Inventor


Due to our lack of knowledge in java coding and application UI design, making an
application from scratch was almost impossible to do within the timeframe we had to finish
this project. So, the best option we found was to utilize a website made by Massachusetts
Institute of Technology that helps small project creators to design a simple app suited for
their needs. For our case, we used this website to design a simple mobile application that
uses the Bluetooth connection of a mobile phone to connect to the Arduino through the
HC-05 Bluetooth module and also send and receive commands to control the motion of the
balancing robot, estimate its input voltage, and indicate its current state of motion.

Figure 39 the designer tap page of the MIT App inventor website

5.3 Application Versions


During the course of our project, we implemented multiple versions of the application that
got progressively more advanced, user friendly, and more customizable. Here are some of
the more noticeable versions of the application.
5.3.1 Application Version 4
This version features a quite straightforward design, an easy to
implement user interface, and self-explanatory button scheme.
This was first implemented during the late components testing phase
to experiment with having the full system connected with each other
to help accustom us with app making and Bluetooth communication
with the robot.
The design included:
• Bluetooth connection button.
• Six buttons each send a numerical value that executes a certain
if condition in the Arduino code based on the received value
from the Bluetooth application. Figure 40 application
version 4

32 | P a g e
wireless Control Application: Application Versions

5.3.2 Application version 8


This version included the first custom UI design with clear set
goals for the user. This design was used to make a troubleshooting
interface for the user to debug any physical or code related issue
depending on the physical output of the system in response to sent
command from the application.
This application was designed to be integrated with an Arduino
code that contained:
• An MPU level meter test with the motors.
• A motor rotation and speed variation test loop.
• A planer direction keypad to assess the robot responsiveness.
• A stop action button to terminate any cycling action during the
troubleshooting.
While this application provided a much need functionality it Figure 41 Application
certainly may cause a slowdown of operation during the final version 8
implementation of the robot control loop as each test loop requires
lots of processing time that is not suitable for the robot required
response time (about 4ms).
5.3.3 Application version 14
This version provided a very advanced control scheme with more
motion direction related controls and a much clearer and user-
friendly UI design.
This app is perfect for the standard control scheme for our final
code as it included:
• More advanced direction control (including diagonal rotations).
• State of action indicator in the middle.
• Serial data reader.
• An emergency stop button to clear any windup mishaps or to
temporarily disable the controller output.
This was the potential candidate for the final Bluetooth application
design until we decided to produce an even more advanced version.
Figure 42 Application
version 14

33 | P a g e
wireless Control Application: Application Versions

5.3.4 The Final Application Version

Figure 43 Final Application version

This version contained a similar control scheme to the previous version with few key
differences and the addition of a more control settings, which included:
1. A speed mode switcher
this included two modes that the user can switch between
Steady mode (the default): provides a slow turning and target speeds that makes the robot
move better in a planer terrain while saving the battery life; making the robot last for longer
periods of time.
Speed mode: provides a much faster turning and target speeds that helps the robot in the
more torque demanding scenarios like climbing ramps, off-road terrain and more. Hover
this mode is best used for short periods of time as it’s a more power demanding mode.
2. Battery indicator
This is a button that requests the current data stored in the battery voltage variable on the
Arduino code that is set through the voltage divider circuit (refer to the Electric circuit
design chapter). Then, it displays the received value on the state viewer box on the
application, giving the user the current available voltage in the supply batteries.

34 | P a g e
wireless Control Application: Application Block Diagrams in MIT App Inventor

5.4 Application Block Diagrams in MIT App Inventor


Here are the code blocks from the final application on the MIT app inventor website.
5.4.1 Main Control Screen
Bluetooth Connection Blocks: it involves opening a list of the paired Bluetooth devices
with the mobile device, establishing a connection with the Bluetooth module, and
indicating if the connection was made successfully or not with a text label.

Figure 44 Bluetooth connection blocks

Direction Keypad: this includes a two executed actions per direction button where:
• On touch down and holding the key, the app sends a byte of data that indicates to the
robot to start moving in this direction and indicate the current state of motion on the
state viewer label.
• When the user releases the button (touch up), the app sends a signal to the robot to reset
the received byte back to zero to tell the robot to return to its stable position.

Figure 45 direction key-pad block diagram.

35 | P a g e
wireless Control Application: Application Block Diagrams in MIT App Inventor

Speed Mode Switcher


Here is the block diagram for the buttons that switch the speeds of the robot. By sending a
signal each to modify the target speed and the turning speed memory on the Arduino code.
It also indicates the switching to the user by swapping between two images of the button
to display for the user what is the current active speed mode of the robot.
Here also is the block that switches the robot to the serial monitor screen to initiate serial
communication.

Figure 46 Speed mode switchers

Battery Indicator
This works by sending a signal that executes a serial.write command on the arduino, it first
checks for the bluetooth connection and makes sure that there is an avialable byte to recive
from the bluetooth module, then it stores the recived byte in a global variable and sets the
state indicator box to show the current value stored in the global variable.
When the user unhold the button the robot nolonger recive any data from the robot (returns
to state zero).

36 | P a g e
How To Balance a Self-Balancing Robot Mechanical Requirements And Limitations

Chapter 6 How To Balance a Self-Balancing Robot


6.1 Mechanical Requirements And Limitations

Figure 47 our self-balancing robot.

6.1.1 Weight And Torque Limitations


The weight of the robot should not be too heavy or too light. When a control action is
applied to balance the robot, if the robot is too light, it may become destabilized and react
violently. On the other hand, if the robot is too heavy, the torque of the steppers may not
be sufficient to support the weight, and it will not stabilize even in the absence of external
forces [20].
Therefore, it is important to calculate the robot's weight before selecting the motors to
ensure that the chosen motors can provide sufficient torque to balance the robot [21].
Using Newton’s Law:
𝑇𝑖𝑛𝑒𝑟𝑡𝑖𝑎𝑙 = 𝑇𝑔𝑟𝑎𝑣𝑖𝑡𝑦 + 𝑇𝑎𝑝𝑝𝑙𝑖𝑒𝑑
𝑇𝑖𝑛𝑒𝑟𝑡𝑖𝑎𝑙 = 𝑚𝑔𝐿𝑠𝑖𝑛𝜃 + 𝑇𝑎𝑝𝑝𝑙𝑖𝑒𝑑
𝑇ℎ𝑒𝑛 𝑇𝑎𝑝𝑝𝑙𝑖𝑒𝑑 = 0
𝑇𝑖𝑛𝑒𝑟𝑡𝑖𝑎𝑙 = 𝑚𝑔𝐿𝑠𝑖𝑛𝜃
𝑡𝑚𝑎𝑥 = 𝑚𝑔𝐿𝑠𝑖𝑛𝜃𝑚𝑎𝑥
𝑤ℎ𝑒𝑟𝑒 𝜃𝑚𝑎𝑥 = 90°
When we start the robot, it should normally stabilize with the steppers torque at 0°
(vertically) after calibrating the gyro at 90° (horizontal). We should also consider a safety
factor in the torque calculation by 1.5 – 2 to make sure that the torque is enough to stabilize
the robot under rough circumstances. [22]
6.1.2 Height
The weight of the robot is not the only factor that affects its stabilization.
The robot’s body length also has an impact on the robot’s stability. If the
body length is too tall, the robot may have a violent reaction to the
control action, making it unsuitable in the torque calculations [21]. This
is because a tall robot has a higher center of mass, which makes it more
difficult to balance. In addition, a taller robot may have longer legs or
wheels, which can increase the distance between the center of mass and
the contact point with the ground, making it more unstable.

37 | P a g e
How To Balance a Self-Balancing Robot Mechanical Requirements And Limitations

Therefore, when designing a self-balancing robot, it is important to consider not only the
weight but also the dimensions of the robot, including its height, width, and length, to
ensure that it can be stabilized properly. A shorter robot with a lower center of mass and a
shorter distance between the center of mass and the contact point with the ground will be
more stable and easier to control. However, it is also important to consider the application
of the robot when deciding on its dimensions. For example, if the robot needs to navigate
over rough terrain or obstacles, a taller robot with larger wheels or legs may be more
suitable.
6.1.3 Wheels
The diameter and type of wheels used in a self-balancing robot can have a significant
impact on its balance and stability [23]. In our previous experiments, we found that using
normal wheels with a small diameter was not suitable for balancing the robot, as they were
not able to even make the robot standstill. This is because the small diameter of the wheels
resulted in a low contact area with the ground, which made it difficult for the robot to
maintain its balance.
To address this issue, we switched to using off-road wheels with a greater diameter. These
wheels had a larger contact area with the ground, which improved the robot's stability and
allowed it to move on rough surfaces with ease. The larger diameter also increased the
torque provided by the wheels, which made it easier for the robot to maintain its balance.
Therefore, when designing a self-balancing robot, it is important to consider the diameter
and type of wheels used to ensure that they can provide sufficient torque and contact area
with the ground to stabilize the robot. The choice of wheels will depend on the application
of the robot, as well as the terrain it will be operating on.
6.1.4 Center of Gravity
The center of gravity is a critical factor in stabilizing a self-balancing robot. If the center
of gravity is in a low position (closer to the wheels), it can cause imbalance, as we
experienced with our three-racked-body robot. Initially, it was difficult to balance the robot
with three racks due to their heavy weight and low center of gravity. However, we were
able to improve the balance by changing the arrangement of the racks and moving the
battery to the top rack. This centered the heavy weight at the top of the robot, which lifted
the center of gravity away from the wheels and made it easier to maintain weight balance
[21].
To further improve the robot's stability, we also reduced the distance between the top and
middle rack. This further lifted the center of gravity and increased the robot's stability. By
optimizing the arrangement of the racks and center of gravity, we were able to achieve a
stable and well-balanced robot.
Therefore, when designing a self-balancing robot, it is important to carefully consider the
placement of the robot's components and ensure that the center of gravity is positioned in
an optimal location for stability. The location of the center of gravity will depend on the

38 | P a g e
How To Balance a Self-Balancing Robot Mechanical Requirements And Limitations

weight and distribution of the robot's components and may need to be adjusted during the
design process to achieve optimal stability.
6.1.4.1 Center of Gravity Calculations
as the self-balancing robot is based on the concept of an inverted pendulum, there are some
important parameters that must be calculated:
• Weight of the cart
• Weight of pendulum
• And the center of gravity (COG) of the pendulum

For the self-balancing robot, we can consider the hinge of the pendulum the wheel axes.
This makes the wheels, the cart and everything else the pendulum.
The center of gravity is simply the average location of the weight of the robot’s body.
Calculating the center of gravity for a system
The center of gravity of the robot can be calculated by taking the center of gravity of the
individual components and doing vector addition of the weighted position vectors. For each
of the axis, x, y and z, the center of gravity is found with:

Where:
, and : are the weight of components 1, 2 and 3 making up the system.
, and : are the coordinates of the center of gravity for the first component.
, and : for the second
, and : for the third.
Determining the center of gravity of a self-balancing robot can be challenging due to its
many components with unknown centers of gravity. However, we can apply the same
techniques used for motor vehicles to determine the center of gravity of the robot. We
neglect the center of gravity in the x- and y-directions, as they are symmetrical and do not
affect the mathematical model. Instead, we focus on the center of gravity in the z-direction
and calculate its height.
For motor vehicles, the center of gravity is often determined by weighing the vehicle at
each wheel and measuring the wheelbase. We can apply the same techniques to the self-
balancing robot to determine its center of gravity. This method involves weighing the robot
at two points, one at the rotation axis of the motors and the other as close to the top as

39 | P a g e
How To Balance a Self-Balancing Robot Mechanical Requirements And Limitations

possible and measuring the distance between them. The weight and distance measurements
can then be used to calculate the height of the center of gravity above the rotation axis [24].

Figure 48. In a motorcar, the weight of the vehicle at each wheel and measuring the wheelbase.

With these measurements we have the car’s total weight W which we can model as a point
mass at the center of gravity.

Since the car is not tipping over, it can be estimated that the center of gravity (COG) is located
somewhere between the front and rear axles of the car. Additionally, since the car is not
moving, according to Newton's laws, the scales are applying a force equal to the weight
to and of the car, acting in the opposite direction. Let us call these forces and .

The longitudinal COG of the car can be determined by considering the moment about the rear
wheel. Since the car is not rotating around this point, the moments resulting from the weight W
at the COG and the force Rf at the front wheels cancel each other out. Mathematically, this can
be written as:

From here we can make b the subject and thus determine the center of gravity in the
longitudinal direction.

40 | P a g e
How To Balance a Self-Balancing Robot Mechanical Requirements And Limitations

Applying to the equation to the robot

• When calculating the center of gravity of the robot, we remove the wheels and only
weigh the pendulum part to simplify the calculations.
• To weigh the robot, we select two points at the bottom and top of the robot separately.
One point is chosen at the rotation axis of the motors to simplify the process, while the
other point is chosen as close to the top as possible. The distance between these two
points is then measured to determine the distance L.
• We determine the weight of the robot by adding the weights of the two chosen points
at the bottom (Wr) and top (Wf) of the robot. This method provides sufficient accuracy
for our purposes.
• For our calculations, we define the top of the robot as corresponding to the front of the
car and the bottom as corresponding to the rear.
• Using the measurements, we obtained; we can now enter them into the equation to
calculate the height of the center of gravity (b) above the rotation axis of the robot.

It's important to note that accurate measurements and calculations are crucial for
determining the center of gravity of a robot, as even small errors can have a significant
impact on its stability and performance. Therefore, it's important to take care and double-
check all measurements and calculations to ensure accurate results.

𝐿 ∗ 𝑅𝑓
𝑏=
𝑊

𝑊 = 𝑊𝑟 + 𝑊𝑓
Where:
W: total weight of the robot.
Wr: the weight at the bottom of the robot.
Wf: The weight at the top of the robot.
Rf: the force at the front wheels.

41 | P a g e
Control Method: PID Controller PID Controller in Our Application:

Chapter 7 Control Method: PID Controller


The control algorithm used to balance the position of the self-balancing robot is
the Proportional Integral Derivative (PID) controller, which is a widely used feedback
mechanism in the industry. The PID controller is a three-term controller that attempts to
adjust and correct the error between the measured process and the desired process and
output the appropriate measure to adjust the process.
The PID controller calculates an error value e(t) as the difference between a desired set
point and a measured process variable. It then corrects the error using proportional,
integral, and derivative terms. The controller attempts to minimize the error over time by
adjusting a control signal. [25]

Figure 49. Block Diagram of PID Controller

8.1 PID Controller in Our Application:


By applying the PID controller terms on our project, in the figure, it is shown self-
balancing robot in two main positions: balanced state and tilted position.

The error is calculated by getting the difference between the actual tilting angle sensed by
the MPU 6050 and the desired set point tilt angle which will be in our case 0°. The
controller generates the suitable control action and sends it to the motors to minimize the
error and balance the robot. [26]

Figure 50. The control mechanism used in self-balancing robot.

42 | P a g e
Control Method: PID Controller PID Controller in Our Application:

The PID controller parameters are tuned to find the suitable gains to balance the system.
Step 1: setting the three gains to zero. Then, we increase the 𝐾𝑝 value gradually until the
system starts to oscillate by then we adjust the 𝐾𝑝 value until the system is nearly stable
with a steady state error.
Step 2: we increase the value of 𝐾𝑑 gradually until the system starts to vibrate when
applying a high disturbance in short period of time. Then, we start adjusting the 𝐾𝑑 till the
system oscillations disappear. However, having a high 𝐾𝑑 value may cause overshoot.
Step 3: we increase 𝐾𝑖 value gradually until any offset or steady state error is eliminated
and corrected. Usually, 𝐾𝑖 values are small because when its value increases the system is
more prone to instability. [26]
The PID controller use the following equation:
𝑡
𝑑𝑒(𝑡)
𝑢(𝑡) = 𝐾𝑝 𝑒(𝑡) + 𝐾𝑖 ∫ 𝑒(𝑡)𝑑(𝑡) + 𝐾𝑑
0 𝑑𝑡
Where:
- 𝐾𝑝 is proportional gain.
- 𝐾𝑖 is integral gain.
- 𝐾𝑑 is derivative gain.
- 𝑢(𝑡) is the control action generated by the PID controller

Figure 51. The closed loop control system of the self-balancing robot. [27]

The angle set points where the robot has to maintain its default position and PID values are
fed to the Arduino using the mobile application through the Bluetooth device. 𝐾𝑝 is the
proportional term, which multiplies with the error and speeds-up or slows-down the
response. Any change in 𝐾𝑝 makes the bot to balance at another set-point.
𝐾i is the integrating term, which reduces the steady-state error and smoothens the motion
of the robot. But a slight change in this integrating factor may cause excessive response to
the system.

43 | P a g e
Control Method: PID Controller Tuning Techniques

𝐾d is the derivative term. It is used to increase the reaction time of the robot. However,
increasing it too much may cause the robot to be unstable. [27] [25]

8.2 Tuning Techniques


There are some tuning techniques that can be used to find the best gain values of 𝐾𝑝, 𝐾𝑖
and 𝐾𝑑 that gives a stable response of the system.
The tuning technique used was trial and error method which is the most common to start
with to get an approximate value of the needed gains. [28]
8.2.1 Trial and Error
Parameter Rise Time Overshoot Settling Steady-State Stability
Time error
𝐾𝑝 Decrease Increase Small Decrease Degrade
Change
𝐾i Decrease Increase Increase Eliminate Degrade
𝐾d Minor Decrease Decrease No effect in Improve
Change theory

We also tried an alternative configuration that helped reduce overshoots and oscillations in
the system. This was achieved by multiplying the gain controller by the output instead of
using the PID in a conventional way, which involves calculating the error and multiplying
it by the gain. This method acts as a filter to the system, allowing the robot to balance faster
than before and reducing the settling time. Furthermore, this approach reduces oscillations
and is particularly effective since the setpoint in our system is not zero, which means that
the robot is slightly inclined to move. By reducing the overshoot resulting from the error
and the oscillations, this method helped improve the overall performance of the system.
[29]

Figure 52. Closed-loop step response of PI control system. line 1: the response from the original structure;
line 2: response from the alternative structure.

44 | P a g e
Control Method: PID Controller Mechanical System Simulink Model

The closed-loop step responses for both controller implementations are simulated and
compared in the previous figure, which shows that the original PI closed-loop control
system has a large overshoot, in contrast, the alternative PI closed-loop control system has
avoided this overshoot. By comparing the closed-loop transfer function from the original
PI controller structure (2) with the one from the alternative structure (1), we notice that
both transfer functions have the same denominator; however, the one from the original
−1
structure has a zero at τ . Because of this zero, the original closed-loop step response had
𝐼
1
an overshot. In other words, the alternative structure is equivalent to a filter being
τ𝐼 𝑠+1
added to the reference signal, which is, in fact, a two-degrees of freedom control system.
It is important to point out that the implementation of PI controller using the alternative
structure is useful for the outer-loop control systems where an overshoot response to a
reference signal is not desirable. However, if the PI controller is used in an inner-loop
control system, then the original implementation structure is recommended because it
provides a faster dynamic response and overshoot to reference signal is not an issue in this
situation. [29]

𝑌(𝑠) 𝐾𝑐
= (1)
𝑅(𝑠) = 𝜏𝐼 𝑠 2 (𝑠+1)3 + 𝐾𝑐 ( 𝜏𝐼 𝑠 + 1)

𝑌(𝑠) 𝐾 ( 𝜏 𝑠 + 1)
𝑐 𝐼
3 + 𝐾 ( 𝜏 𝑠 + 1) (2)
= = 𝜏 𝑠2(𝑠+1)
𝑅(𝑠) 𝐼 𝑐 𝐼

8.3 Mechanical System Simulink Model


To build a 3D mechanical model for the two-wheeled self-balancing robot we use
Simulink, to assess the robot and tune it in a safe way before implementing it on hardware
also a mechanical model is used to estimate the system’s transfer function using the system
identification toolbox.
In this model we use the PID controller to get auto-tuned values or trial and error values to
balance the system. [30] [31]

Figure 53. The mechanical system of a two-wheeled self-balancing robot.

45 | P a g e
Control Method: PID Controller Mechanical System Simulink Model

8.3.1 Blocks Definition


Solver configuration: it is used to perform the calculations of the system.
World frame: This block represents the global reference frame in a model. Directly or
indirectly, all other frames are defined with respect to the World frame as it is the
ultimate reference frame.
Mechanism configuration: This block specifies the gravity and simulation parameters of
the mechanism to which the block connects.
Rigid transform: It is a block used to connect solid blocks with each other’s so they can
move as a single unit during simulation.
Revolute joint: This block gives a degree of freedom to the motion of the robot’s body,
and it will allow the chassis to swing like a pendulum.
Prismatic joint: This block will allow the body to move back and forth and stabilizing
the body in an upright pose with a suitable control action. [31] [30]
8.3.2 Steps To Build a Model
- We start building the model using MATLAB, typing simnew in the command
window to display a Simscape multibody model template equipped with the
needed parts to start building the model.
- We start by building the wheels of the robot, we open the library to get the
element responsible for wheels:
• Library
• Simscape
• Multibody
• Body elements.
We get the cylindrical solid block and we adjust its dimensions and mass to build the tires
and wheels [32] [30]

Figure 54. Setting the body element dimensions to simulate the real-life wheel.

46 | P a g e
Control Method: PID Controller Mechanical System Simulink Model

The components are then grouped into a subsystem.

Figure 55. A subsystem for the left wheel and tire.

To make the right wheel, we repeat the same steps.


Then we connect both wheels with motors in cart subsystem.

Figure 56. Cart subsystem where there are two stepper motors connected with the wheels.

Then, we build the robot’s body which consists of three rectangular racks attached together
with four rods, we start building the rectangular racks using the brick solid block and
adjusting its dimensions properly and their mass. We then get a cylindrical solid block and
adjust it.
To link both the racks and rods together, we use the rigid transform block by adjusting
where the rods will connect with the racks then we put them all in a subsystem to represent
the chassis. [32] [30]

47 | P a g e
Control Method: PID Controller Mechanical System Simulink Model

Figure 57. Chassis subsystem and the connection of rods and racks using the rigid transform block.

We connect the chassis and the cart with a revolute joint block to make the robot’s body
swing like a pendulum and then we connect the prismatic joint block this will make the
robot move back and forth and with a proper control action coming from the PID controller,
it will eventually stabilize the body.
We read the angle of inclination of the chassis provided by the position of the revolute
joint, so we change its sensing setting to read the position, also, we set the force in the
prismatic joint block to be provided as an input and the motion to be automatically
computed.

Figure 59. Prismatic joint block


Figure 58. Revolute joint block setting its actuation force to be
setting its sensing to position provided as an input.

48 | P a g e
Control Method: PID Controller System Identification Toolbox

We use a gain to convert the output position angle from radians to degree.
We use a step block to give an initial inclination for the robot instead of applying an
external force.
We will then adjust the PID block using an autotune feature to get a suitable PID values to
balance the robot in the simulation. [32] [30]

8.4 System Identification Toolbox


System Identification Toolbox in MATLAB is a tool for dynamic system modeling, time-
series analysis, and forecasting. We can easily use it in dynamic relationships and models
just like our project to measure variables to create transfer functions, process models, and
state-space models in either continuous or discrete time while using time- or frequency-
domain data.
This toolbox is used in order to estimate a transfer function from the mechanical system
created using Simscape. Typically, the transfer function parameters are unknown. In order
to calculate the motor's parameters experimentally, the system is put in a unity feedback
configuration with a gain controller. The set point is varied using a square wave pattern.
The input force and the robot’s position are recorded. This enables us to form a set of
equations in the unknown parameters. Solving the resulting equations will enable us to
construct a transfer function for the self-balancing robot. [31]

Figure 60. Setting the PID block to a proportional controller.

The transfer function that relates the force applied on the body of the robot which is the
input on the system and the position of the robot after applying the force which is the
output.
Normally, a self-balancing robot has a transfer function of a 4th order but after some
approximations we got a 3rd order system.

49 | P a g e
Control Method: PID Controller System Identification Toolbox

Steps to open system identification toolbox to get the transfer function:

1. To run the graphical user interface (GUI) of the Identification toolbox, type "ident" at
the MATLAB in the command window. The GUI contains the input-output parts of
data (in the left blocks) and the estimated transfer functions (in the right blocks).
2. Click at the arrow next to "Import Data" and select "Time Domain Data". The
window for importing data will appear. Insert data in the "Input" and "Output" taps.
3. Select the "sampling interval". You may click the box next to data plot to see plots of
the input and output.
4. Click on the arrow next to the Estimate button. Then, select "Transfer Function".
Select the number of poles and zeros.
5. Drag the appropriate model to the “To Workspace” button. The identification steps
can be repeated for different sampling intervals for best results. [31]

The obtained discrete transfer function is:

This is the estimated transfer function with 3 poles and 2 zeros.

50 | P a g e
Arduino Codes Used This Project MPU-6050 Calibration Code

Chapter 8 Arduino Codes Used This Project


All the codes used here can be found in the appendix section. This section is mainly focused
on explaining the code’s main idea and how the main parts work.

9.1 MPU-6050 Calibration Code


This code is used in order to acquire the approximate gyro values (x, y, z) for the MPU to
indicate that the robot is currently in an upright position.
The robot is placed on a stand in an upright position then the hardware test is uploaded.
The code checks if there are any I2C devices connected and checks if any of these devices
is an MPU-6050.
The program will output several raw gyro values as well as the balance value. The balance
value is used in the void loop to be used in angle calculations.

Figure 61 the MPU calibration code serial monitor’s output

These values are later combined into a single value (Balance value) that is later used in the
main code calculations to set up a balance point for the PID controller to approach.
It’s worth noting that the value can exist with a marginal error with the range of 100 points
(up or down) and thus it advised to run the code multiple times and average the acquired
balance values for a more accurate set point.

51 | P a g e
Arduino Codes Used This Project Hardware Troubleshooting Tests Code

9.2 Hardware Troubleshooting Tests Code


The aim for this code was to test each component’s individual functionality to help during
any troubleshooting phase. This code provides the user with 4 tests for each individual
component, which are:
• Battery voltage indicator to help identify the current voltage level of the source.
• Bluetooth module connection test with minor control actions (forward, reverse, turn
left, turn right)
• An MPU level meter test to insure the MPU is still working.
• A small forward-reverse cycle to insure the correct operation of the motors.

After uploading the code, the Arduino runs a check to see the current battery voltage of the
input through an analog pin. If the input is smaller than 10.5 volts, the robot won’t start
any other test while generating a pulsating clock that flickers a LED on the Arduino to
indicate low input voltage.
If the battery voltage is higher than 10.5 volts, the system will function and wait for the
user to connect using a Bluetooth device. If the device couldn’t establish a connection, then
that indicates a problem with the HC-05 Bluetooth module.
After connecting the device using a custom application to give out specific signal values
the user then proceeds to choose the test he requires.
After choosing the MPU test (sending an integer value = 5), the system starts to function
as a level meter where the angular orientation of the MPU dictates the motor’s motion
speed and direction. If with changing the position and angle of the MPU no speed or
direction change is observed, then there is a problem related to the system gyroscope.
After choosing the motor test (sending an integer value = 6), the system starts cycling in a
forward and reverse directions. If the two motors didn’t move in the same direction as each
other, then there is an issue of reverse connection of one of the motors.
If the motors didn’t function throughout the entire tests without being in the off state, then
a problem related to the motors, or the drivers is indicated.
While it may not be the most robust code for troubleshooting, it provides basic visual
indications of any issue that may appear during the testing phases of the self-balancing
robot. A further improvement for the code can be made by adding text indicators on the
serial monitor in case of failure in any test or a morse code signal using the built-in led off
the Arduino microcontroller.

52 | P a g e
Arduino Codes Used This Project Main Code of The Self-Balancing Robot

9.3 Main Code of The Self-Balancing Robot


The main code consists of 3 main parts:
• The initial parameters and PID gains.
• The void setup and interruption sub routine.
• The main void loops.

9.3.1 The Initial Parameters And PID Gains


In this section, the user inputs the main parameters acquired by the user through system
identification that defines the system limits. These parameters include:
• Maximum target speed and turning speed.
• Accelerometer calibration value (balance value).
• PID controller gains value.
• The gyro bus address and wire library.

Then the global variables are declared that will be used throughout the code.

53 | P a g e
Arduino Codes Used This Project Main Code of The Self-Balancing Robot

9.3.2 The Void Setup And Interruption Sub Routine


Starting the void setup, the serial port is set to 9600 kbps and the I2C bus is set as master
and initializing the I2C bus clock at 400kHz.

Then in order to generate a variable pulsating control signal for the stepper motor a sub-
routine is made that needs to be executed every 20ms.

Then we set up the MPU parameter ranges to its maximum scale for more accurate readings
by modifying the internal registries of the MPU using the wire library.

The digital pins connected to the stepper motor drivers are then set as output with the pins
connected to the micro-stepping pins are set to output a 1/4 micro-stepping degree.

54 | P a g e
Arduino Codes Used This Project Main Code of The Self-Balancing Robot

A for loop is made to run for 500 loops throughout which the MPU takes multiple readings
for the Yah and Pitch angles to identify its current position relative to its surrounding area.
Then the output calibrated values are divided by 500 to average out the gyro offset. Finally,
a loop timer is initialized to start at the end of the next cycle.

The interruption subroutine is used to throttle the stepper motor speed resulted from the
PID controller outputs to the left and right motor to minimize the impact of the nonlinear
behavior of the stepper motors.

9.3.3 The Main Void Loops


The main loop requires at least 4ms to execute each command available in the loop before
repeating the execution. The loop starts by requesting a data byte from the Bluetooth
module which contains the main controller commands embedded into each bit. Then after
a set period the received byte resets as a safety measure (we choose every 5 seconds).

55 | P a g e
Arduino Codes Used This Project Main Code of The Self-Balancing Robot

After which a small battery checkup is made to ensure that the input voltage does not drop
below a critical level that might not be sufficient to operate the stepper motors.
This is done through using the voltage divider circuit output mentioned before and
converting it into an analog signal that the Arduino compares to a set value. If the voltage
divider output is lower that the set point the system does not start and the led on the Arduino
is lit up to signal “low battery” to the robot user.

After the initial checks, two bytes are then requested from the MPU to set the starting
acceleration speed of the loop. Then we add the calibrated value to specify how far are we
from the correct position in order to balance. In order to avoid later division by zero, a
limiter condition is used. Then using the resulted value we calculate the current pitch angle
of the robot. If the accelermoter angle is almost zero. The main PID controller loop starts
to operate in this loop.

After that a calculation is made to figure out the current traveled distance during the
excution of this loop for later use.

56 | P a g e
Arduino Codes Used This Project Main Code of The Self-Balancing Robot

Not every gyro is mounted 100% leveled with the axis of the robot. This could be caused
by not using proper mounting sockets or a problem during manufacturing. To compensate
for the misalignment, a small angle correction is needed when the robot is rotating is
applied through these lines of code.

After completing the gyro angle calculations and corrections, the PID controller
calculations start. A variable is used to store the PID error, then a small brake function is
used to lower the PID output from the last loop. Afterwhich, the Ki controller gain is
calculated and then limited to the maximum control output. Then the PID controller output
is calculated using the gain values we inputed from the initial steps while also making sure
to avoid overshooting the control signal using a limiter function. A small deadband
function is used to stop the motors when the PID controller output approaches the balance
state of the robot.
A small safety protocol is made to turn off the motors and reset the PID memory to 0 in
case the tips over or the battery is low or the robot fails to start.

57 | P a g e
Arduino Codes Used This Project Main Code of The Self-Balancing Robot

When the PID controller outputs are ready, the values are then sent to each motor control
variable separately for later controls. Then a series of condition function is made to control
the robot movement using the Bluetooth controls. By dissecting the received byte into bits,
each bit will represent a variable that can be modified.
In our case we used the first 8 bits to represent :
• Forward movement
• Backward movement
• Turning left
• Turning right
• Emeragncy stopping
• steady speed mode
• fast speed mode
• battery voltage indicator
Each bit modifies the PID controller output for each motor separately to be able to turn and
traverse with a much higher degree of freedom than just moving forward and reverse.
A check function is made to lower the PID setpoint till it approaches zero incase no forward
or backwards commands are given

58 | P a g e
Arduino Codes Used This Project Main Code of The Self-Balancing Robot

To compensate for the non-linear behavior of the stepper motors, the following
calculations are needed to get a linear speed behavior. The resulted pulse signals are
copied to be later used in the interruption routine.
Finally, the loop timer is recalibrated to insure a full loop time of 4 milliseconds (the time
needed by the MPU to sense and send its current position reading for the next loop).

59 | P a g e
Conclusion and Future work Conclusion

Chapter 9 Conclusion and Future work


10.1 Conclusion
The self-balancing robot provides a good learning experience to those who hope to learn
how to implement PID controllers, learn how to prototype (electric circuit design, PCBs,
basic mechanical structures), have a moderate knowledge on stepper motors and drive
systems, accomplish full control of a MPU-6050 gyroscope, and have a starting point in
the world of embedded systems and robotics. This project achieves its goals through
opening its implementors to the practical side of control systems by guiding us through a
journey of structure designing, electrical circuits implementation, controller tuning through
various means, Interface design and much more. The project fluidity helps in opening the
door to much more complex implementations as it does not limit to standard design
principles (the sky is the limit).

10.2 Future Work


The self-balancing robot does not dictate a certain implementation technique in terms of
circuit design, mechanical structure design, different electrical components and more. So,
here we will be mentioning some of the possible improvements that can be done to this
project and also mention other control algorithms that may provide a much better response
than the PID controllers.
10.2.1 Better Alternative for The Used Components
10.2.1.1 STM32 Micro-controller:
STM32 is a family of 32-bit microcontrollers. STM32 microcontrollers are more related to
industrial and real-life applications. While the Arduino NANO is fully capable of
controlling self-balancing robots, using the STM32 is an upgrade. STM32 is more powerful
than Arduino. STM32 blue pill has a clock up to 72MHz while the Arduino NANO has a
clock up to 16MHz. This means that the STM32 blue pill can send data or signals to the
stepper motor drivers much faster than the Arduino NANO [33]. Programming the STM32
is more challenging than programming the Arduino, however, it gives a hands-on
experience with a microcontroller widely used in the industry.
10.2.2 TMC2208 Motor Mriver:
Although the TMC2208 is more expensive than the A4988 and the DRV8825, its main
advantage is its micro-stepping resolution. The TMC2208 offers a micro-stepping
resolution up to 1/256 step. This high resolution means less noise coming from the motor
and more stability for the self-balancing robot. The TMC2208 has the same pin diagram as
the A4988 and the DRV8825 so there is no change when it comes to writing the code. [34]

60 | P a g e
Conclusion and Future work Future Work

10.2.3 ESP8266 WI-FI Module:


The ESP8266 WI-FI module can be used instead of the HC-05 Bluetooth module. Although
the WI-FI module is generally more expensive and consumes more power, it has two main
advantages. The first advantage is longer range. Bluetooth module has a range of about
10m while the WI-FI module has a range of about 45m. The next advantage is the faster
transmission speed. The Bluetooth module has a transmission speed of 2Mbps while the
WI-FI module has a transmission speed of 54 Mbps. [35]
10.2.4 Mechanical Structure Improvements
Opting for 3D printing over laser cutting can be advantageous because plastic, which
is commonly used in 3D printing, generally has a lighter weight than acrylic. However, to
utilize 3D printing effectively, it is necessary to have proficiency with the necessary tools,
such as the SolidWorks program.
3D printing offers several advantages over laser cutting. One key advantage is its ability to
produce complex geometries that are difficult or impossible to manufacture using laser
cutting. Additionally, 3D printing allows for the use of multiple materials in a single part,
offering greater design flexibility and the ability to produce parts with varying material
properties. Finally, 3D printing allows for rapid prototyping and design iteration, making
it an ideal choice for producing parts with complex shapes and varying material properties
[36].

Figure 62 ED printed model of a two-wheeled self-balancing robot

61 | P a g e
Conclusion and Future work Future Work

10.2.5 Better Electrical Circuit And PCB Design Techniques


Throughout the project we noticed few details that can be either added or improved
throughout our electric design that er decided to mention most of which in this section, this
includes:
• Better schematic diagram.
• Better configurations for specific components.
• Recommended circuits to include in future designs.
10.2.5.1 Better Schematic Diagram
An issue we encountered during the assembly is the unavailability of some components in
the current market which led to having some missing protection components like the diode.
Another issue was the power wiring of some of the components wasn’t ideal as the majority
of required current by some components had to path through the Arduino first before
reaching their target element.
We addressed all wiring related and missing components issues in the following design:

Figure 63 better Schematic design

10.2.5.2 Better Configurations for Specific Components


Throughout our practical movement testing we noticed small details that had no
documentation on in component placements that result in an unpleasant experience when
tunning the the robot control output

62 | P a g e
Conclusion and Future work Future Work

One example is how to shape the PCB design. It is recommended to have a rounded corner
-aka rounded rectangular- PCB as it’s the most ideal design to prevent concentration of
stress on the edges of the PCB. Also, the screw holes on the PCB should be designed with
the available screws on the market design, the lowest we could find (only in the electronics
shops) was 3mm, the most ideal to be found in every possible shop was 5mm.
This board design is 120x60mm and 10mm radius of the rounded corners, with 5mm holes.
The board can be wider and longer as you see fits your electric components design.

Figure 64 Recommended PCB layout.

another example is the positioning of the Arduino NANO board that had a capacitor in the
way of the micro-USB port which prevented us from directly connecting the I2C bus to the
Arduino board without needing to disconnect the board from the PCB in order to upload a
new code. This can be solved by moving the USB side of the Arduino board to one of the
PCB edges, this way we have a better space to reach with the connector.
Another issue we found is the lack of extra connection points with the Arduino board once
it is connected to the PCB, So, a solution we found was to add an extra pin header for each
pin on the Arduino this way we we could easily connect to external test boards without
needing to disassemble the PCB.

Figure 65 Recommended Arduino configuration. on the PCB

63 | P a g e
Conclusion and Future work Future Work

Another issue was the location of the MPU-6050 gyroscope on the PCB board was not
centered to the robot center of motion. This caused the robot to start moving forward when
only given an order to rotate around its own axis, a simple is to place the MPU directly in
the exact center point of your PCB in case the PCB is centered inside the robot’s body.
Also, it is recommended to have two 3mm screw holes in the PCB where the MPU will be
to stabilize and minimize the reading error of the MPU.

Figure 66 Recommended MPU-6050 position on the PCB.

We also recommend using a pluggable terminal header for input power instead of regular
pin headers as it proven to be more secure and safe to use for high tensile scenarios (regular
pin headers are not durable enough for this project).the pluggable terminal has proven to
be the best terminal block as it works with all possible power sources while securing the
connection both ways (holding the wires with nails and mechanically locking with PCB).

Figure 67 Pluggable terminal block 2 pins connected to an adaptor on a mini breadboard.

64 | P a g e
Conclusion and Future work Future Work

10.2.5.3 Recommended circuits to include in future designs.


Built-in voltage indicator (using the LM3914(
A common problem we faced was having to use external means to identify the current
voltage state of the robot as there was no form of level indications on the batteries. A
possible fix to this issue Is by using the LM3914 IC board in the following configuration.
This IC provides an output to a certain voltage level depending on how the much input
voltage is provided by the source in comparison to a set reference value of the IC.

Figure 68 LM3914 recommended circuit from datasheet.


24V to 12V regulation
While using a 12V battery pack is cheaper and more economic, the robot could only last
up to 1.5 hours of continuous operation. This can be resolved by adding more batteries,
effectively increasing the maximum volage available while only utilizing more battery
time. This can be done by using DC-DC step down converter circuit, they can be found for
as cheap as 40 EGP and can be easily integrated in the PCB construction. A note worth
mentioning is to avoid linear regulator as they result in so much thermal power losses
compared to the switching type.
10.2.6 Different Control Algorithms
While the PID controller is an easy learning curve (provided that we already have a good
background on the controller) and good system output and response times. The following
methods provide a much better system overall output but require more time and effort to
implement.
10.2.6.1 Fuzzy Logic Controller
A fuzzy logic controller is a controller that utilizes fuzzy logic to determine a course of
action. A fuzzy logic controller is used to supervise conventional proportional and
derivative actions such that the conventional gains are adapted online through fuzzy
reasoning. The computation of the control action is composed of four steps: input scaling
and shifting, fuzzification, fuzzy inference, and de-fuzzification.
For a self-balancing robot system, the robot will be successfully stabilized as required, with
good dynamic performance. The robot’s position, speed, angle, and angle rate return to the
origin point.

65 | P a g e
Conclusion and Future work Future Work

10.2.6.2 Linear Quadratic Regulator (LQR) Controller


The Linear Quadratic Regulator (LQR) is a common technique that provides optimal
controlled feedback gains to enable the closed-loop poles to be stable and high-
performance design of systems. The main idea of operation of the LQR controller is based
on finding the present control decision subject to certain constraints so as to minimize some
measure of the deviation from the ideal behavior.
This type of controller needs mathematical modeling or the state space model of the system
to obtain the feedback gains. For self-balancing robot system, LQR control is capable of
rejecting disturbances quite good. It is also good for robot if the robot is moving around
while maintaining its balance.

66 | P a g e
Appendix The MPU Calibration Code

Appendix
10.3 The MPU Calibration Code
#include <Wire.h>

byte error, MPU_6050_found, nunchuck_found, lowByte, highByte;


int address;
int nDevices;

void setup()
{
Wire.begin();
TWBR = 12;
Serial.begin(9600);
}

void loop()
{
Serial.println("Scanning I2C bus...");

nDevices = 0;
for(address = 1; address < 127; address++ )
{
Wire.beginTransmission(address);
error = Wire.endTransmission();

if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)Serial.print("0");
Serial.println(address,HEX);
nDevices++;
if(address == 0x68 || address == 0x69){
Serial.println("This could be a MPU-6050");
Wire.beginTransmission(address);
Wire.write(0x75);
Wire.endTransmission();
Serial.println("Send Who am I request...");
Wire.requestFrom(address, 1);
while(Wire.available() < 1);
lowByte = Wire.read();
if(lowByte == 0x68){
Serial.print("Who Am I responce is ok: 0x");
Serial.println(lowByte, HEX);
}
else{
Serial.print("Wrong Who Am I responce: 0x");
if (lowByte<16)Serial.print("0");
Serial.println(lowByte, HEX);
}
if(lowByte == 0x68 && address == 0x68){
MPU_6050_found = 1;
Serial.println("Starting Gyro....");
set_gyro_registers();
}
}
if(address == 0x52){

67 | P a g e
Appendix The MPU Calibration Code

Serial.println("This could be a Nunchuck");


Serial.println("Trying to initialise the device...");
Wire.beginTransmission(0x52);
Wire.write(0xF0);
Wire.write(0x55);
Wire.endTransmission();
delay(20);
Wire.beginTransmission(0x52);
Wire.write(0xFB);
Wire.write(0x00);
Wire.endTransmission();
delay(20);
Serial.println("Sending joystick data request...");
Wire.beginTransmission(0x52);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(0x52,1);
while(Wire.available() < 1);
lowByte = Wire.read();
if(lowByte > 100 && lowByte < 160){
Serial.print("Data response normal: ");
Serial.println(lowByte);
nunchuck_found = 1;
}
else{
Serial.print("Data response is not normal: ");
Serial.println(lowByte);
}
}
}
else if (error==4)
{
Serial.print("Unknown error at address 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");
if(MPU_6050_found){
Serial.print("Balance value: ");
Wire.beginTransmission(0x68);
Wire.write(0x3F);
Wire.endTransmission();
Wire.requestFrom(0x68,2);
Serial.println((Wire.read()<<8|Wire.read())*-1);
delay(20);
Serial.println("Printing raw gyro values");
for(address = 0; address < 20; address++ ){
Wire.beginTransmission(0x68);
Wire.write(0x43);
Wire.endTransmission();
Wire.requestFrom(0x68,6);
while(Wire.available() < 6);
Serial.print("Gyro X = ");

68 | P a g e
Appendix The MPU Calibration Code

Serial.print(Wire.read()<<8|Wire.read());
Serial.print(" Gyro Y = ");
Serial.print(Wire.read()<<8|Wire.read());
Serial.print(" Gyro Z = ");
Serial.println(Wire.read()<<8|Wire.read());
}
Serial.println("");
}
else Serial.println("No MPU-6050 device found at address 0x68");

if(nunchuck_found){
Serial.println("Printing raw Nunchuck values");
for(address = 0; address < 20; address++ ){
Wire.beginTransmission(0x52);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(0x52,2);
while(Wire.available() < 2);
Serial.print("Joystick X = ");
Serial.print(Wire.read());
Serial.print(" Joystick y = ");
Serial.println(Wire.read());
delay(100);
}
}
else Serial.println("No Nunchuck device found at address 0x52");
while(1);
}

void set_gyro_registers(){
//Setup the MPU-6050
Wire.beginTransmission(0x68); //Start communication with the address found during search.
Wire.write(0x6B); //We want to write to the PWR_MGMT_1 register (6B hex)
Wire.write(0x00); //Set the register bits as 00000000 to activate the gyro
Wire.endTransmission(); //End the transmission with the gyro.

Wire.beginTransmission(0x68); //Start communication with the address found during search.


Wire.write(0x1B); //We want to write to the GYRO_CONFIG register (1B hex)
Wire.write(0x00); //Set the register bits as 00000000 (250dps full scale)
Wire.endTransmission(); //End the transmission with the gyro

Wire.beginTransmission(0x68); //Start communication with the address found during search.


Wire.write(0x1C); //We want to write to the ACCEL_CONFIG register (1A hex)
Wire.write(0x08); //Set the register bits as 00001000 (+/- 4g full scale range)
Wire.endTransmission(); //End the transmission with the gyro

Wire.beginTransmission(0x68); //Start communication with the address found during search


Wire.write(0x1A); //We want to write to the CONFIG register (1A hex)
Wire.write(0x03); //Set the register bits as 00000011 (Set Digital Low Pass Filter to
~43Hz)
Wire.endTransmission(); //End the transmission with the gyro
}

69 | P a g e
Appendix Main Control System Code

10.4 Main Control System Code

#include <Stepper.h>

#include <SoftwareSerial.h>

///////////////////////////////////////////////////////////////////////////////////////

//Terms of use

///////////////////////////////////////////////////////////////////////////////////////

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR

//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER

//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,

//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN

//THE SOFTWARE.

///////////////////////////////////////////////////////////////////////////////////////

#include <Wire.h>

int gyro_address = 0x68;

int acc_calibration_value = -8780;

//Various settings

float pid_p_gain = 8.5;

float pid_i_gain = 0.4;

float pid_d_gain = 4;

float turning_speed = 15; //old 30

float max_target_speed = 50; //150

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Declaring global variables

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

byte start, received_byte, low_bat;

int left_motor, throttle_left_motor, throttle_counter_left_motor, throttle_left_motor_memory;

int right_motor, throttle_right_motor, throttle_counter_right_motor, throttle_right_motor_memory;

//int battery_voltage, battery_marker; (restore if wrong)

int battery_marker;

float battery_voltage;

int receive_counter;

int gyro_pitch_data_raw, gyro_yaw_data_raw, accelerometer_data_raw;

long gyro_yaw_calibration_value, gyro_pitch_calibration_value;

unsigned long loop_timer;

float angle_gyro, angle_acc, angle, self_balance_pid_setpoint;

float pid_error_temp, pid_i_mem, pid_setpoint, gyro_input, pid_output, pid_last_d_error;

float pid_output_left, pid_output_right;

SoftwareSerial myserial(7,1);

70 | P a g e
Appendix Main Control System Code

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Setup basic functions

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void setup(){

Serial.begin(9600); //Start the serial port at 9600 kbps

Wire.begin(); //Start the I2C bus as master

TWBR = 12; //Set the I2C clock speed to 400kHz

myserial.begin(9600);

//To create a variable pulse for controlling the stepper motors a timer is created that will execute a piece

of code (subroutine) every 20us

//This subroutine is called TIMER2_COMPA_vect

TCCR2A = 0; //Make sure that the TCCR2A register

is set to zero

TCCR2B = 0; //Make sure that the TCCR2A register

is set to zero

TIMSK2 |= (1 << OCIE2A); //Set the interupt enable bit OCIE2A

in the TIMSK2 register

TCCR2B |= (1 << CS21); //Set the CS21 bit in the TCCRB

register to set the prescaler to 8

OCR2A = 39; //The compare register is set to 39

=> 20us / (1s / (16.000.000MHz / 8)) - 1

TCCR2A |= (1 << WGM21); //Set counter 2 to CTC (clear timer

on compare) mode

//By default the MPU-6050 sleeps. So we have to wake it up.

Wire.beginTransmission(gyro_address); //Start communication with the

address found during search.

Wire.write(0x6B); //We want to write to the PWR_MGMT_1

register (6B hex)

Wire.write(0x00); //Set the register bits as 00000000

to activate the gyro

Wire.endTransmission(); //End the transmission with the

gyro.

//Set the full scale of the gyro to +/- 250 degrees per second

Wire.beginTransmission(gyro_address); //Start communication with the

address found during search.

Wire.write(0x1B); //We want to write to the

GYRO_CONFIG register (1B hex)

Wire.write(0x00); //Set the register bits as 00000000

(250dps full scale)

Wire.endTransmission(); //End the transmission with the gyro

//Set the full scale of the accelerometer to +/- 4g.

Wire.beginTransmission(gyro_address); //Start communication with the

address found during search.

71 | P a g e
Appendix Main Control System Code

Wire.write(0x1C); //We want to write to the

ACCEL_CONFIG register (1A hex)

Wire.write(0x08); //Set the register bits as 00001000

(+/- 4g full scale range)

Wire.endTransmission(); //End the transmission with the gyro

//Set some filtering to improve the raw data.

Wire.beginTransmission(gyro_address); //Start communication with the

address found during search

Wire.write(0x1A); //We want to write to the CONFIG

register (1A hex)

Wire.write(0x03); //Set the register bits as 00000011

(Set Digital Low Pass Filter to ~43Hz)

Wire.endTransmission(); //End the transmission with the gyro

pinMode(2, OUTPUT); //Configure digital poort 2 as

output

pinMode(3, OUTPUT); //Configure digital poort 3 as

output

pinMode(4, OUTPUT); //Configure digital poort 4 as

output

pinMode(5, OUTPUT); //Configure digital poort 5 as

output

pinMode(11, OUTPUT); //Configure digital poort 11 as

output

pinMode(13, OUTPUT); //Configure digital poort 13 as

output

digitalWrite(11,HIGH); //setting MS1 on the drivers to high

for 1/4 microstepping

for(receive_counter = 0; receive_counter < 500; receive_counter++){ //Create 500 loops

if(receive_counter % 15 == 0)digitalWrite(13, !digitalRead(13)); //Change the state of the LED every

15 loops to make the LED blink fast

Wire.beginTransmission(gyro_address); //Start communication with the gyro

Wire.write(0x43); //Start reading the Who_am_I

register 75h

Wire.endTransmission(); //End the transmission

Wire.requestFrom(gyro_address, 4); //Request 2 bytes from the gyro

gyro_yaw_calibration_value += Wire.read()<<8|Wire.read(); //Combine the two bytes to make one

integer

gyro_pitch_calibration_value += Wire.read()<<8|Wire.read(); //Combine the two bytes to make one

integer

delayMicroseconds(3700); //Wait for 3700 microseconds to

simulate the main program loop time

72 | P a g e
Appendix Main Control System Code

gyro_pitch_calibration_value /= 500; //Divide the total value by 500 to

get the avarage gyro offset

gyro_yaw_calibration_value /= 500; //Divide the total value by 500 to

get the avarage gyro offset

loop_timer = micros() + 4000; //Set the loop_timer variable at the

next end loop time

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Main program loop

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void loop(){

if(myserial.available()){ //If there is serial data

available

received_byte = myserial.read(); //Load the received serial data in

the received_byte variable

receive_counter = 0; //Reset the receive_counter variable

//if(receive_counter <= 1250)receive_counter ++; //The received byte will be

valid for 25 program loops (100 milliseconds)

//else received_byte = 0x00; //After 100 milliseconds the

received byte is deleted

//Load the battery voltage to the battery_voltage variable.

//85 is the voltage compensation for the diode.

//Resistor voltage divider => (2.2k + 3.3k)/2.2k = 2.5

//12.5V equals ~5V @ Analog 0.

//12.5V equals 1023 analogRead(0).

//1250 / 1023 = 1.222.

//The variable battery_voltage holds 1050 if the battery voltage is 10.5V.

battery_voltage = ((analogRead(0) * 1.222) - 80);

if(battery_voltage < 1050 && battery_voltage > 800){ //If batteryvoltage is below 10.5V

and higher than 8.0V

digitalWrite(13, HIGH); //Turn on the led if battery voltage

is too low

low_bat = 1; //Set the low_bat variable to 1

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Angle calculations

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

73 | P a g e
Appendix Main Control System Code

Wire.beginTransmission(gyro_address); //Start communication with the gyro

Wire.write(0x3F); //Start reading at register 3F

Wire.endTransmission(); //End the transmission

Wire.requestFrom(gyro_address, 2); //Request 2 bytes from the gyro

accelerometer_data_raw = Wire.read()<<8|Wire.read(); //Combine the two bytes to make one

integer

accelerometer_data_raw += acc_calibration_value; //Add the accelerometer calibration

value

if(accelerometer_data_raw > 8200)accelerometer_data_raw = 8200; //Prevent division by zero by

limiting the acc data to +/-8200;

if(accelerometer_data_raw < -8200)accelerometer_data_raw = -8200; //Prevent division by zero by

limiting the acc data to +/-8200;

angle_acc = asin((float)accelerometer_data_raw/8200.0)* 57.296; //Calculate the current angle

according to the accelerometer

if(start == 0 && angle_acc > -0.5&& angle_acc < 0.5){ //If the accelerometer angle is

almost 0

angle_gyro = angle_acc; //Load the accelerometer angle in

the angle_gyro variable

start = 1; //Set the start variable to start

the PID controller

Wire.beginTransmission(gyro_address); //Start communication with the gyro

Wire.write(0x43); //Start reading at register 43

Wire.endTransmission(); //End the transmission

Wire.requestFrom(gyro_address, 4); //Request 4 bytes from the gyro

gyro_yaw_data_raw = Wire.read()<<8|Wire.read(); //Combine the two bytes to make one

integer

gyro_pitch_data_raw = Wire.read()<<8|Wire.read(); //Combine the two bytes to make one

integer

gyro_pitch_data_raw -= gyro_pitch_calibration_value; //Add the gyro calibration value

angle_gyro += gyro_pitch_data_raw * 0.000031; //Calculate the traveled during this

loop angle and add this to the angle_gyro variable

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//MPU-6050 offset compensation

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Not every gyro is mounted 100% level with the axis of the robot. This can be cause by misalignments during

manufacturing of the breakout board.

//As a result the robot will not rotate at the exact same spot and start to make larger and larger circles.

//To compensate for this behavior a VERY SMALL angle compensation is needed when the robot is rotating.

//Try 0.0000003 or -0.0000003 first to see if there is any improvement.

74 | P a g e
Appendix Main Control System Code

gyro_yaw_data_raw -= gyro_yaw_calibration_value; //Add the gyro calibration value

//Uncomment the following line to make the compensation active

angle_gyro -= gyro_yaw_data_raw * -0.0000003; //Compensate the gyro offset when the

robot is rotating

angle_gyro = angle_gyro * 0.9996 + angle_acc * 0.0004; //Correct the drift of the gyro

angle with the accelerometer angle

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//PID controller calculations

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//The balancing robot is angle driven. First the difference between the desired angel (setpoint) and actual

angle (process value)

//is calculated. The self_balance_pid_setpoint variable is automatically changed to make sure that the robot

stays balanced all the time.

//The (pid_setpoint - pid_output * 0.015) part functions as a brake function.

//pid_error_temp = angle_gyro - self_balance_pid_setpoint - pid_setpoint;

pid_error_temp = angle_gyro - self_balance_pid_setpoint - pid_setpoint;

if(pid_output > 10 || pid_output < -10)pid_error_temp += pid_output * 0.015 ;

pid_i_mem += pid_i_gain * pid_error_temp; //Calculate the I-controller value

and add it to the pid_i_mem variable

if(pid_i_mem > 400)pid_i_mem = 400; //Limit the I-controller to the

maximum controller output

else if(pid_i_mem < -400)pid_i_mem = -400;

//Calculate the PID output value

pid_output = pid_p_gain * angle_gyro + pid_i_mem + pid_d_gain * (pid_error_temp - pid_last_d_error);

if(pid_output > 400)pid_output = 400; //Limit the PI-controller to the

maximum controller output

else if(pid_output < -400)pid_output = -400;

pid_last_d_error = pid_error_temp; //Store the error for the next loop

if(pid_output < 5 && pid_output > -5)pid_output = 0; //Create a dead-band to stop the

motors when the robot is balanced

if(angle_gyro > 30 || angle_gyro < -30 || start == 0 || low_bat == 1){ //If the robot tips over or the

start variable is zero or the battery is empty

pid_output = 0; //Set the PID controller output to 0

so the motors stop moving

pid_i_mem = 0; //Reset the I-controller memory

start = 0; //Set the start variable to 0

self_balance_pid_setpoint = 0; //Reset the

self_balance_pid_setpoint variable

75 | P a g e
Appendix Main Control System Code

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Control calculations

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

pid_output_left = pid_output; //Copy the controller output to the

pid_output_left variable for the left motor

pid_output_right = pid_output; //Copy the controller output to the

pid_output_right variable for the right motor

if(received_byte & B00000001){ //If the first bit of the receive

byte is set change the left and right variable to turn the robot to the left

pid_output_left += turning_speed; //Increase the left motor speed

pid_output_right -= turning_speed; //Decrease the right motor speed

if(received_byte & B00000010){ //If the second bit of the receive

byte is set change the left and right variable to turn the robot to the right

pid_output_left -= turning_speed; //Decrease the left motor speed

pid_output_right += turning_speed; //Increase the right motor speed

if(received_byte & B00000100){ //If the third bit of the receive

byte is set change the left and right variable to turn the robot to the right

if(pid_setpoint > -2.5)pid_setpoint -= 0.05; //Slowly change the setpoint angle

so the robot starts leaning forewards

if(pid_output > max_target_speed * -1)pid_setpoint -= 0.005; //Slowly change the setpoint angle

so the robot starts leaning forewards

if(received_byte & B00001000){ //If the forth bit of the receive

byte is set change the left and right variable to turn the robot to the right

if(pid_setpoint < 2.5)pid_setpoint += 0.05; //Slowly change the setpoint angle

so the robot starts leaning backwards

if(pid_output < max_target_speed)pid_setpoint += 0.005; //Slowly change the setpoint angle

so the robot starts leaning backwards

if(!(received_byte & B00001100)){ //Slowly reduce the setpoint to zero

if no foreward or backward command is given

if(pid_setpoint > 0.5)pid_setpoint -=0.05; //If the PID setpoint is larger than

0.5 reduce the setpoint with 0.05 every loop

else if(pid_setpoint < -0.5)pid_setpoint +=0.05; //If the PID setpoint is smaller

then -0.5 increase the setpoint with 0.05 every loop

else pid_setpoint = 0; //If the PID setpoint is smaller

then 0.5 or larger then -0.5 set the setpoint to 0

76 | P a g e
Appendix Main Control System Code

if(received_byte & B00010000){ //If the fifth bit of the receive

byte is set deactivate the robot and reset everything

pid_output = 0; //Set the PID controller output to 0

so the motors stop moving

pid_i_mem = 0; //Reset the I-controller memory

start = 0; //Set the start variable to

if(received_byte & B00100000){ //If the sixth bit of the receive

byte is set lower the target speed to a more efficient values

float turning_speed = 15; //this mode is best for battery

efficiency

float max_target_speed =

50;

if(received_byte & B01000000){ //If the seventh bit of the receive

byte is set increase the target speed

float turning_speed = 25; //this mode is best for more torque

demanding tasks (ramps and fast movements)

float max_target_speed = 100;

if(received_byte & B10000000){ //If the 8th bit of the receive byte

is set increase the target speed

battery_marker ++; //add 1 to the marker memory

if (battery_marker <= 1){ //this way the battery will send

only 1 write command to the user

myserial.write(battery_voltage);

Serial.print(battery_voltage/100, 1); //delete (100) and ,1 if not working

else{ //if the battery voltage no longer

requested reset the battery marker

battery_marker = 0; //reset the battery markers in zero

//The self-balancing point is adjusted when there is not forward or backwards movement from the transmitter.

This way the robot will always find it's balancing point

if(pid_setpoint == 0){ //If the setpoint is zero degrees

77 | P a g e
Appendix Main Control System Code

if(pid_output < 0)self_balance_pid_setpoint += 0.0015; //Increase the

self_balance_pid_setpoint if the robot is still moving forewards

if(pid_output > 0)self_balance_pid_setpoint -= 0.0015; //Decrease the

self_balance_pid_setpoint if the robot is still moving backwards

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Motor pulse calculations

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//To compensate for the non-linear behavior of the stepper motors the following calculations are needed to get

a linear speed behavior.

if(pid_output_left > 0)pid_output_left = 405 - (1/(pid_output_left + 9)) * 5500;

else if(pid_output_left < 0)pid_output_left = -405 - (1/(pid_output_left - 9)) * 5500;

if(pid_output_right > 0)pid_output_right = 405 - (1/(pid_output_right + 9)) * 5500;

else if(pid_output_right < 0)pid_output_right = -405 - (1/(pid_output_right - 9)) * 5500;

//Calculate the needed pulse time for the left and right stepper motor controllers

if(pid_output_left > 0)left_motor = 400 - pid_output_left;

else if(pid_output_left < 0)left_motor = -400 - pid_output_left;

else left_motor = 0;

if(pid_output_right > 0)right_motor = 400 - pid_output_right;

else if(pid_output_right < 0)right_motor = -400 - pid_output_right;

else right_motor = 0;

//Copy the pulse time to the throttle variables so the interrupt subroutine can use them

throttle_left_motor = left_motor;

throttle_right_motor = right_motor;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Loop time timer

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//The angle calculations are tuned for a loop time of 4 milliseconds. To make sure every loop is exactly 4

milliseconds a wait loop

//is created by setting the loop_timer variable to +4000 microseconds every loop.

while(loop_timer > micros());

loop_timer += 4000;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Interrupt routine TIMER2_COMPA_vect

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

ISR(TIMER2_COMPA_vect){

//Left motor pulse calculations

throttle_counter_left_motor ++; //Increase the

throttle_counter_left_motor variable by 1 every time this routine is executed

78 | P a g e
Appendix Main Control System Code

if(throttle_counter_left_motor > throttle_left_motor_memory){ //If the number of loops is larger

then the throttle_left_motor_memory variable

throttle_counter_left_motor = 0; //Reset the

throttle_counter_left_motor variable

throttle_left_motor_memory = throttle_left_motor; //Load the next throttle_left_motor

variable

if(throttle_left_motor_memory < 0){ //If the throttle_left_motor_memory

is negative

PORTD &= 0b11111011; //Set output 3 low to reverse the

direction of the stepper controller

throttle_left_motor_memory *= -1; //Invert the

throttle_left_motor_memory variable

else PORTD |= 0b00000100; //Set output 3 high for a forward

direction of the stepper motor

else if(throttle_counter_left_motor == 1)PORTD |= 0b00001000; //Set output 2 high to create a

pulse for the stepper controller

else if(throttle_counter_left_motor == 2)PORTD &= 0b11110111; //Set output 2 low because the pulse

only has to last for 20us

//right motor pulse calculations

throttle_counter_right_motor ++; //Increase the

throttle_counter_right_motor variable by 1 every time the routine is executed

if(throttle_counter_right_motor > throttle_right_motor_memory){ //If the number of loops is larger

then the throttle_right_motor_memory variable

throttle_counter_right_motor = 0; //Reset the

throttle_counter_right_motor variable

throttle_right_motor_memory = throttle_right_motor; //Load the next throttle_right_motor

variable

if(throttle_right_motor_memory < 0){ //If the throttle_right_motor_memory

is negative

PORTD |= 0b00010000; //Set output 5 low to reverse the

direction of the stepper controller

throttle_right_motor_memory *= -1; //Invert the

throttle_right_motor_memory variable

else PORTD &= 0b11101111; //Set output 5 high for a forward

direction of the stepper motor

else if(throttle_counter_right_motor == 1)PORTD |= 0b00100000; //Set output 4 high to create a

pulse for the stepper controller

else if(throttle_counter_right_motor == 2)PORTD &= 0b11011111; //Set output 4 low because the pulse

only has to last for 20us

79 | P a g e
Appendix Self-Balancing Robot Costs of Production.

10.5 Self-Balancing Robot Costs of Production.


Here is a list of every item we bought and where we bought it from, this project cost us a
grand total of 3623.1 L.E. This included every item we bought and the replacement of
some broken parts. The actual final product cost around 2500 LE

Main components Amount Price (LE) TP (LE) Source Notes

may vary in price and specs based on model parameters…


Arduino NANO + USB cable 3 200 600 RAM electronics the reason we bought more than one due to losses during
testing phases :)
MPU 6050 Gyroscope 1 150 150 RAM electronics easy to find and the cheapest Type
DRV8825 Stepper Driver 2 75 150 RAM electronics better altrenative to A4988
A4988 Stepper Driver 2 65 130 RAM electronics cheapest Stepper motor driver available
NEMA 17 Stepper motor 2 275 550 MTM Electronics not very easy to aquire
Bluetooth module HC-05 1 225 225 RAM electronics most common;y used

Power sources Notes


neccesary for testing purposes only (if plan to be
12 Volt 2 A power adaptor 1 15 15 RAM Electronics
only used buy a higher rating with longer cable length
3.7 volt Li-ion cell rechargable 3 45 135 free electronics 3 * 3.7 = 11.1 V enough to power the the entire circuit
battery pack holder 1 15 15 free electronics for easier connection of the batteries

Secondary component elements Notes


Voltage regulator 12V to 5V LM7805 1 4 4 RAM Electronics required to minimize the current flow through the arduino
capacitor 100uF 2 0.5 1 RAM Electronics easy to find
capacitor 0.1uF 2 0.5 1 RAM Electronics easy to find
capacitor 2200uF 1 2 2 RAM Electronics easy to find
Resistor 1K 10 0.1 1 Free Electronics easy to find
Resistor 2k2 10 0.1 1 Free Electronics easy to find
Resistor 3k3 10 0.1 1 Free Electronics easy to find
Diode 1N5408 1 0.75 0.75 Free Electronics easy to find
Fuse 1 2 2 Elgmal Electronics requires a Fuse holder for better functionalty
Fuse unit holder BLX-A 1 4 4 Elgmal Electronics not very easy to aquire
Mini toggle switch 3 Pins 1 6 6 Free Electronics any type will work just fine (but take into account the PCB Design
Female DC power connector 1 1.5 1.5 Free Electronics to act as a power source input
pin header female 7 3.5 24.5 Free Electronics to elevate the circuit components for easier replacement
Stepper hous. NEMA 17 24HZ 2 65 130 RAM Electronics metallic frames used for holding the stepper motors in the full structure
screws and nuts _ 100 100 not specific easy to find
Wheels normal 60mm diameter 2 30 60 Free Electronics where too small for our design
Wheels normal 85mm diameter 2 80 160 used needed couplers and 3d printed elements to balance
Jumper wires _ 40 30 different providers for testing phases

Printing Costs+F42A3A31:G41 Notes


1 cm^2 = 1.41 EGP
PCB Printing Costs 5 142.67 713.35 Faris Electronics
May vary In price for different PCB manufactures
mainly priced per how long the laser works
Laser cutting machining costs 1 260 260
for exmaple (Fab lab charges 250LE per hour of laser work)
PCB WELDING COSTS 150 150 MEGA Electronics Co. not necessary if you know how to solder electronics

Google maps location for the stores locations Notes

not the best prices but good quality


RAM Electronics https://goo.gl/maps/1DHZfLrsKnSeCU398
website: https://ram-e-shop.com/
good prices with questionable quality
Free Electronics https://goo.gl/maps/9GtBCV86bSJMt54i6
website: https://free-electronic.com/
https://www.google.com/maps/place/Elec+Stores/@30.0442721,31.2381777,19.95z/data=!4m5!3m4!1s0x1458418153207b55:0xa50b215cf52f0cf!8m2!3d30.0441991!4d31.2380765
Elgmal Electronics
https://www.google.com/maps/place/Elec+Stores/@30.0442721,31.2381777,19.95z/data=!4m5!3m4!1s0x1458418153207b55:0xa50b215cf52f0cf!8m2!3d30.0441991!4d31.2380765
MTM Electronics
MEGA Electronics Co. https://goo.gl/maps/DaZ46fPjUKrh4Yec6 might be a bit expensive, find a better alternative

80 | P a g e
Appendix Self-Balancing Robot Costs of Production.

If you plan to apply for a financial aid program, we recommend using this version instead
(more expensive as it includes backups and alternative components.
Components Amount Price Total price (LE)
Arduino NANO + USB cable 3 200 600
MPU 6050 Gyroscope 1 150 150
DRV8825 Stepper Driver 2 85 170
TMC2409 Stepper Driver (alt.) 2 195 390
NEMA 17 Stepper motor 2 275 550
Bluetooth module HC-05 1 225 225
12 Volt 2 A power adaptor 1 15 15
3.7-volt Li-ion cell rechargeable 3 45 135
battery pack holder 1 15 15
PCB printing 3 150 450
Laser cutting/3D printing 1 450 450
PCB Soldering costs 1 150 150
Wheels 85mm D 2 100 200
Wires, resistors, cap, screws, …etc. - 200 200
Total cost 3,700
Also here is the location and websites of the stores we dealt with to find the updated
prices
Store Location Note on the store
RAM https://goo.gl/maps/1DHZfLrsKnSeCU398 not the best prices but decent quality
Electronics website: https://ram-e-shop.com/

Free https://goo.gl/maps/9GtBCV86bSJMt54i6 fair prices with questionable quality


Electronics website: https://free-electronic.com/

Elgmal https://www.google.com/maps/place/Elec+Sto Only dealt with once


Electronics res/@30.0442721,31.2381777,19.95z/data=!4
m5!3m4!1s0x1458418153207b55:0xa50b215cf
52f0cf!8m2!3d30.0441991!4d31.2380765
MTM https://www.google.com/maps/place/Elec+Sto The only source that had new
res/@30.0442721,31.2381777,19.95z/data=!4
Electronics
m5!3m4!1s0x1458418153207b55:0xa50b215cf
stepper motors at the time
52f0cf!8m2!3d30.0441991!4d31.2380765
MEGA https://goo.gl/maps/DaZ46fPjUKrh4Yec6 might be a bit expensive, find a better
Electronics alternative
Co.

81 | P a g e
References

References

[1] B. A. Schreiber., "robotics," [Online]. [8] B. SCHWEBER, "Unipolar vs. Bipolar drive for
Available: stepper motors, Part 1: principles," 6 January
https://www.britannica.com/technology/robotic 2022. [Online]. Available:
s. [Accessed 18 April 2023]. https://www.powerelectronictips.com/unipolar-
vs-bipolar-drive-for-stepper-motors-part-1-
[2] "Balancing robot tutorial," 7 September 2014. principles-faq/. [Accessed 23 April 2023].
[Online]. Available:
https://wired.chillibasket.com/2014/09/balanci [9] J. Joseph, "How Does the MPU6050
ng-robot-intro/. [Accessed 19 April 2023]. Accelerometer & Gyroscope Sensor Work and
Interfacing It With Arduino," 16 May 2022.
[3] "Inverted Pendulum: System Modeling," [Online]. Available:
[Online]. Available: https://circuitdigest.com/microcontroller-
https://ctms.engin.umich.edu/CTMS/index.php projects/interfacing-mpu6050-module-with-
?example=InvertedPendulum&section=System arduino#:~:text=How%20does%20MPU6050
Modeling. [Accessed 20 April 2023]. %20Module%20Work,of%20a%20system%20
or%20object.. [Accessed 24 April 2023].
[4] M. K. Saini, "Difference between Stepper
Motor and DC Motor," 22 August 2022. [10] "An Overview of Arduino Nano Board,"
[Online]. Available: [Online]. Available:
https://www.tutorialspoint.com/difference- https://www.elprocus.com/an-overview-of-
between-stepper-motor-and-dc- arduino-nano-board/. [Accessed 24 April 2023].
motor#:~:text=DC%20motors%20have%20con
tinuous%20motion.&text=Stepper%20motors [11] C. Woodford, "Lithium-ion batteries," 10 April
%20give%20slow%20response,response%20th 2022. [Online]. Available:
an%20a%20stepper%20motor.&text=The%20s https://www.explainthatstuff.com/how-lithium-
tepper%20motors%20are%20not,po. [Accessed ion-batteries-work.html. [Accessed 24 April
22 April 2023]. 2023].

[5] C. Cavalo, "Stepper Motors vs. DC Motors - [12] "Control Stepper Motor with DRV8825 Driver
What's the Difference?," [Online]. Available: Module & Arduino," [Online]. Available:
https://www.thomasnet.com/articles/machinery https://lastminuteengineers.com/drv8825-
-tools-supplies/stepper-motors-vs-dc-motors/. stepper-motor-driver-arduino-tutorial/.
[Accessed 22 April 2023]. [Accessed 25 April 2023].

[6] "What is a Stepper Motor : Types & Its [13] "HC-05 - Bluetooth Module," 16 July 2021.
Working," [Online]. Available: [Online]. Available:
https://www.elprocus.com/stepper-motor- https://components101.com/wireless/hc-05-
types-advantages-applications/. [Accessed 22 bluetooth-module. [Accessed 25 April 2023].
April 2023].
[14] P. Miller, "Building a two wheeled balancing
[7] C. Fiore, "Stepper Motors Basics: Types, Uses, robot," University of southern Queensland,
and Working Principles," [Online]. Available: Queensland, 2008.
https://www.monolithicpower.com/en/stepper-
motors-basics-types- [15] M. Ullman, "What's the difference? MDF vs.
uses#:~:text=The%20basic%20working%20pri plywood," 11 February 2020. [Online].
nciple%20of,rotor%20aligns%20with%20this Available:
%20field.. [Accessed 22 April 2023]. https://www.bobvila.com/articles/mdf-vs-
plywood/. [Accessed 11 December 2022].

82 | P a g e
References

[16] J. G. M. K. Ye Ding1, "Modeling, Simulation [25] M. A. H. a. M. A. R. M. A. Hannan, "Design


and Fabrication of a," 12-18-2012. and Implementation of a Self-Balancing Robot
Using PID Controller".
[17] "Laser cutting: Examinig advantages and
disadvantages of laser technology," 26 January [26] J. A. A.-G. a. A. A. Al-Raweshidy, "Design and
2022. [Online]. Available: Implementation of a Self-Balancing Two-
https://www.rapiddirect.com/blog/advantages- Wheeled Robot Using PID Control".
and-disadvantages-of-laser-cutting/. [Accessed
11 December 2022]. [27] Y. R. Anmol Singh Shekhawat, "Design and
Control of Two-wheeled Self-Balancing Robot
[18] M. Rangaiah, "3D printing technology: using Arduino".
Advantages and disadvantages," 27 May 2021.
[Online]. Available: [28] J. D. P. a. A. E.-N. Gene F. Franklin, "Feedback
https://www.analyticssteps.com/blogs/3d- Control of Dynamic Systems".
printing-technology-advantages-and-
disadvantages. [Accessed 11 December 2022]. [29] S. C. D. Y. L. G. a. K. N. Liuping Wang, "PID
and Predictive Control of Electrical Drives and
[19] Millennium Circuits Limited, "FR4: WHEN Power Converters Using MATLAB/Simulink,"
CAN YOU USE IT AND WHEN CAN YOU pp. 45-47.
NOT," Millennium Circuits Limited | 7703
Derry St. Harrisburg, PA 17111-5205, [Online]. [30] "Self balancing robot | Simulink basics series,"
Available: https://www.mclpcb.com/blog/fr4- [Online]. Available:
guide/. [Accessed 17 4 2023]. https://www.youtube.com/watch?v=QtmVFlZi
5T8&ab_channel=Algobotics.
[20] R. S. Fearing, "Design of biologically inspired
robots," in 2003 IEEE/RSJ International [31] MathWorks, "MathWorks," [Online].
Conference on Intelligent Robots and Systems Available: https://www.mathworks.com/.
i(IROS 2003), pp. 4224-4229, doi:
10.1109/IROS.2003.1250932., 2003. [32] MathWorks, "MathWorks," [Online].
Available:
[21] S. B. a. K. M. M. Abderrahim, "Design and https://www.mathworks.com/help/ident/.
implementation of a fuzzy controller for a two-
wheeled self-balancing robot,," International [33] Y. Sanghvi, "Arduino Uno vs STM32duino
Journal of Advanced Computer Science and (Blue Pill)," 31 July 2021. [Online]. Available:
Applications, vol. 3, no. 5, pp. 101-106, 2012. https://www.tutorialspoint.com/arduino-uno-
vs-stm32duino-blue-pill. [Accessed 2 July
[22] J. J. Craig, Introduction to Robotics: Mechanics 2023].
and Control , 3rd ed, Upper Saddle River, NJ:
USA: Pearson Prentice Hall, 2005. [34] "TMC2208," [Online]. Available:
https://wiki.fysetc.com/TMC2208/. [Accessed
[23] M. A. a. K. M. S. Bououden, "Design of a self- 2 July 2023].
balancing robot with a new control strategy,,"
International Journal of Advanced Computer [35] AKB, "Are Bluetooth and Wifi Modules the
Science and Applications, vol. 4, no. 12, pp. Same?," 19 November 2022. [Online].
188-192, 2013. Available:
https://www.campuscomponent.com/blogs/post
[24] R. S. K. a. J. K. Gupta, A Textbook of Machine /are-bluetooth-and-wifi-modules-the-
Design, 14th ed, Delhi: India: S. Chand & same#:~:text=Difference%20Between%20Blue
Company Ltd, 2018. tooth%20And%20WiFi,your%20gadgets%20to
%20the%20internet.. [Accessed 3 July 2023].

[36] A. S. a. L. S. S. K. Khanna, "3D Printing: A


state-of-the-art review," in Materials Today:

83 | P a g e
References

Proceedings, vol. 32, pp. 103-110, 2020, doi: li-ion-rechargeable-battery. [Accessed 24 April
10.1016/j.matpr.2020.03.081., 2020. 2023].

[37] B. Schweber, "Stepper Motors Make the Right [42] [Online]. Available:
Moves with Precision, Ease and Smarter https://en.wikipedia.org/wiki/Laser_cutting.
Drivers," [Online]. Available:
https://www.mouser.in/publicrelations_techarti [43] [Online]. Available: What is 3D Printing? -
cle_steppermotors_rightmoves_2015final/. Technology Definition and Types. (n.d.).
[Accessed 23 April 2023]. https://www.twi-global.com/technical-
knowledge/faqs/what-is-3d-printing.
[38] "MEMS Accelerometer," [Online]. Available:
https://www.leveldevelopments.com/2020/10/ [44] "Karooza.net," [Online]. Available:
what-are-inclinometers/mems-accelerometer/. https://karooza.net/dertermining-the-centre-of-
[Accessed 24 April 2023]. gravity-for-a-self-balancing-robot. [Accessed 9
May 2023].
[39] "GY-521 MPU6050 Triple 3-Axis
Accelerometer Gyroscope I2C," [Online]. [45] H. Chin, "2.004 Lab 8 Intro: Self-Balancing
Available: https://electra.store/product/gy-521- Robot Control Part I: Stabilization Using PID
mpu6050-triple-3-axis-accelerometer- Control," 2019.
gyroscope-i2c/. [Accessed 24 April 2023].
[46] J. G. M. K. Ye Ding, "Modeling, Simulation and
[40] "A000005 - Arduino Nano Board," [Online]. Fabrication of a Balancing Robot," 2012 .
Available: https://www.distrelec.ch/en/arduino-
nano-board-arduino-a000005/p/11096733. [47] "Inverted pendulum," January 2010. [Online].
[Accessed 24 April 2023]. Available:
https://en.wikipedia.org/wiki/Inverted_pendulu
[41] "18650 Li-Ion Rechargeable Battery 1C (1200 m. [Accessed 20 April 2023].
MAh)," [Online]. Available:
https://quartzcomponents.com/products/18650-

84 | P a g e

You might also like