You are on page 1of 58

ARDUINO BASED OBSTACLE AVOIDANCE ROBOT CAR

MICHAEL AKWE ARI

BU/16C/ENG/2038

Thesis submitted to the Faculty of Engineering through the Department of

Computer Engineering in partial fulfilment of the requirements for the

Degree of Bachelor of Engineering

in

Computer Engineering

Baze University

Abuja, Nigeria

[September 2020]
DECLARATION

BAZE UNIVERSITY

DEPARTMENT OF COMPUTER ENGINEERING

I, Michael Akwe Ari, confirm that this report and the work presented in it are my own achievement.

I have read and do understand the penalties associated with plagiarism.

Signed:………………………..

Date: ………………………….

i
CERTIFICATION
This is to certify that this thesis is fully adequate in scope and quality as an undergraduate project
work for the award of degree of Bachelor of Engineering in Computer Engineering.

……………………………………………… ………….

Dr. Sadiq Umar Date

Supervisor

This is to certify that this thesis satisfies the requirements as a graduation project for the award of
degree of Bachelor of Engineering in Computer Engineering.

……………………………………………… ………….

Name and Signature of HOD, Date

Department of Electrical/Computer Engineering .

Endorsement of External Examiner:

……………………………………………… ………….

Name and Signature of External Examiner Date

Approval of the Faculty of Engineering:

……………………………………………… ………….

Name and Signature of Dean, Date

Faculty of engineering .

ii
DEDICATION
This report is dedicated to the Almighty God for strength enabling me to complete this work. I also
dedicate this work to my lovely parents and siblings who have worked tirelessly to make sure that I
achieve my dream in my chosen field through their advice, financial support and prayers. I pray the
good Lord keep all of you alive and in sound state to reap the fruit of your labour.

iii
ACKNOWLEDGEMENT
I am most grateful to God Almighty for favour, grace and protection. I sincerely appreciate my parents,
Mr. and Mrs Ari, my siblings and friends for their unquantifiable love and financial assistance during
this period. I am also thankful to my project supervisor Dr Sadiq Umar who supported me throughout
this project with utmost cooperation and patience and for helping me in doing this Project. May God
bless and reward you all.

iv
ABSTRACT
This project involves the design and implementation of an intelligent obstacle-avoiding robot car. The
objective of this project is to implement a robot car, which while moving should have the ability to
detect obstacles in its path and change direction where obstacles are present without any form of
external influence. The new direction to be taken to avoid collision is the direction that has the most
distance between the obstacle and the sensor and this is determined by the robot based on sensor
inputs.

This implementation was done using an ultrasonic wave sensor, which measures distance by sending
pulses. Also, the movement of the servo motor (for sensor movement) and the DC motors (for wheel
movement) are controlled by the motor driver shield in order to enable the obstacle avoidance
function. The commands are sent to the Arduino microcontroller chip which serves as the main control
of the robot car, as it controls the sensor and car movement.

The implemented robot car was able to successfully detect and avoid obstacles within the line of sight
of the Ultrasonic sensor used.

v
Contents
DECLARATION.......................................................................................................................................................i
CERTIFICATION .................................................................................................................................................... ii
DEDICATION ....................................................................................................................................................... iii
ACKNOWLEDGEMENT ........................................................................................................................................ iv
ABSTRACT ............................................................................................................................................................ v
Chapter 1: Introduction .......................................................................................................................................1
1.1 Background..........................................................................................................................................1
1.2 Research Problem ...............................................................................................................................1
1.3 Motivation ...........................................................................................................................................2
1.4 Aim and Objectives..............................................................................................................................2
Chapter 2: Literature review ...............................................................................................................................3
2.1 Artificial Intelligence ............................................................................................................................3
2.2 Robotics and Robots............................................................................................................................3
2.3 Robot Learning ....................................................................................................................................4
2.4 Autonomous Robot .............................................................................................................................4
2.5 Arduino ................................................................................................................................................5
2.5.1 Overview.............................................................................................................................................5
2.5.2 Features ..............................................................................................................................................6
2.5.3 Advantages .........................................................................................................................................7
2.5.4 Arduino Board Types ..........................................................................................................................7
Chapter 3: Materials and Analysis Techniques ...................................................................................................9
3.1 Materials..............................................................................................................................................9
3.2 Analysis ................................................................................................................................................9
3.2.1 HC-SR04 Ultrasonic Sensor ..........................................................................................................9
3.2.2 SG-90 Servo Motor ................................................................................................................... 13
3.2.3 Arduino UNO R3 ....................................................................................................................... 15
3.2.4 DC Motor .................................................................................................................................. 17
3.2.5 L293D Motor Driver Shield ....................................................................................................... 19
3.3 Methodology .................................................................................................................................... 20
3.3.1 Robot Construction ......................................................................................................................... 20
3.3.2 Programming the Robot .................................................................................................................. 24

vi
Chapter 4: Results and Discussion.................................................................................................................... 33
4.1 Results .............................................................................................................................................. 33
4.2 Discussion ............................................................................................................................................... 34
5 Conclusion, Recommendation and Issues for Future Work ..................................................................... 35
5.1 Conclusion ........................................................................................................................................ 35
5.2 Recommendation ............................................................................................................................. 35
5.3 Issues ................................................................................................................................................ 35
References ........................................................................................................................................................ 37
Appendix........................................................................................................................................................... 39

vii
List of Figures

Figure 2.1 Autonomous Urbie by NASA. (Adapted from NASA, 2001) ............................................ 5
Figure 2.2 Arduino Integrated Development Environment (IDE). (Adapted from Arduino, 2016) .... 6
Figure 3.1 Diagram showing the basic operation of the HC-SR04 Ultrasonic Sensor. (Adapted from
Electroschematics, 2015) ..................................................................................................................... 9
Figure 3.2 HC-SR04 Ultrasonic Sensor Pins ..................................................................................... 11
Figure 3.3 SG-90 Servo Motor. .......................................................................................................... 13
Figure 3.4 Arduino UNO R3 Board. .................................................................................................. 15
Figure 3.5 DC Motors (Adapted from Allaboutcircuits, 2017).......................................................... 17
Figure 3.6 DC Gear Motor. (Adapted from Allaboutcircuits, 2017) ................................................. 18
Figure 3.7 L293D Motor Driver Shield (Adapted from Lelong, 2020) ............................................. 19
Figure 3.8 Block diagram showing the Hardware Implementation of the project ............................. 21
Figure 3.9 Robot Chassis Components. ............................................................................................. 22
Figure 3.10Wheels and Motors Attached to the Chassis ................................................................... 22
Figure 3.11 Components attached to the chassis................................................................................ 23
Figure 3.12 Robot Car Schematic. (Adapted from Arduino, 2014) ................................................... 23
Figure 3.13 Flow chart for the program ............................................................................................. 25
Figure 4.1 The hardware model of the Obstacle Avoiding Robot ..................................................... 33

viii
List of Tables

Table 2.1: Arduino Board Types based on ATMEGA328 microcontroller ........................................ 8


Table 3.1: HC-SR04 Ultrasonic Sensor Pins..................................................................................... 11
Table 3.2: Arduino UNO R3 Pins ..................................................................................................... 15
Table 3.3: Driving System Operation................................................................................................ 29

