The Control of A Self-Balancing Robot
The Control of A Self-Balancing Robot
Faculty of Engineering
Electrical Power Department
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
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 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|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.
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.
2|Page
Introduction Project Main Idea and Stages:
3|Page
Main Components Stepper Motors
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.
5|Page
Main Components MPU-6050:
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:
7|Page
Main Components Arduino NANO
8|Page
Main Components Rechargeable Lithium-ion Battery
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]
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]
10 | P a g e
Main Components DRV8825 Stepper Motor Driver
11 | P a g e
Main Components Components Interfacing
12 | P a g e
Main Components Components Interfacing
13 | P a g e
Main Components Components Interfacing
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.
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.
15 | P a g e
Main Components Components Interfacing
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.
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
18 | P a g e
Mechanical Structure Material Used: Acrylic
casing
materials: Advantages Disadvantages
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
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’
Figure 23 First rack of self-balancing robot Figure 24 Second rack of the self-balancing robot
21 | P a g e
Mechanical Structure Mechanical Structure CNC Fabrication
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.
22 | P a g e
Mechanical Structure 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.
23 | P a g e
Mechanical Structure Choosing the Wheels
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
25 | P a g e
Electric Circuit Design Schematic Design
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
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
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).
30 | P a g e
wireless Control Application: Why Use a Mobile Application
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.
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
Figure 39 the designer tap page of the MIT App inventor website
32 | P a g e
wireless Control Application: Application Versions
33 | P a g e
wireless Control Application: Application Versions
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
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.
35 | P a g e
wireless Control Application: Application Block Diagrams in MIT App Inventor
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
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
• 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:
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]
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]
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)
𝑅(𝑠) 𝐼 𝑐 𝐼
45 | P a g e
Control Method: PID Controller Mechanical System Simulink Model
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
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.
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]
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
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]
50 | P a g e
Arduino Codes Used This Project MPU-6050 Calibration Code
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
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
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
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.
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
60 | P a g e
Conclusion and Future work Future Work
61 | P a g e
Conclusion and Future work Future Work
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.
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.
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.
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).
64 | P a g e
Conclusion and Future work Future Work
65 | P a g e
Conclusion and Future work Future Work
66 | P a g e
Appendix The MPU Calibration Code
Appendix
10.3 The MPU Calibration Code
#include <Wire.h>
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
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.
69 | P a g e
Appendix 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
//THE SOFTWARE.
///////////////////////////////////////////////////////////////////////////////////////
#include <Wire.h>
//Various settings
float pid_d_gain = 4;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int battery_marker;
float battery_voltage;
int receive_counter;
SoftwareSerial myserial(7,1);
70 | P a g e
Appendix Main Control System Code
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup(){
myserial.begin(9600);
//To create a variable pulse for controlling the stepper motors a timer is created that will execute a piece
is set to zero
is set to zero
on compare) mode
gyro.
//Set the full scale of the gyro to +/- 250 degrees per second
71 | P a g e
Appendix Main Control System Code
output
output
output
output
output
output
register 75h
integer
integer
72 | P a g e
Appendix Main Control System Code
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loop(){
available
if(battery_voltage < 1050 && battery_voltage > 800){ //If batteryvoltage is below 10.5V
is too low
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Angle calculations
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
73 | P a g e
Appendix Main Control System Code
integer
value
if(start == 0 && angle_acc > -0.5&& angle_acc < 0.5){ //If the accelerometer angle is
almost 0
integer
integer
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Not every gyro is mounted 100% level with the axis of the robot. This can be cause by misalignments during
//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.
74 | P a g e
Appendix Main Control System Code
robot is rotating
angle_gyro = angle_gyro * 0.9996 + angle_acc * 0.0004; //Correct the drift of the gyro
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//The balancing robot is angle driven. First the difference between the desired angel (setpoint) and actual
//is calculated. The self_balance_pid_setpoint variable is automatically changed to make sure that the robot
if(pid_output < 5 && pid_output > -5)pid_output = 0; //Create a dead-band to stop the
if(angle_gyro > 30 || angle_gyro < -30 || start == 0 || low_bat == 1){ //If the robot tips over or the
self_balance_pid_setpoint variable
75 | P a g e
Appendix Main Control System Code
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Control calculations
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
byte is set change the left and right variable to turn the robot to the left
byte is set change the left and right variable to turn the robot to the right
byte is set change the left and right variable to turn the robot to the right
if(pid_output > max_target_speed * -1)pid_setpoint -= 0.005; //Slowly change the setpoint angle
byte is set change the left and right variable to turn the robot to the right
if(pid_setpoint > 0.5)pid_setpoint -=0.05; //If the PID setpoint is larger than
else if(pid_setpoint < -0.5)pid_setpoint +=0.05; //If the PID setpoint is smaller
76 | P a g e
Appendix Main Control System Code
efficiency
float max_target_speed =
50;
if(received_byte & B10000000){ //If the 8th bit of the receive byte
myserial.write(battery_voltage);
//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
77 | P a g e
Appendix Main Control System Code
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//To compensate for the non-linear behavior of the stepper motors the following calculations are needed to get
//Calculate the needed pulse time for the left and right stepper motor controllers
else left_motor = 0;
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;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//The angle calculations are tuned for a loop time of 4 milliseconds. To make sure every loop is exactly 4
//is created by setting the loop_timer variable to +4000 microseconds every loop.
loop_timer += 4000;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ISR(TIMER2_COMPA_vect){
78 | P a g e
Appendix Main Control System Code
throttle_counter_left_motor variable
variable
is negative
throttle_left_motor_memory variable
else if(throttle_counter_left_motor == 2)PORTD &= 0b11110111; //Set output 2 low because the pulse
throttle_counter_right_motor variable
variable
is negative
throttle_right_motor_memory variable
else if(throttle_counter_right_motor == 2)PORTD &= 0b11011111; //Set output 4 low because the pulse
79 | P a g e
Appendix Self-Balancing Robot Costs of Production.
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/
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§ion=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
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