ix
List of Acronyms

GPS: Global Positioning System

DC: Direct Current

AC: Alternating current

AI: Artificial Intelligence

IDE: Integrated Development Environment

IDII: Interaction Design Institute Ivrea

LED: Light Emitting Diode

USB: Universal Serial Bus

FORTRAN: Formula Translation

COBOL: Common Business-Oriented Language

CPU: Central Processing Unit

IC: Integrated Circuit

4WD: Four-Wheel Drive

GND: Ground

IOREF: Input /Output Reference

UART: Universal Asynchronous Serial Receiver / Transmitter

AREF: Analog Reference

COM: Communication

SDA: Serial Data

SCL: Serial Clock

ICSP: In-Circuit Serial Programmer

DIY: Do It Yourself

x
RPM: Revolutions Per Minute

PWM: Pulse Width Modulation

PC: Personal Computer

xi
Chapter 1: Introduction
1.1 Background

In our world today, ROBOTICS is a very interesting research area, which is fast growing as it is the
simplest way for modifying modern day technology. Robotics plays a major role in technology
advancement, which is why I decided to work on the robotics field and design something intelligent
to make human life simpler.

An autonomous robot is one which can move without any external interference in an environment
which is unstructured and unknown to the robot. The robot is able to do this because of the software
intelligence embedded inside it in order for it to be able to sense the environment, detect any obstacle
which is in its path and move round the environment by avoiding these obstacles [1]. In the designing
of an autonomous robot, there are many robotic designs that can be used. To make a selection of the
design to be used, the main factor to be put into consideration is the physical environment in which
the robot will be operated. Examples of autonomous robots: walking robots, drones, robotic cars, and
snake robots.

The obstacle avoiding robot has enough intelligence in order for it to cover the maximum area of the
space provided and it has an ultrasound sensor which is used to detect any obstacles in the path of the
robot, after which it will move in a direction to avoid the obstacle [2].

The main aim of such technology is that it can play a huge role in today’s transportation as it can be
used to avoid accidents, which generally happen on congested roads by applying emergency brake. If
this technology is used in a car, it will automatically sense any objects (living things or objects) in the
path of the car and automatically apply breaks or take a side to the available free space where
necessary.

1.2 Research Problem


A necessary requirement of every autonomous mobile robot is obstacle avoidance. This obstacle
avoidance feature is of high importance in a robot’s navigation system in an unknown area so as to
prevent collisions during its operation. It is necessary for an autonomous robot to avoid collisions in
order to prevent damage to the object or to the robot itself. Application areas where obstacle
avoidance is necessary include automatic vacuum cleaners and helicopters. Even in robots which
work in a familiar environment and the path of the robot has been adequately defined, some

1
environmental changes could occur and cause the robot to run into an object in its way so it is
necessary for the robot to be able to adapt to the change by avoiding any objects in its path. This
problem of effective trajectory planning is what has led to the need for a robot that can detect and
avoid objects in a pre-computed path, or objects that appear suddenly. The solution to this trajectory
problem involves the use of sensors by the robot to detect objects and avoid them thereby making
the robot to be more independent since it would not require external influence.

1.3 Motivation
The idea of an autonomous robot is not a new one. Every company that uses mobile robots to
perform tasks would like the robot to be able to carry out its functions effectively without any
external control. With the advancement in the GPS technology, achieving the independent robot
movement is closer to reality. However, the concern of how the robot sees and interacts with its
environment must be addressed before the robot is used. To address this concern, sensors are used to
collect enough environmental data that the robot interprets for smooth navigation of the robot. This
method of addressing the concern leaves three questions: is it possible for a sensor to collect enough
data for collision-free movement? Also, is there a fast and effective method of interpreting this data
to the robot? Lastly, after interpretation, can the robot react and make correct decisions as quick and
precise as a human would in the same environment? These are questions that must be answered to
allow for human-free robot movement

1.4 Aim and Objectives

The Aim of this project is to design and implement a robot car that is able to move round an unknown
environment without running into obstacles in its path.

The Objectives of the project are as follows:

 The robot car should have the capacity to detect obstacles in its path based on a predetermined
threshold distance.
 After detection of an obstacle, the robot should be able to change its direction to a relatively open
path by making an autonomous decision.
 The robot car should not require any external control during its operation.
 The robot car should be able to measure distance between itself and an obstacle in real time.
 The robot car should be able to operate effectively in an environment which is unknown to it.

2
Chapter 2: Literature review
2.1 Artificial Intelligence

Artificial Intelligence (AI) is the ability of a computer or a computer controlled-robot to think and
perform tasks like humans. An artificially intelligent machine is one which is capable of learning,
reasoning, planning, perception, problem solving [3].
This field was discovered on the claim that human intelligence can be sufficiently described to the
point that a machine can simulate it.

2.2 Robotics and Robots

Robotics is an interdisciplinary research area at the interface of computer science and engineering.
Robotics involves the design, construction, operation, and use of robots [4]. The goal of robotics is to
design intelligent machines in order to help human beings in their daily activities. This technology
has resulted in automated machines that can replace humans in manufacturing processes or dangerous
environments. These robots have numerous structures depending on their functions.

Generally, robots are grouped into:

 Manipulator robots (industrial robots)


 Mobile robots (autonomous vehicles)
 Self-reconfigurable robots, which are robots that can adjust themselves based on the task to be
performed.

Robots may be designed to act on their decision-making ability or to be controlled by humans [5].

Robots work by trying to mimic/replicate the human behaviour as they are made to possess the same
components of human beings. These components include:

 A muscle system in order to move the body structure


 A body structure.
 A power source used to activate sensors and muscles
 A sense system used to obtain environmental information
 A brain system which processes the sensed information and gives the muscles information on how
to respond

3
2.3 Robot Learning

Robot learning involves the combination of robotics and machine learning by the learning of different
algorithms by the robot in order to apply techniques which will enable it to obtain skills and adjust to
its surrounding. The robot learning can take place by imitation of humans or by self-learning guided
by a human [6].

2.4 Autonomous Robot

An Autonomous robot is one that is capable of performing activities with a high level of self-control
and without any form of externa control. This kind of robot is achieved by integrating artificial
intelligence, robotics, and information engineering [7].

Autonomous robots, just like human beings, additionally can settle on their own choices and afterward
respond accordingly. A genuinely autonomous robot is one that can sense and recognize its
environment, settle on choices dependent on what it sees and afterwards, actuate a movement in
response. Regarding mobility, for instance, the decision-based activities incorporate but however are
not restricted to the following: starting, stopping, and manoeuvring around obstructions that are in
their path.

Some mobile robots utilize ultrasound sensors to detect obstacles or infrared. These sensors work in
similar fashion to animal echolation. The robot sends a beam of light or a sound signal out and
observes the reflection distance by identifying how long it takes the signal to bounce back [8], [9].

In some advanced robots, stereo vision is used. This method uses two cameras for depth perception
and image recognition in order to detect and categorize different objects.

In more advanced robots, they can be able to study new environments and adjust to them. They even
work on areas with uneven land as they can link land patterns with certain actions. For example, a
rover robot constructs a land map by utilizing its visual sensors and if the map depicts uneven land
patterns, the robot can adapt to the environment and choose to take a different path. Such kind of
systems can be highly beneficial for exploration and can be used for operation on other planets [10],
[11].

Figure 2.1 shows the bot developed by NASA called Urbie which was designed for military uses. It
is able to move through stairs and other such paths [12].

4
Figure 2.1 Autonomous Urbie by NASA. (Adapted from NASA, 2001)

When the robot gets stuck, it moves its appendages in every way until something works out. Force
sensors work very closely with the actuators, instead or computer directing everything based on a
program.

2.5 Arduino

2.5.1 Overview
Arduino is a widely used open-source prototyping platform which is based on software and hardware
that are easy to use. It is made up of a programmable microcontroller unit and the Arduino Integrated
Development Environment (IDE) which is used to write and upload codes to the Arduino board. The
Arduino board is the physical microcontroller boards used for making electronic projects. Arduino
boards are capable of reading inputs and converting them into outputs. You can send instructions to
the microcontroller on the Arduino board and tell it what to do using the Arduino programming
language (based on Wiring). Due to the open-source nature of the Arduino environment, codes are
easily written and uploaded to the Arduino board. Arduino is written in Java so it can be run on Linux,
Mac OSX and windows [13], [14].

5
2.5.2 Features
The key features of Arduino include:
 The Microcontroller boards are capable of detecting signals (analog or digital) from different
sensors and convert the input into an output by triggering a response such as activating a motor,
turning a LED on or off, and many other actions.
 The microcontroller board functions can be controlled by sending instructions to the
microcontroller using the Arduino Integrated Development Environment.
 An external piece of hardware for loading code into the board is not requires unlike in some other
circuit boards. Just a USB cable is required.
 It is simple to learn the Arduino programming language as it is a simplified version of C++.
 Arduino allows for a standard form factor, which breaks the functions of the board to a more
accessible package.

Figure 2.2 Arduino Integrated Development Environment (IDE).

6
2.5.3 Advantages
Arduino boards are widely used in making different engineering projects and different applications.
The Arduino software is simple and adequate for projects and it runs on Windows, Mac, and Linux.

Arduino is utilized in schools to make low cost scientific instruments in order to verify the principles
of chemistry and physics [15], [16], [17]. Arduino is preferred over other microcontrollers because:
 Simpler working process due to its friendly programming environment and USB availability.
 It is inexpensive.
 It uses a Cross-platform application.
 It has a clear and simple programming environment.
 It has an open source and extensible software.
 It has an open source and extensible hardware.

2.5.4 Arduino Board Types


There are various types of Arduino boards which are available depending on the different
microcontrollers use though all these boards utilize a single Integrated Development Environment.

What differentiates the boards is the number of inputs, outputs, speed, operating voltage, form factor
etc.
Some boards have been designed to be embedded and have no programming interface (hardware) that
needs to be bought separately. Some are made to run directly from a 3.7V battery while others need
at least 5V [18][19].

7
Table 2.1: Arduino Board Types based on ATMEGA328 microcontroller

Operating Clock Digital Analog PWM UA Programming


Volt Speed i/o Inputs RT Interface
Arduino Uno R3 5V 16MHz 14 6 6 1 USB via
ATMega16U2
Arduino Uno R3 5V 16MHz 14 6 6 1 USB via
SMD ATMega16U2
Red Board 5V 16MHz 14 6 6 1 USB via FTDI
Arduino Pro 3.3V 8MHz 14 6 6 1 FTDI-Compatible
3.3v/8 MHz Header
Arduino Pro 5V 16MHz 14 6 6 1 FTDI-Compatible
5V/16MHz Header
Arduino mini 05 5V 16MHz 14 8 6 1 FTDI-Compatible
Header
Arduino Pro mini 3.3V 8MHz 14 8 6 1 FTDI-Compatible
3.3v/8mhz Header
Arduino Pro mini 5V 16MHz 14 8 6 1 FTDI-Compatible
5v/16mhz Header
5V 16MHz 14 6 6 1 FTDI-Compatible
Arduino Ethernet Header**-]]]#
Arduino Fio 3.3V 8MHz 14 8 6 1 FTDI-Compatible
Header
LilyPad Arduino 3.3V 8MHz 14 6 6 1 FTDI-Compatible
328 main board Header
LilyPad Arduino 3.3V 8MHz 9 4 5 0 FTDI-Compatible
simple board Header

8
Chapter 3: Materials and Analysis Techniques
3.1 Materials

The following components were used for the hardware implementation of the project:

 1x HC-SR04 Ultrasonic sensor


 1x HC-SR04 holder
 3x 9v battery
 3x 9v battery connectors
 1x SG90 Servo Motor
 1x Arduino UNO R3
 2x Power switch
 1x 4WD Chassis RC car
 Jumper wires
 4x DC Motors
 1x L293D Motor Driver

3.2 Analysis

3.2.1 HC-SR04 Ultrasonic Sensor

Figure 3.1 Diagram showing the basic operation of the HC-SR04 Ultrasonic Sensor. (Adapted from
Electroschematics, 2015)

9
3.2.1.1 HC-SR04 Ultrasonic Sensor Overview
The word ‘ultra’ means ‘beyond’ and sonic means ‘sound’. Combining the two of them together
ultrasonic is a sound which is above the human hearing range (20 KHz).
An Ultrasonic sensor is a sensor that can detect ultrasound waves by converting the waves into electric
signals or vice versa [20], [21], [22].
An ultrasonic sensor is capable of measuring the total distance between itself and an object by sending
out a wave at a certain frequency and listening for that wave to bounce back to it. During this, it
records the tame taken between when the wave was generated and when it bounced back in order to
calculate the distance between it and an object [23].

3.2.1.2 HC-SR04 Ultrasonic Sensor Features


 It has a 5V DC power supply
 Its Quiescent current is less than 2mA
 Its working current is 15mA
 Its effectual angle is less than 15 degrees
 Its ranging distance is between 2cm – 400cm/1” – 13ft
 Its Resolution is 0.3cm
 Its measuring angle is 30degrees
 Its Trigger pulse width is 10uS
 Its dimension is 45mm x 20mm x 15mm

10
3.2.1.3 HC-SR04 Ultrasonic Sensor Pin Configuration

Figure 3.2 HC-SR04 Ultrasonic Sensor Pins

Table 3.1: HC-SR04 Ultrasonic Sensor Pins

Pin Number Pin Name Description

1 VCC The is used to power the sensor with 5V

2 Trigger This is an Input pin which has to be kept high


for 10us to initialize measurement by sending
Ultrasound wave.
3 Echo This is an output pin which goes high for a
period of time equal to the time taken for the
Ultrasonic wave to return back to the sensor.
4 Ground This pin is connected to the ground of the
system

11
3.2.1.4 Working of HC-SR04 Ultrasonic Sensor
Sonar is used by the ultrasonic sensor to obtain the distance between itself and an object. Here’s how
it works:

 The trig pin(transmitter) sends a signal which is a high-frequency sound


 The signal is reflected once it hits an object
 The echo pin(receiver) receives the reflection

For example, if the distance between the object and the sensor is 10cm, and the speed of sound is
340m/s, the sound wave will need to travel about 294μs. The value gotten at the echo pin will be twice
that number because the wave travels to and fro. To get the distance in cm, the time gotten at the echo
pin is multiplied by 0.034 and divided by 2 [24], [25].

3.2.1.5 Applications of HC-SR04 Ultrasonic Sensor


 It is used in robots to detect and avoid obstacles in the path of the robot.
 It is used to measure distance within a wide range (200cm-400cm)
 It can be used for mapping of objects around a sensor by rotation of sensor.
 Since the Ultrasonic waves are capable of penetrating water, it can be used to measure depths of
places like pits, wells, etc. [26].

12
3.2.2 SG-90 Servo Motor

Figure 3.3 SG-90 Servo Motor.

3.2.2.1 SG-90 Servo Motor Overview


A servo motor is an electrical device that pushes or rotates objects with high precision. If there is need
for an object to be rotated as a specific angle or distance, then a servo motor is used [27].

A servo motor consists of a motor that uses servo mechanism. The two types of servo motors are the
DC servo motors (DC powered) and the AC servo motor (AC powered) where the difference between
them is the input power. A very high torque can be obtained from a small and lightweight servo motor
which allows these servo motors to be used in applications like robots, toy cars, etc. The main reason
why a servo motor is used is because of its high angle precision, i.e. after rotating, it will stop and wait
for the next instruction to happen unlike a normal electric motor which rotates as long as it is being
supplied power and stops rotating when power supply is turned off [28][29].

3.2.2.2 Working Principle of Servo Motors


A servo motor includes motors (DC and AC), a potentiometer, gear assembly, and a controlling circuit.

Firstly, gear assembly is used to reduce the Revolutions per Minute (RPM) and to increase the torque
of the motor. At the initial position of the servo motor shaft, the potentiometer knob is in such a way
that no electrical signal is generated at the potentiometer output. An electrical signal is passed to
13
another input terminal of the error detector amplifier and the difference between these two signals is
that one is coming from the potentiometer and the other is coming from another source. The both
signals will be processed in a feedback mechanism and the output will be provided in terms of an error
signal. This error is used as the motor input to cause it to start rotating. The motor shaft is connected
to the potentiometer which causes the potentiometer to generate a signal as the motor rotates. As the
angular position of the potentiometer changes, its feedback output also changes and after a while the
potentiometer reaches a position that the potentiometer output and the external signal are the same.
Once the outputs are the same, the amplifier will not output anything into the motor since there is no
difference between the generated potentiometer signal and the external applied signal which in turn
causes the motor to stop rotating.

Servo motors are controlled by Pulse width Modulation (PWM) which is provided by the control
wires. There is a minimum pulse, a maximum pulse and a repetition rate. A servo motor can turn 90
degrees to either direction from its neutral position. The servo motor expects a pulse every 20ms which
determines how far the motor will turn. In the figure 4-11 below, a 1.5ms pulse will make the motor
turn 90 degrees. If the pulse is shorter than 1.5ms, the shaft moves to 0 degrees and if it is longer than
1.5ms, the shaft will turn to 180 degrees. Pulse with modulation simply means that the angle of
rotation is dependent on the duration of pulse applied to the control PIN.

Basically, servo motors are made up of a DC motor controlled by a potentiometer (Variable resistor)
and some gears which convert the high-speed force into torque [30].

3.2.2.3 Applications of Servo Motors


 Robotics
 Animatronics
 Radio Control Cars/Boats/Planes

3.2.2.4 Advantages of using Servo Motors


 Low Cost
 They have a wide range of sizes and torque ratings
 They are simple to control

14
3.2.3 Arduino UNO R3

Figure 3.4 Arduino UNO R3 Board.

3.2.3.1 Arduino UNO Power Overview

 External power supply voltage: 7V to 12V DC


 USB power or externally via barrel jack connector

Table 3.2: Arduino UNO R3 Pins

Pin Function
Vin Voltage from External power jack
5V 5V output from on-board Voltage regulator chip
3.3V 3.3V output from on-board Voltage regulator chip
Gnd 3 pins for ground
IOREF Tied to 5V, tells Arduino shields voltage level from which Arduino board operates
Reset From RESET pin on MCU, tied to VCC through 10K resistor, pull to GND to reset

15
3.2.3.2 Arduino UNO Digital Input/ Output Overview
 It has 14 Digital Inputs and Outputs
 It has a logic level of 5V
 Its Sink/Source is 20mA per pin
 It utilizes Universal Asynchronous Serial Receiver/Transmitter (UART) for which pin 0 is for
receiving and pin 1 is for transmitting
 It has 8-bit PWM
 It has a Serial Peripheral Interface [19].

3.2.3.3 Arduino UNO Analog Inputs Overview


 Analog Input pins are A0, A1, A2, A3, A4, A5
 Its sampled input is from 0V to 5V and it has a 10 bits resolution
 The AREF pin can be used to adjust the upper limit of the input range
 It has Two-wire Interface COM
 Pin A4 is SDA pin for data
 Pin A5 is SCL pin for clock [20].

3.2.3.4 Arduino UNO R3 Communication Overview


 It can communicate with a computer, another Arduino, shields, sensors [21].
 Asynchronous communication (No clock):
 UART TTL (5V)
 On board ATmegaU16 programmed to function as USB to serial chip
 ATmegaU16 uses standard USB COM drivers so that no external drivers are required for
communication with the board
 Synchronous communication (Clock) uses SPI Pins 10, 11, 12, 13, and TWI pins A4 and A5.

3.2.3.5 Arduino Programming Overview


 The bootloader firmware comes already preinstalled with the Arduino UNO [22]
 New sketches can be Uploaded via the USB

16
 External programmer can be used to upload sketches via the In-circuit serial programmer pins
(ICSP)
 It has 32KB of Flash memory where the sketches are stored
 It has 2KB of SRAM where the variables are stored until power cycled
 It has 1KB of EEPROM which stores long term information.

3.2.4 DC Motor

Figure 3.5 DC Motors (Adapted from Allaboutcircuits, 2017)

3.2.4.1 DC Motor Overview


A DC motor is a device that converts electrical energy into mechanical energy as it rotates. A magnetic
field is produced by an inductor inside the DC motor and this magnetic field creates a rotary motion
as DC voltage is applied to its terminal. There is an Iron shaft inside the motor which is wrapped in a
coil of wire. This shaft contains two fixed North and South magnets on both sides which causes both
an attractive and repulsive force thereby producing a torque.

3.2.4.2 Types of DC Motors


 Brushed Motors
 Brushless Motors
 Planetary Gear Motors
 Spur Gear Motors
 Stepper Motors

17
 Coreless & Coreless Brushless Motors
 Gear heads Motors

3.2.4.3 DC Gear Motor

Figure 3.6 DC Gear Motor. (Adapted from Allaboutcircuits, 2017)

DC Gear Motors are the most common kind of motors which convert electrical to mechanical energy.

A gear motor consists of a gearbox and a motor. The addition of a gear head to a motor reduced the
speed while increasing the torque output. Important parameters in gear motors include:

 Speed (rpm)
 Efficiency (%)
 Torque (lb.-in)

The factors to consider before selecting a gear motor for any application include:

 Speed
 Load
 Torque requirements

18
3.2.5 L293D Motor Driver Shield

Figure 3.7 L293D Motor Driver Shield (Adapted from Lelong, 2020)

3.2.5.1 L293D Motor Driver Shield Overview


The L293D is a high voltage, high current Integrated circuit which is used to drive DC motors with a
power supply of up to 36V. This chip is able to supple a maximum of 600mA per channel. This chip
is also known as a type of H-Bridge as it enables a voltage to be applied across a load in either direction
to an output, e.g. a motor [26], [27], [28].

3.2.5.2 Features of the L293D Motor Driver Shield


 It has to connections to allow for 5V servos to be connected to the Arduino’s high-resolution
dedicated timer
 It has up to 4 bi-directional DC motors with individual 8-bit speed selection
 It has up to 2 stepper motors with single coil, double coil, interleaved or micro-stepping.
 It has 4 H-Bridges

19
 It has Pull down resistors to disable motors during power up
 The Arduino reset button is brought to the top
 It is compatible with Mega, UNO & Duemilanove
 Its dimensions are: 69mm x 53mm x 14.3mm

3.2.5.3 Applications of the L293D Motor Driver Shield


 It is utilized in robots that require a stepper motor interface
 It is used in multiple DIY projects

3.3 Methodology
3.3.1 Robot Construction
3.3.1.1 Robot Working Principle
The robot uses the Ultrasonic sensor to measure the distance in front of it then it moves. As the distance
reduces, the robot interprets it as the presence of an obstacle. As soon as the robot detects the obstacle,
it stops and moves back a few cm then looks left and right before moving to a free path.

3.3.1.2 Hardware Components


 1x Arduino UNO R3
 1x 4 Wheel Robot Car Chassis(Includes Motors)
 1x HC-SR04 Ultrasonic sensor
 1x HC-SR04 Ultrasonic sensor holder
 1x L293D Motor Driver Shield
 1x SG90 Servo Motor
 2x 9V Battery
 1x 9V Battery clip without DC jack
 1x 9V Battery clip with DC jack
 1x Power Switch
 Jumper wires

20
Figure 3.8 Block diagram showing the Hardware Implementation of the project

3.3.1.3 Necessary Tools and Machines


 1x Soldering Iron
 Solder
 Glue
 Screw drivers
 Arduino IDE

21
3.3.1.4 Constructing the Robot car

Figure 3.9 Robot Chassis Components.

 Step 1. Connect the motor and wheels to the chassis by soldering the thick red and black wires to
the positive and negative terminals of the motors then attach them to the chassis [32].

Figure 3.10Wheels and Motors Attached to the Chassis

 Step 2. Attach the switch, battery clip, SG90 Servo Motor and Arduino UNO to the chassis. After
this, mount the L293D Motor Driver shield on the Arduino UNO R3 and the HC-SR04 to the
Servo motor.
22
Figure 3.11 Components attached to the chassis

 Step 3. Wire up components as shown in figure 4-17 below.

Figure 3.12 Robot Car Schematic. (Adapted from Arduino, 2014)

23
3.3.2 Programming the Robot
The Arduino microcontroller communicates with the PC via the USB connection. Data is transferred
between the board and the PC bit by bit. An adaptor is used for power supply to the board and a USB
programmer is used to burn the hardware program (written in Arduino IDE) into the board.

24
3.3.2.1 Flowchart of the program

Figure 3.13 Flow chart for the program


25
3.3.2.2 Arduino Coding
The code requires the use of three libraries and two of them must be downloaded for the program to
be able to compile. The first library is the motor shield driver library and the second one is the
NewPing library for the supersonic distance sensor.
Step 1. Firstly we need to include all the libraries in the code.
 Motor Shield library
 Servo Motor library
 Ultrasonic Sensor library
#include <AFMotor.h> //add Adafruit Motor Shield library
#include <Servo.h> //add Servo Motor library
#include <NewPing.h> //add Ultrasonic sensor library

Step 2. We declare the pins that are connected to the ultrasonic sensor. We also declare variables
which will be used to store info in this code:
#define TRIG_PIN A0 /* Pin A0 on the Motor Drive Shield soldered to the ultrasonic sensor*/
#define ECHO_PIN A1 /* Pin A1 on the Motor Drive Shield soldered to the ultrasonic sensor*/
#define MAX_DISTANCE 300 /* sets maximum useable sensor measuring distance to 300cm*/
#define MAX_SPEED 160 /* sets speed of DC traction motors to 150/250 or about 70% of full speed
- to get power drain down.*/
#define MAX_SPEED_OFFSET 40 /* this sets offset to allow for differences between the two DC
traction motors*/
#define COLL_DIST 30 /* sets distance at which robot stops and reverses to 30cm*/
#define TURN_DIST COLL_DIST+20 /* sets distance at which robot veers away from object*/
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE); /* sets up sensor library to use the
correct pins to measure distance.*/

Step 3. We initialize the servo motor by creating an object of the servo library. Also we initialize the
Motors to which the wheels are connected using the AF library:
AF_DCMotor leftMotor1(1, MOTOR12_1KHZ); /* create motor #1 using M1 output on Motor Drive
Shield, set to 1kHz PWM frequency*/

26
AF_DCMotor leftMotor2(2, MOTOR12_1KHZ); /* create motor #2, using M2 output, set to 1kHz
PWM frequency*/
AF_DCMotor rightMotor1(3, MOTOR34_1KHZ);/* create motor #3, using M3 output, set to 1kHz
PWM frequency*/
AF_DCMotor rightMotor2(4, MOTOR34_1KHZ);/* create motor #4, using M4 output, set to 1kHz
PWM frequency*/
Servo myservo; // create servo object to control a servo

Step 4. We define/initialize variables to be used


int leftDistance, rightDistance; //distances on either side
int curDist = 0;
String motorSet = "";
int speedSet = 0;

Step 5. We go into the void setup () function where we initialize the servo motor and set it to look
straight using a 90 degrees angle.
void setup() {
myservo.attach(10); /* attaches the servo on pin 10 (SERVO_1 on the Motor Drive Shield to the
servo object */
myservo.write(90); // tells the servo to position at 90-degrees ie. facing forward.
delay(1000); // delay for one seconds
}

Step 6. We go into the loop function and measure the distance and set it to change direction if the
forward path is blocked
void loop() {
myservo.write(90); // move eyes forward
delay(90);
curDist = readPing(); // read distance
if (curDist < COLL_DIST) {changePath();} /* if forward is blocked change direction*/

moveForward(); // move forward

27
delay(500);
}
Step 6. We instruct it on how it is to change path.
First the void changePath () function instructs it to stop forward movement, then check and store right
distance(by turning the servo motor 36 degrees), check and store left distance(by turning the servo
motor 144 degrees) and then return sensor to the centre position.
After this, we go into the void compareDistance () function and instruct it to follow the longer distance.
void changePath() {
moveStop(); // stop forward movement
myservo.write(36); // check distance to the right
delay(500);
rightDistance = readPing(); //set right distance
delay(500);
myservo.write(144); // check distace to the left
delay(700);
leftDistance = readPing(); //set left distance
delay(500);
myservo.write(90); //return to center
delay(100);
compareDistance();
}

void compareDistance() // find the longest distance


{
if (leftDistance>rightDistance) //if left is less obstructed
{
turnLeft();
}
else if (rightDistance>leftDistance) //if right is less obstructed
{
turnRight();

28
}
else //if they are equally obstructed
{
turnAround();
}
}

3.3.2.3 Sensor Coding


The Ultrasonic sensor is used to detect objects in the path of the robot so it does nor run into any
objects.

The sensor code gives the sensor instruction to read the sensor distance.
int readPing() { // read the ultrasonic sensor distance
delay(70);
unsigned int uS = sonar.ping();
int cm = uS/US_ROUNDTRIP_CM;
return cm;
}

3.3.2.4 Driving System Coding


The following wheel rotation will be used in order to drive the car.

Table 3.3: Driving System Operation

Motion/Motor Left Motor 1 Left Motor 2 Right Motor 1 Right Motor 2


Move Forward Forward Forward Forward Forward
Move Backward Backward Backward Backward Backward
Turn Right Forward Forward Backward Backward
Turn Left Backward Backward Forward Forward

void moveStop() {

29
leftMotor1.run(RELEASE);
leftMotor2.run(RELEASE);
rightMotor1.run(RELEASE);
rightMotor2.run(RELEASE);
} // stop the motors.

void moveForward() {
motorSet = "FORWARD";
leftMotor1.run(FORWARD); // turn it on going forward
leftMotor2.run(FORWARD); // turn it on going forward
rightMotor1.run(FORWARD); // turn it on going forward
rightMotor2.run(FORWARD); // turn it on going forward
for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) /* slowly bring the speed up to avoid
loading down the batteries too quickly*/
{
leftMotor1.setSpeed(speedSet);
leftMotor2.setSpeed(speedSet);
rightMotor1.setSpeed(speedSet);
rightMotor2.setSpeed(speedSet);
delay(5);
}
}

void moveBackward() {
motorSet = "BACKWARD";
leftMotor1.run(BACKWARD); // turn it on going backward
leftMotor2.run(BACKWARD); // turn it on going backward
rightMotor1.run(BACKWARD); // turn it on going backward
rightMotor2.run(BACKWARD); // turn it on going backward

30
for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) /* slowly bring the speed up to avoid
loading down the batteries too quickly*/
{
leftMotor1.setSpeed(speedSet);
leftMotor2.setSpeed(speedSet);
rightMotor1.setSpeed(speedSet);
rightMotor2.setSpeed(speedSet);
delay(5);
}
}

void turnRight() {
motorSet = "RIGHT";
leftMotor1.run(FORWARD); // turn motor 1 forward
leftMotor2.run(FORWARD); // turn motor 2 forward
rightMotor1.run(BACKWARD); // turn motor 3 backward
rightMotor2.run(BACKWARD); // turn motor 4 backward
rightMotor1.setSpeed(speedSet+MAX_SPEED_OFFSET);
rightMotor2.setSpeed(speedSet+MAX_SPEED_OFFSET);
delay(1500); // run motors this way for 1500
motorSet = "FORWARD";
leftMotor1.run(FORWARD); // set both motors back to forward
leftMotor2.run(FORWARD);
rightMotor1.run(FORWARD);
rightMotor2.run(FORWARD);
}

void turnLeft() {
motorSet = "LEFT";
leftMotor1.run(BACKWARD); // turn motor 1 backward

31
leftMotor2.run(BACKWARD); // turn motor 2 backward
leftMotor1.setSpeed(speedSet+MAX_SPEED_OFFSET);
leftMotor2.setSpeed(speedSet+MAX_SPEED_OFFSET);
rightMotor1.run(FORWARD); // turn motor 3 forward
rightMotor2.run(FORWARD); // turn motor 4 forward
delay(1500); // run motors this way for 1500
motorSet = "FORWARD";
leftMotor1.run(FORWARD); // turn it on going forward
leftMotor2.run(FORWARD); // turn it on going forward
rightMotor1.run(FORWARD); // turn it on going forward
rightMotor2.run(FORWARD); // turn it on going forward
}

void turnAround() {
motorSet = "RIGHT";
leftMotor1.run(FORWARD); // turn motor 1 forward
leftMotor2.run(FORWARD); // turn motor 2 forward
rightMotor1.run(BACKWARD); // turn motor 3 backward
rightMotor2.run(BACKWARD); // turn motor 4 backward
rightMotor1.setSpeed(speedSet+MAX_SPEED_OFFSET);
rightMotor2.setSpeed(speedSet+MAX_SPEED_OFFSET);
delay(1700); // run motors this way for 1700
motorSet = "FORWARD";
leftMotor1.run(FORWARD); // set both motors back to forward
leftMotor2.run(FORWARD);
rightMotor1.run(FORWARD);
rightMotor2.run(FORWARD);
}

32
Chapter 4: Results and Discussion
4.1 Results
The outcome of this thesis is a simple, Arduino-controlled robot car which moves around detecting
obstacles in its way and avoiding them. During operation of the robot, the ultrasonic sensor sends
out an ultrasound wave to the front position (90 degrees), right position (36 degrees), and left
position (144 degrees). When the wave strikes an obstacle, it bounces back and the distance is stored
for the front, right, and left position. After this, the microcontroller compares the values based on its
algorithm and determines whether to move forward or change path.

Tests carried out on the final hardware revealed the limitations of the detection algorithm. The
limitations were related to cases of some obstacles not being detected and this was as a result of the
sensor not being able to measure obstacles outside the measuring range of the sensor. When an
object is in the way of the car and this object is not within the line of sight of the sensor, it will not
be detected thereby leading to collision. To avoid this, the testing was further carried out in an
enclosed area where the wall is the only obstacle and the car was able to move freely without
collision. To implement a car which will detect multiple obstacles and avoid them, more sensors
have to be used in order to cover a wider range for obstacle detection.

Figure 4.1 The hardware model of the Obstacle Avoiding Robot

33
4.2 Discussion
Sensor Performance: The sensor used is one of the most important components. It is a very
important component because the performance of this robot is critically dependent on the accuracy
of the sensor. The HC-SR04 has a measuring range of 30 degrees and 300cm. It operates by emitting
a high-frequency sound wave (40Khz) through one of its piezo-electric transducers and detects the
returning pulses (echo) through another transducer. When obstacles in the path of the car were not
within this 30-degree angle, the sound waves emitted by the sensor could not hit these objects which
did not allow for object detection. This was an issue because the robot car can collide with an object
which has a lesser height than the sensor or objects which are in the way of the car but do not fall
within the sensor range. Aside from this range issue, the sensor was able to detect objects within its
range for obstacle avoidance.

Battery Stress: There was a lot of stress on the battery coming from the components, especially the
motors. The motors need a lot of energy for their operation, especially cheaper motors because they
have less efficiency. The motor driver shield is powered separately from the Arduino. The Arduino
requires a 9-12V supply and it was supplied power using a single 9V battery while the motor driver
shield requires 5-28V and was supplied power with two 9V batteries connected in series. The
motors, servo motor and sensor all required 3-6V each. With fully charged batteries for the motor
driver shield, it took a few minutes of operation before the power supplied was insufficient to rotate
the motors.

Effect of Heat on Motor Driver Shield: The continuous current that the shield can deliver is
dependent on how well the shield is kept cool. The printed circuit board is designed in such a way so
as to draw heat out of the motor driver chips but performance can still be improved by addition of
heatsinks. As the motor driver chip temperature approaches its limit, less power is delivered to the
motor which would result in motors not being able to rotate. The shield was tested at room
temperature with no forced air flow or heat sinks and it was able to deliver continuous current to the
four motor channels before the thermal protection started reducing the current. The shield delivered
enough power to move the car for about 15 minutes, after which the power was insufficient for the
motors.

34
5 Conclusion, Recommendation and Issues for Future Work
5.1 Conclusion

Today we are in a world of robotics and we use different types of robots daily in our life.

This “Obstacle Avoidance Robot Car” project is proved using the Ultrasonic sensor for detecting
objects, Motor Driver Shield for driving the DC motors, DC motors for movement of the wheels of
the robot with the help of the Arduino Microcontroller. The factors which affect the accuracy of the
designed robot include the environment the robot was tested and the number of present obstacles in
the test space. These factors mainly affected the sensor which means that the accuracy of the robot is
dependent on the sensor.

5.2 Recommendation

For a fully autonomous robot, it should be able to adapt to its environment (land, underwater,
underground, space) as this is very key in robotics. It should also be able to work for extended time
periods without external intervention, avoid harmful situations, and move all or part of itself
throughout its operating environment.

For better results and improved accuracy of this robot, better sensors are required. Also, better
actuators will result in a faster and more efficient robot. Further recommendations include:

 Addition of a Camera: If a camera is added into this project, the robot can be driven beyond line
of sight. Also, the camera could be used for image processing purposes.
 Addition of wireless technology: If wireless technology is added to the current project, this could
allow for external communication and control of the robot from a remote computer.
 Depending on the application, the robot can be given a task to identify a place on a map, go there,
and perform a certain function

5.3 Issues

The performance and accuracy of this robot majorly depends on the sensor used and the number of
sensors used. The ultrasonic sensor used is for commercial applications and it can easily encounter
interference. This caused issues with getting accurate distance measurements under some certain
conditions.

35
The sensor cannot accurately measure the distance between itself and an object when:
 Distance is greater than 3 metres
 The angle is too shallow
 The object is too small
 The object surface is not reflective

36
References
[1] Crisp, J. (2004). Introduction to Microprocessors and Microcontrollers. Oxford: Newnes.
[2] Hall, D. (2005). Microprocessors and Interfacing. New york: Tata McGraw Hill Education
Private Limited.
[3] M. Saravanan, N. S. (2010). Microprocessors and Microcontrollers. Oxford: Oxford University
Press.
[4] Monk, S. (2017). Electronics Cookbook. California: O’Reilly Media, Inc.
[5] Murphy, R. R. (2000). Introduction to AI Robotics. Massachusetts: MIT Press.
[6] Paul, O. (2019). Robotics. Retrieved from
https://www.sciencedirect.com/topics/engineering/robotics.
[7] What is robotics?. (2019). Retrieved from https://builtin.com/robotics.
[8] Adam, A. (2019). Robotics. Retrieved from https://www.britannica.com/technology/robotics.
[9] Artificial Intelligence. (2018). Retrieved from https://builtin.com/artificial-intelligence.
[10] Rouse, M. (2020). What techtarget is artificial intelligence. Retrieved from
https://searchenterpriseai..com/definition/AI-Artificial-Intelligence.
[11] Owen-Hill, A. ( 2020). What's the difference between robotics and Artificial Intelligence.
Retrieved from https://blog.robotiq.com/whats-the-difference-between-robotics-and-
artificial-intelligence.
[12] NASA, (2001). Urbie. Accessed on April 16 2020. Retrieved from
https://www.nasa.gov/vision/earth/technologies/urbie.html

[13] Banzi, M. (2008). Getting started with Arduino. California: O'Reilly Media, Inc.
[14] Banzi, M. (2008). Getting started with Arduino. California: O'Reilly Media, Inc.
[15] John. (2018). Story and history of development of Arduino. Retrieved from
https://www.circuitstoday.com/story-and-history-of-development-of-arduino
[16] Nick. (2020). A brief history of Arduino. Retrieved from https://8bitwork.com/2019/06/02/a-
brief-history-of-arduino/
[17] Nussey, J. (2013). Arduino for Dummies. For Dummies.
[18] Perea, F. (2015). Arduino Essentials. Birmingham: Packt Publishing Ltd
[19] Monk, S. (2011). Programming Arduino: Getting Started with Sketches. New york: McGraw-
Hill Education TAB.
[20] Blum, R. ( 2014). Arduino Programming in 24 Hours. Indianapolis: Sams Publishing.

37
[21] Hughes, J. (2016). Arduino: A technical reference. California: O'Reilly Media, Inc.
[22] Geddes, M. (2016). Arduino Project Handbook. California: O’Reilly Media, Inc.
[23] HC-SR04 Ultrasonic sensor. (2017).Retrieved from https://components101.com/ultrasonic-
sensor-working-pinout-datasheet
[24] Ultrasonic Sensor HC-SR04 and Arduino Tutorial. (2015). Retrieved from
https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/
[25] Complete Guide for Ultrasonic Sensor HC-SR04 with Arduino. (2013). Retrieved from
https://randomnerdtutorials.com/complete-guide-for-ultrasonic-sensor-hc-sr04/
[26] Adafruit Motor Shield. (2012). Retrieved from https://learn.adafruit.com/adafruit-motor-
shield?view=all
[27] Control DC, Stepper & Servo with L293D Motor Driver Shield & Arduino. (n.d.).Retrieved
from https://lastminuteengineers.com/l293d-motor-driver-shield-arduino-tutorial/
[28] Arduino L293D Motor Driver Shield Tutorial. (2019). Retrieved from
https://create.arduino.cc/projecthub/electropeak/arduino-l293d-motor-driver-shield-tutorial-c1ac9b
[29] Cox, C. (n.d.). How to control servo motors with the Arduino. Retrieved from
https://www.circuitbasics.com/controlling-servo-motors-with-arduino/
[30] Goel, A. (2018). Servo Motor: types and working principle explained. Retrieved from
https://engineering.eckovation.com/servo-motor-types-working-principle-explained/
[31] Youngblood, T. (2015). Servo Motor Control with an Arduino. Retrieved from
https://www.allaboutcircuits.com/projects/servo-motor-control-with-an-arduino/
[32] 4WD Smart Robot Car. (n.d.). Retrieved from https://www.instructables.com/id/4WD-SMART-
ROBOT-CAR/

38
Appendix
Robot Code

#include <AFMotor.h> //add Adafruit Motor Shield library

#include <Servo.h> //add Servo Motor library

#include <NewPing.h> //add Ultrasonic sensor library

#define TRIG_PIN A0 // Pin A0 on the Motor Drive Shield soldered to the ultrasonic sensor

#define ECHO_PIN A1 // Pin A1 on the Motor Drive Shield soldered to the ultrasonic sensor

#define MAX_DISTANCE 300 // sets maximum useable sensor measuring distance to 300cm

#define MAX_SPEED 160 // sets speed of DC traction motors to 150/250 or about 70% of full speed
- to get power drain down.

#define MAX_SPEED_OFFSET 40 // this sets offset to allow for differences between the two DC
traction motors

#define COLL_DIST 30 // sets distance at which robot stops and reverses to 30cm

#define TURN_DIST COLL_DIST+20 // sets distance at which robot veers away from object

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE); // sets up sensor library to use the


correct pins to measure distance.

AF_DCMotor leftMotor1(1, MOTOR12_1KHZ); // create motor #1 using M1 output on Motor Drive


Shield, set to 1kHz PWM frequency

AF_DCMotor leftMotor2(2, MOTOR12_1KHZ); // create motor #2, using M2 output, set to 1kHz
PWM frequency

AF_DCMotor rightMotor1(3, MOTOR34_1KHZ);// create motor #3, using M3 output, set to 1kHz
PWM frequency

39
AF_DCMotor rightMotor2(4, MOTOR34_1KHZ);// create motor #4, using M4 output, set to 1kHz
PWM frequency

Servo myservo; // create servo object to control a servo

int leftDistance, rightDistance; //distances on either side

int curDist = 0;

String motorSet = "";

int speedSet = 0;

//-------------------------------------------- SETUP LOOP --------------------------------------------------------


--------------------

void setup() {

myservo.attach(10); // attaches the servo on pin 10 (SERVO_1 on the Motor Drive Shield to the
servo object

myservo.write(90); // tells the servo to position at 90-degrees ie. facing forward.

delay(1000); // delay for one seconds

//-----------------------------------------------------------------------------------------------------------------------
-------------

//---------------------------------------------MAIN LOOP ---------------------------------------------------------


---------------------

void loop() {

myservo.write(90); // move eyes forward

40
delay(90);

curDist = readPing(); // read distance

if (curDist < COLL_DIST) {changePath();} // if forward is blocked change direction

moveForward(); // move forward

delay(500);

//-----------------------------------------------------------------------------------------------------------------------
--------------

void changePath() {

moveStop(); // stop forward movement

myservo.write(36); // check distance to the right

delay(500);

rightDistance = readPing(); //set right distance

delay(500);

myservo.write(144); // check distace to the left

delay(700);

leftDistance = readPing(); //set left distance

delay(500);

myservo.write(90); //return to center

delay(100);

compareDistance();

41
void compareDistance() // find the longest distance

if (leftDistance>rightDistance) //if left is less obstructed

turnLeft();

else if (rightDistance>leftDistance) //if right is less obstructed

turnRight();

else //if they are equally obstructed

turnAround();

//-----------------------------------------------------------------------------------------------------------------------
--------------

int readPing() { // read the ultrasonic sensor distance

delay(70);

unsigned int uS = sonar.ping();

int cm = uS/US_ROUNDTRIP_CM;

return cm;

42
}

//-----------------------------------------------------------------------------------------------------------------------
--------------

void moveStop() {leftMotor1.run(RELEASE); leftMotor2.run(RELEASE);


rightMotor1.run(RELEASE); rightMotor2.run(RELEASE);} // stop the motors.

//-----------------------------------------------------------------------------------------------------------------------
--------------

void moveForward() {

motorSet = "FORWARD";

leftMotor1.run(FORWARD); // turn it on going forward

leftMotor2.run(FORWARD); // turn it on going forward

rightMotor1.run(FORWARD); // turn it on going forward

rightMotor2.run(FORWARD); // turn it on going forward

for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid
loading down the batteries too quickly

leftMotor1.setSpeed(speedSet);

leftMotor2.setSpeed(speedSet);

rightMotor1.setSpeed(speedSet);

rightMotor2.setSpeed(speedSet);

delay(5);

//----------------------------------------------------------------------------------------------------------------

43
void moveBackward() {

motorSet = "BACKWARD";

leftMotor1.run(BACKWARD); // turn it on going backward

leftMotor2.run(BACKWARD); // turn it on going backward

rightMotor1.run(BACKWARD); // turn it on going backward

rightMotor2.run(BACKWARD); // turn it on going backward

for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid
loading down the batteries too quickly

leftMotor1.setSpeed(speedSet);

leftMotor2.setSpeed(speedSet);

rightMotor1.setSpeed(speedSet);

rightMotor2.setSpeed(speedSet);

delay(5);

//-----------------------------------------------------------------------------------------------------------------------
--------------

void turnRight() {

motorSet = "RIGHT";

leftMotor1.run(FORWARD); // turn motor 1 forward

leftMotor2.run(FORWARD); // turn motor 2 forward

rightMotor1.run(BACKWARD); // turn motor 3 backward

44
rightMotor2.run(BACKWARD); // turn motor 4 backward

rightMotor1.setSpeed(speedSet+MAX_SPEED_OFFSET);

rightMotor2.setSpeed(speedSet+MAX_SPEED_OFFSET);

delay(1500); // run motors this way for 1500

motorSet = "FORWARD";

leftMotor1.run(FORWARD); // set both motors back to forward

leftMotor2.run(FORWARD);

rightMotor1.run(FORWARD);

rightMotor2.run(FORWARD);

//-----------------------------------------------------------------------------------------------------------------------
--------------

void turnLeft() {

motorSet = "LEFT";

leftMotor1.run(BACKWARD); // turn motor 1 backward

leftMotor2.run(BACKWARD); // turn motor 2 backward

leftMotor1.setSpeed(speedSet+MAX_SPEED_OFFSET);

leftMotor2.setSpeed(speedSet+MAX_SPEED_OFFSET);

rightMotor1.run(FORWARD); // turn motor 3 forward

rightMotor2.run(FORWARD); // turn motor 4 forward

delay(1500); // run motors this way for 1500

motorSet = "FORWARD";

leftMotor1.run(FORWARD); // turn it on going forward

45
leftMotor2.run(FORWARD); // turn it on going forward

rightMotor1.run(FORWARD); // turn it on going forward

rightMotor2.run(FORWARD); // turn it on going forward

//--------------------------------------------------------------------------------------------------------------

void turnAround() {

motorSet = "RIGHT";

leftMotor1.run(FORWARD); // turn motor 1 forward

leftMotor2.run(FORWARD); // turn motor 2 forward

rightMotor1.run(BACKWARD); // turn motor 3 backward

rightMotor2.run(BACKWARD); // turn motor 4 backward

rightMotor1.setSpeed(speedSet+MAX_SPEED_OFFSET);

rightMotor2.setSpeed(speedSet+MAX_SPEED_OFFSET);

delay(1700); // run motors this way for 1700

motorSet = "FORWARD";

leftMotor1.run(FORWARD); // set both motors back to forward

leftMotor2.run(FORWARD);

rightMotor1.run(FORWARD);

rightMotor2.run(FORWARD);

46

You might also like