Professional Documents
Culture Documents
ARDU 2005 - v2
ARDU 2005 - v2
ARDU 2005 - v2
Ver 2.0
May 2017
Prepared by
Training Department
Robotic Systems Enterprise (Drabot)
www.drabot.com
www.facebook.com/drabot.robotics
Supported by
Drabot Community
The training module contains several materials which have been accepted for the
award of any other degree or diploma in certain university, contains several
research papers that related to this course, and contains internet resources.
Thanks to everyone .
i
SUMMARY
This is a comprehensive module that will lead participants from basic Arduino, basic
electronics/ components, hardware interface, programming skill (C Language), and project
development. Participants are required to build a self-contained mobile robot that is able to
manoeuvre in given environment. This module covers three main types of ground robot which
are Bluetooth Ground Robot (BGR), Line Following Robot (LFR) and Autonomous Mobile
Ground Robot (AMGR).
ii
CONTENTS
iii
Contents iv
4.10 DIGITAL, ANALOG AND PWM FUNCTIONS.......................................................................................... 41
4.10.1 Digital I/O ................................................................................................................................. 41
4.10.2 Analog & PWM ......................................................................................................................... 41
4.11 SERIAL COMMUNICATION ................................................................................................................... 42
4.12 EXTRA: LANGUAGE REFERENCE ......................................................................................................... 42
vii
Figure 3-16 Compass module ............................................................................................... 26
Figure 3-17 Infrared Sensor.................................................................................................. 27
Figure 3-18 Infrared sensor working operation .................................................................... 28
Figure 3-19 Infrared Receiver Sensor VS1838B .................................................................. 28
Figure 3-20 Remote Control SE-020401 .............................................................................. 29
Figure 3-21 Battery connection if using four units of AA Alkaline Battery 1.5V. .............. 30
Figure 3-22 Battery connection if using two units of Lithium battery 3.7V. A jumper wire
(white) is needed to connect negative terminals from second battery to fourth battery. .. 30
Figure 3-23 Comparison between digital and analog signals. .............................................. 31
Figure 3-24 ADC. ................................................................................................................. 31
Figure 3-25 PWM. ................................................................................................................ 32
Figure 3-26 Serial Communication. ..................................................................................... 33
Figure 4-1 Basic structure. ................................................................................................... 34
Figure 4-2 for loop. ............................................................................................................... 37
Figure 4-3 Syntax. ................................................................................................................ 38
Figure 4-4 Math Operators. .................................................................................................. 38
Figure 4-5 Comparison Operators. ....................................................................................... 39
Figure 4-6 Variables. ............................................................................................................ 40
Figure 4-7 Digital. ................................................................................................................ 41
Figure 4-8 Analog (analogRead) and PWM (a.k.a analogWrite) ......................................... 41
Figure 5-1 Arduino UNO and USB cable. ........................................................................... 43
Figure 5-2 UNO compatible board and USB cable. ............................................................. 43
Figure 5-3 Installation 1. ...................................................................................................... 44
Figure 5-4 Installation 2. ...................................................................................................... 44
Figure 5-5 Installation 3. ...................................................................................................... 45
Figure 5-6 Windows 7: Click Control Panel > Hardware and Sound> Device Manager. For
Windows 10: You have to search Device Manager. ........................................................ 46
Figure 5-7 Check the port number (COM number) for USB-SERIAL CH340. In this case,
its port number is COM7. You have to memorise this number because you will use this
number for serial communication later (e.g. Upload code, serial monitor, graphical user
interface (GUI), etc.) ........................................................................................................ 47
Figure 5-8 Blink example. .................................................................................................... 48
Figure 5-9 Select your board (e.g. In our case is Arduino UNO)......................................... 48
Figure 5-10 Select your serial port number. ......................................................................... 49
Figure 5-11 Upload the program. ......................................................................................... 49
Figure 5-12 Results after Done Uploading. .......................................................................... 50
viii
List of Tables
ix
x
Chapter 1 Unmanned Ground Vehicle (UGV)
1.1 INTRODUCTION
An unmanned ground vehicle (UGV) is a vehicle that operates while in contact with the
ground and without an onboard human presence. UGVs can be used for many applications
where it may be inconvenient, dangerous, or impossible to have a human operator present.
Generally, the vehicle will have a set of sensors to observe the environment, and will either
autonomously make decisions about its behaviour or pass the information to a human operator
at a different location who will control the vehicle through teleoperation.
The UGV is the land-based counterpart to unmanned aerial vehicles and remotely
operated underwater vehicles. Unmanned robotics are being actively developed for both
civilian and military use to perform a variety of dull, dirty, and dangerous activities.
1.2 HISTORY
A working remote controlled car was reported in the October 1921 issue of RCA's World
Wide Wireless magazine. The car was unmanned and controlled wirelessly via radio; it was
thought the technology could someday be adapted to tanks. In the 1930s, the USSR developed
Teletanks, a machine gun-armed tank remotely controlled by radio from another tank. These
were used in the Winter War (1939-1940 ) against Finland and at the start of the Eastern Front
after Germany invaded the USSR in 1941. During World War II, the British developed a radio
control version of their Matilda II infantry tank in 1941. Known as "Black Prince", it would
have been used for drawing the fire of concealed anti-tank guns, or for demolition missions.
Due to the costs of converting the transmission system of the tank to Wilson type gearboxes,
an order for 60 tanks was cancelled.
1
Figure 1-2 RCA radio controlled car. Dayton, Ohio 1921.
From 1942, the Germans used the Goliath tracked mine for remote demolition work.
The Goliath was a small tracked vehicle carrying 60 kg of explosive charge directed through a
control cable. Their inspiration was a miniature French tracked vehicle found after France was
defeated in 1940. The combination of cost, low speed, reliance on a cable for control, and
poor protection against weapons meant it was not considered a success.
The first major mobile robot development effort named Shakey was created during the
1960s as a research study for the Defense Advanced Research Projects Agency for Artificial
Intelligence (DARPA-AI) to test its obedience with commands, which is different from
advanced robots that are autonomous or semi-autonomous. Shakey was a wheeled platform
that had a TV camera, sensors, and a computer to help guide its navigational tasks of picking
up wooden blocks and placing them in certain areas based on commands.
Unmanned ground vehicles are generally considered Remote-Operated and
Autonomous, although Supervisory Control is also used to refer to situations where there is a
combination of decision making from internal UGV systems and the remote human operator.
1.3 REMOTE-OPERATED
A remote-operated UGV is a vehicle that is controlled by a human operator via interface. All
actions are determined by the operator based upon either direct visual observation or remote
use of sensors such as digital video cameras. A basic example of the principles of remote-
operation would be a remote controlled toy car.
2
Mesa Associates Tactical Integrated Light-Force Deployment Assembly
(MATILDA)
Vecna Robotics Battlefield Extraction-Assist Robot (BEAR)
G-NIUS Autonomous Unmanned Ground Vehicles (Israel Aerospace
Industries/Elbit Systems joint venture) Guardium
Robowatch ASENDRO
Ripsaw MS1
DRDO Daksh
VIPeR
DOK-ING mine clearing, firefighting, and underground mining UGV's
MacroUSA Armadillo V2 Micro UGV (MUGV) and Scorpion SUGV
Nova 5
Krymsk APC
Figure 1-3 Guardium used by the Israel Defense Forces to operate as part of the border security
operations.
1.4 AUTONOMOUS
An autonomous UGV is essentially an autonomous robot that operates without the need for a
human controller. The vehicle uses its sensors to develop some limited understanding of the
environment, which is then used by control algorithms to determine the next action to take in
the context of a human provided mission goal. This fully eliminates the need for any human
to watch over the menial tasks that the UGV is completing.
3
Avoid situations that are harmful to people, property or itself, unless those are part of
its design specifications
Disarm, or remove explosives.
Repair itself without outside assistance.
A robot may also be able to learn autonomously. Autonomous learning includes the ability to:
Learn or gain new capabilities without outside assistance.
Adjust strategies based on the surroundings.
Adapt to surroundings without outside assistance.
Develop a sense of ethics regarding mission goals
Autonomous robots still require regular maintenance, as with all machines. One of the most
crucial aspects to consider when developing armed autonomous machines is the distinction
between combatants and civilians. If done incorrectly, robot deployment can be detrimental.
This is particularly true in the modern era, when combatants often intentionally disguise
themselves as civilians to avoid detection. Even if a robot maintained 99% accuracy, the
number of civilian lives lost can still be catastrophic. Due to this, it is unlikely that any fully
autonomous machines will be sent into battle armed, at least until a satisfactory solution can
be developed.
4
Chapter 2 Introduction to Arduino
2.1 WHAT IS ARDUINO
Arduino is an open-source electronics prototyping platform based on easy-to-use hardware
and software. It's intended for anyone making interactive projects.
Arduino boards are able to read inputs - light on a sensor, a finger on a button, etc- and
turn it into an output - activating a motor, turning on an LED, publishing something online.
You can tell your board what to do by sending a set of instructions to the microcontroller on
the board. To do so you use the Arduino programming language (based on Wiring), and the
Arduino Software (IDE), based on Processing.
Arduino was born at the Ivrea Interaction Design Institute, Italy as an easy tool for fast
prototyping, aimed at students without a background in electronics and programming. As
soon as it reached a wider community, the Arduino board started changing to adapt to new
needs and challenges, differentiating its offer from simple 8-bit boards to products for Iot
applications, wearable, 3D printing, and embedded environments. All Arduino boards are
completely open-source, empowering users to build them independently and eventually adapt
5
them to their particular needs. The software, too, is open-source, and it is growing through the
contributions of users worldwide.
There are many other microcontrollers and microcontroller platforms available for
physical computing. Parallax Basic Stamp, Netmedia's BX-24, Phidgets, MIT's Handyboard,
and many others offer similar functionality. All of these tools take the messy details of
microcontroller programming and wrap it up in an easy-to-use package. Arduino also
simplifies the process of working with microcontrollers, but it offers some advantage for
teachers, students, and interested amateurs over other systems:
Inexpensive - Arduino boards are relatively inexpensive compared to other
microcontroller platforms. The least expensive version of the Arduino module can be
assembled by hand, and even the pre-assembled Arduino modules cost less than $50.
Cross-platform - The Arduino Software (IDE) runs on Windows, Macintosh OSX,
and Linux operating systems. Most microcontroller systems are limited to Windows.
Simple, clear programming environment - The Arduino Software (IDE) is easy-to-
use for beginners, yet flexible enough for advanced users to take advantage of as well.
For teachers, it's conveniently based on the Processing programming environment, so
students learning to program in that environment will be familiar with how the
Arduino IDE works.
Open source and extensible software - The Arduino software is published as open
source tools, available for extension by experienced programmers. The language can
be expanded through C++ libraries, and people wanting to understand the technical
details can make the leap from Arduino to the AVR C programming language on
which it's based. Similarly, you can add AVR-C code directly into your Arduino
programs if you want to.
Open source and extensible hardware - The plans of the Arduino boards are
published under a Creative Commons license, so experienced circuit designers can
make their own version of the module, extending it and improving it. Even relatively
inexperienced users can build the breadboard version of the module in order to
understand how it works and save money.
Figure 2-3 The breadboard version of Arduino UNO module (basic circuit).
6
2.2 ARDUINO BOARD
Arduino senses the environment by receiving inputs from many sensors, and affects its
surroundings by controlling lights, motors, and other actuators.
Browse the full range of official Arduino products, including Boards, Modules (a
smaller form-factor of classic boards), Shields (elements that can be plugged onto a board to
give it extra features), and Kits. If you need more info you can compare the specs of each
board here. If you are wondering if your Arduino board is authentic you can learn how to spot
a counterfeit board here. Buying from outside the USA? Check out the Genuino boards.
7
Figure 2-5 Arduino products.
2.2.1 Arduino UNO (USA only) & Genuino UNO (outside USA)
The UNO is the best board to get started with electronics and coding. If this is your first
experience tinkering with the platform, the UNO is the most robust board you can start
playing with. The UNO is the most used and documented board of the whole Arduino &
Genuino family. "Uno" means one in Italian and was chosen to mark the release of Arduino
Software (IDE) 1. Please refer Arduino official website to get more information about this
board (schematic, reference design, communication, etc.)!!!
Figure 2-6 Arduino UNO (USA only) & Genuino UNO (outside USA).
The price is around RM 96 - RM 105.
8
Figure 2-7 Technical specification of Arduino UNO.
9
2.2.2 UNO compatible board (used in this course)
The UNO compatible board used in this module has all the amazing features Arduino UNO
offer: 14 Digital I/O pins with 6 PWM pins, 6 Analog inputs, UART, SPI, external interrupts,
not to forget the I2C too. It is 100% compatible with Arduino UNO program. An Arduino
UNO costs about nearly RM 100, and the UNO compatible board used in this module would
cost about RM 40 only!! The UNO compatible board has some cost optimizations such as
cheaper components and connectors. The Arduino UNO board cut costs by replacing
ATmega16U2 by CH340 USB to serial chip, and replacing the ATMEGA328P-PU MCU
(DIP) by an SMT version of the Atmel MCU such as ATMEGA328P-AU (QFP).
Other changes on UNO compatible board include:
Added extra through holes side-by-side with the Arduino headers for easier
debugging and direct soldering (usefull for practical Arduino project).
Extra 3x4 pin holes with TX, RX, VCC, GND, and I2C pins.
You may have to install extra drivers for CH340. For those attend this course,
please find this driver inside the Software folder.
10
Figure 2-10 Comparison between Arduino UNO (right-hand side) and UNO compatible board used in
this module (left-hand side).
You can download Arduino Software from this link. For those attend this course, please
find this driver inside the Software folder.
11
Figure 2-12 Arduino IDE basic.
12
Figure 2-15 Definition of button bar.
13
Chapter 3 Components & Electrical Fundamental
3.1 INTRODUCTION
In this module, the Multifunction Mobile Ground Robot (MMGR) educational kit is used
for real-time implementation and it consists of three different modes: Bluetooth Ground
Robot (BGR), Line Following Robot (LFR) and Autonomous Mobile Ground Robot
(AMGR). This kit consists of several subsystems as shown in Figure 3-1 - Figure 3-4. There
are two types of configuration where the first one is with IR receiver connection and another
one is without using IR receiver connection (The difference on the digital pin number 3).
Figure 3-1 Functional block diagram for Bluetooth Ground Robot and Line Following Robot modes of MMGR
with IR Receiver connection.
14
Figure 3-2 Functional block diagram for Autonomous Mobile Ground Robot mode of MMGR without IR
Receiver connection.
15
Figure 3-3 Actual block diagram for Bluetooth Ground Robot and Line Following Robot modes of MMGR
with IR Receiver connection
16
Figure 3-4 Actual block diagram for Autonomous Mobile Ground Robot mode of MMGR without IR
Receiver connection.
17
3.2 COMPONENTS
This section describes the major components (hardware) of Multifunction Mobile Ground
Robot (MMGR).
Figure 3-5 Arduino Sensor Shield v5.0. For MMGR, we only use pins in red box.
18
Figure 3-6 Arduino Sensor Shield v5.0 Diagram
19
Ultrasonic sensors (also known as transceivers when they both send and receive, but more
generally called transducers) work on a principle similar to radar or sonar which evaluates
attributes of a target by interpreting the echoes from radio or sound waves respectively.
Ultrasonic sensors generate high frequency sound waves and evaluate the echo which is
received back by the sensor. Sensors calculate the time interval between sending the signal
and receiving the echo to determine the distance to an object.
This technology can be used for measuring wind speed and direction (anemometer),
tank or channel level, and speed through air or water. For measuring speed or direction a
device uses multiple detectors and calculates the speed from the relative distances to
particulates in the air or water. To measure tank or channel level, the sensor measures the
distance to the surface of the fluid. Further applications include: humidifiers, sonar, medical
ultra sonography, burglar alarms and non-destructive testing.
Systems typically use a transducer which generates sound waves in the ultrasonic
range, above 18,000 hertz, by turning electrical energy into sound, then upon receiving the
echo turn the sound waves into electrical energy which can be measured and displayed.
In this module, Ultrasonic ranging module HC SR04 is used which provides 2cm - 400cm
non-contact measurement function, the ranging accuracy can reach to 3mm. The
modules includes ultrasonic transmitters, receiver and control circuit. The basic principle of
work:
20
3.2.3 Servo
A servomotor is a rotary actuator that allows for precise control of angular position
(angle), velocity and acceleration. It consists of a suitable motor coupled to a sensor for
position feedback. It also requires a relatively sophisticated controller, often a dedicated
module designed specifically for use with servomotors.
Servomotors are not a different class of motor, on the basis of fundamental operating
principle, but uses servomechanism to achieve closed loop control with a generic open loop
motor. Servomotors are used in applications such as robotics, CNC machinery or automated
manufacturing.
In this module, SG90 9g Micro Servo is used which is tiny and lightweight with high
output power. Servo can rotate approximately 180 degrees (90 in each direction), and works
just like the standard kinds but smaller. You can use any servo code, hardware or library to
control these servos. Good for beginners who want to make stuff move without building a
motor controller with feedback & gear box, especially since it will fit in small places. It
comes with a 3 horns (arms) and hardware.
Specifications:
Weight: 9 g
Dimension: 22.2 x 11.8 x 31 mm approx.
Stall torque: 1.8 kgf·cm
Operating speed: 0.1 s/60 degree
Operating voltage: 4.8 V (~5V)
Dead band width: 10 µs
Temperature range: 0 ºC – 55 ºC
21
Figure 3-10 Principle of operation
Position "0" (1.5 ms pulse) is middle, "90" (~2ms pulse) is all the way to the left. Please refer
data sheet for more details!!!
Bluetooth is a wireless technology standard for exchanging data over short distances (using
short-wavelength UHF radio waves in the ISM band from 2.4 to 2.485 GHz) from fixed and
mobile devices and building personal area networks (PANs). Range is approximately 10
Meters (30 feet).
These modules are based on the Cambridge Silicon Radio BC417 2.4 GHz BlueTooth
Radio chip. This is a complex chip which uses an external 8 Mbit flash memory.
22
Figure 3-12 Cambridge Silicon Radio BC417 pinout on HC-05
These low-cost Cambridge Silicon Radio BC417 work well with other Microcomputers.
IMPORTANT Definitions:
HC-05 is a more capable module that can be set to be either Master or Slave
These small (3 cm long) modules run on 3.3V power with 3.3V signal levels, They
have no pins and usually solder to a larger board.
The module has two modes of operation, Command Mode where we can send AT
commands to it and Data Mode where it transmits and receives data to another
Bluetooth module.
"Breakout" Boards that make these easy to use are available and recommended. These
mount the sub-module like that shown on the right on a slightly larger board. NOTE:
Sellers often label them "HC-05" or "HC-06", but they have some other model number
on the reverse side. Most of these boards support operation at 5V power and interface
to 5V Arduino signal levels with some technique of level shifting.
HC-05 Pinout:
KEY or EN: If brought HIGH before power is applied, forces AT Command Setup
Mode. LED blinks slowly (2 seconds)
VCC: +5 Power
GND: System / Arduino Ground
TXD: Transmit Serial Data from HC-05 to Arduino Serial Receive. NOTE: 3.3V
HIGH level: OK for Arduino
RXD: Receive Serial Data from Arduino Serial Transmit
STATE: Tells if connected or not
23
3.2.5 Full-Bridge Motor Driver Dual L298N
The LN298 is a high voltage, high current, dual full-bridge motor driver designed to
accept standard TTL logic levels and drive inductive loads such as relays, solenoids, DC and
stepping motors.
L298N H-bridge IC can control the speed and direction of two DC motors, or control one
bipolar stepper motor with ease. The L298N H-bridge module can be used with motors that
have a voltage of between 5 and 35V DC.
The L298 is an integrated monolithic circuit in a 15-lead Multiwatt and PowerSO20
packages. It is a high voltage, high current dual full-bridge driver designed to accept standard
TTL logic levels and drive inductive loads such as relays, solenoids, DC and stepping motors.
Two enable inputs are provided to enable or disable the device independently of the input
signals. The emitters of the lower transistors of each bridge are connected together and the
corresponding external terminal can be used for the connection of an external sensing resistor.
An additional supply input is provided so that the logic works at a lower voltage.
Features:
Operating supply voltage of up to 46V
4.5-7VDC logic supply voltage
Total DC current of up to 4A
Low saturation voltage
Over-temperature protection
Logical ‘0’ input up to 1.5V (high-noise immunity)
24
Motor A (LEFT MOTOR) truth table:
25
This DC or direct current motor works on the principal, when a current carrying
conductor is placed in a magnetic field, it experiences a torque and has a tendency to move
This is known as motoring action. If the direction of current in the wire is reversed, the
direction of rotation also reverses. When magnetic field and electric field interact they
produce a mechanical force, and based on that the working principle of DC motor is
established.
The Compass Module is designed for low-field magnetic sensing with a digital interface and
perfect to give precise heading information. This compact sensor fits into small projects
such as UAVs and robot navigation systems. The sensor converts any magnetic field to a
differential voltage output on 3 axes. This voltage shift is the raw digital output value, which
can then be used to calculate headings or sense magnetic fields coming from different
directions.
26
Specification:
Power 3V-5V DC
Chipset HMC5883L
Communication via I2C protocol
o SDA-serial data
o SCL-serial clock
Measuring range: ± 1.3-8 Gauss
Dimensions 14.8 x 13.5 x 3.5mm
** 4 pins of compass module will be used: VCC, GND, SCL and SDA.
TCRT5000 sensor of infrared emission diode constantly launch infrared, the infrared ray is
emitted when the intensity of reflected back has not been reflected or but is not big enough,
the light activated triode has been in the off state, the output end of the module at this time for
the high level, indicating diode has been put out state; detected objects appear within the
scope of testing, infrared light is reflected back and strength is enough big, light activated
triode saturation, at this time the output of the module for the low level, instructs the diode
lights.
Specification:
Infrared sensors TCRT5000
Test reflection distance: 1mm to 25mm
Working voltage of 3.3V to 5V
Output form: digital switch output (0 and 1)
Small board PCB size: 3.2cm x 1.4cm
Voltage comparator LM393
27
Figure 3-18 Infrared sensor working operation
A small PCB is also included with the sensor that provides an indicator LED and also a 10K
pull up resistor. A pull-up resistor is a resistor connected between a signal conductor and a
positive power supply voltage to ensure that the signal will be a valid logic level if external
devices are disconnected or high-impedance is introduced.
28
Specification:
Operating voltage (VCC): 2.7V to 5.5V
Infrared Frequency: 38kHz HX1838 NEC Code
Reception Angle: ± 45 degrees
Reception Distance: up to 18m
Leg pitch: 2.54mm (0.1")
Infrared remote control is an electronic device that used to operate or transmit data wirelessly
from a distance using infrared wave to send data. Note that any infrared remote will work just
fine but the type that is use in this course is low-cost car mp3 SE-020401.
Specification:
Remote control distance: more than 8 meters
Launch tube infrared wavelength: 940Nm
Crystal: the oscillation frequency of 455 KHz
IR carrier frequency: 38KHz
Encoding: the encoding format of the NEC, upd6122 encoding scheme, the user code
00FF, key coding below picture
Size: 86 * 40 * 6mm
Frequency: 38K
Power supply: CR2025/160mAH
Button: free height is less than 3mm, the force 200-350g, the life of more than 200,000
29
3.2.11 Battery
An electric battery is a device consisting of one or more electrochemical cells with external
connections provided to power to autonomous mobile ground robot.
It need voltage minimum 6V to operate. In this module, two options are proposed as
shown in Figure 3-14 and 3-15: 1) using four units of AA Alkaline Battery 1.5V and 2) using
two units of Lithium battery 3.7V. Note: If you are using two units of lithium battery, a
jumper wire (white) is needed to connect negative terminal from second battery ground
to fourth battery ground.
Figure 3-21 Battery connection if using four units of AA Alkaline Battery 1.5V.
Figure 3-22 Battery connection if using two units of Lithium battery 3.7V. A jumper wire (white) is needed to
connect negative terminals from second battery to fourth battery.
30
3.3 ELECTRICAL FUNDAMENTALS
31
3.3.3 Pulse Width Modulation
Pulse Width Modulation, or PWM, is a technique for getting analog results with digital
means. Digital control is used to create a square wave, a signal switched between on and off.
This on-off pattern can simulate voltages in between full on (5 Volts) and off (0 Volts) by
changing the portion of the time the signal spends on versus the time that the signal spends
off. The duration of "on time" is called the pulse width. To get varying analog values, you
change, or modulate, that pulse width. If you repeat this on-off pattern fast enough with an
LED for example, the result is as if the signal is a steady voltage between 0 and 5v controlling
the brightness of the LED.
In the graphic below, the green lines represent a regular time period. This duration or
period is the inverse of the PWM frequency. In other words, with Arduino's PWM frequency
at about 500Hz, the green lines would measure 2 milliseconds each. A call to analogWrite() is
on a scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on), and
analogWrite(127) is a 50% duty cycle (on half the time) for example.
32
3.3.4 Serial Communication
In telecommunication and data transmission, serial communication is the process of sending
data one bit at a time, sequentially, over a communication channel or computer bus. This is in
contrast to parallel communication, where several bits are sent as a whole, on a link with
several parallel channels.
Serial communication is used for all long-haul communication and most computer
networks, where the cost of cable and synchronization difficulties makes parallel
communication impractical.
A serial bus consists of just two wires - one for sending data and another for receiving.
As such, serial devices should have two serial pins: the receiver, RX, and the transmitter, TX.
Serial communication on pins TX/RX uses TTL logic levels (5V or 3.3V depending
on the board). Don't connect these pins directly to an RS232 serial port; they operate at +/-
12V and can damage your Arduino board.
Serial is used for communication between the Arduino board and a computer or other
devices. All Arduino boards have at least one serial port (also known as a UART or USART):
Serial. It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via
USB. Thus, if you use these functions, you cannot also use pins 0 and 1 for digital input or
output.
You can use the Arduino environment's built-in serial monitor to communicate with an
Arduino board. Click the serial monitor button in the toolbar and select the same baud rate
used in the call to begin().
33
Chapter 4 Arduino Programming Language
4.1 INTRODUCTION
The Arduino language is based on C/C++. Arduino programs can be divided in three main
parts: structure, values (variables and constants), and functions. This link describes the details
about these three main parts.
4.2 STRUCTURE
4.2.1 Basic
In Arduino, we have two basic structures: 1) setup( ) and 2) loop( ). For each sketch, these
two basic structures are compulsory to be implemented.
The setup( ) function is called when a sketch starts. Use it to initialize variables, pin
modes, start using libraries, etc. The setup function will only run once, after each powerup or
reset of the Arduino board.
After creating a setup() function, which initializes and sets the initial values, the loop()
function does precisely what its name suggests, and loops consecutively, allowing your
program to change and respond. Use it to actively control the Arduino board.
34
4.2.2 Control Structure
4.2.2.1 if
if, which is used in conjunction with a comparison operator, tests whether a certain condition
has been reached, such as an input being above a certain number. The format for an if test is:
The program tests to see if someVariable is greater than 50. If it is, the program takes a
particular action. Put another way, if the statement in parentheses is true, the statements inside
the brackets are run. If not, the program skips over the code.
The brackets may be omitted after an if statement. If this is done, the next line (defined by the
semicolon) becomes the only conditional statement.
if (x > 120)
digitalWrite(LEDpin, HIGH);
if (x > 120){
digitalWrite(LEDpin1, HIGH);
digitalWrite(LEDpin2, HIGH);
} // all are correct
The statements being evaluated inside the parentheses require the use of one or more
operators
Comparison operator:
x == y (x is equal to y)
x != y (x is not equal to y)
x < y (x is less than y)
x > y (x is greater than y)
x <= y (x is less than or equal to y)
x >= y (x is greater than or equal to y)
Warning:
Beware of accidentally using the single equal sign (e.g. if (x = 10) ). The single equal sign is
the assignment operator, and sets x to 10 (puts the value 10 into the variable x). Instead use
35
the double equal sign (e.g. if (x == 10)), which is the comparison operator, and tests whether
x is equal to 10 or not. The latter statement is only true if x equals 10, but the former
statement will always be true.
if can also be part of a branching control structure using the if...else construction.
4.2.2.2 if….else
if/else allows greater control over the flow of code than the basic if statement, by allowing
multiple tests to be grouped together. For example, an analog input could be tested and one
action taken if the input was less than 500, and another action taken if the input was 500 or
greater. The code would look like this”
else can proceed another if test, so that multiple, mutually exclusive tests can be run at the
same time.
Each test will proceed to the next one until a true test is encountered. When a true test is
found, its associated block of code is run, and the program then skips to the line following the
entire if/else construction. If no test proves to be true, the default else block is executed, if one
is present, and sets the default behaviour.
Note that an else if block may be used with or without a terminating else block and vice versa.
An unlimited number of such else if branches is allowed.
36
if (pinFiveInput < 500)
{
// do Thing A
}
else if (pinFiveInput >= 1000)
{
// do Thing B
}
else
{
// do Thing C
}
Another way to express branching, mutually exclusive tests, is with the switch case statement.
4.2.2.3 for
The for statement is used to repeat a block of statements enclosed in curly braces. An
increment counter is usually used to increment and terminate the loop. The for statement is
useful for any repetitive operation, and is often used in combination with arrays to operate on
collections of data/pins.
The initialization happens first and exactly once. Each time through the loop, the condition is
tested; if it's true, the statement block, and the increment is executed, then the condition is
tested again. When the condition becomes false, the loop ends.
37
Tips:
The C for loop is much more flexible than for loops found in some other computer languages,
including BASIC. Any or all of the three header elements may be omitted, although the
semicolons are required. Also the statements for initialization, condition, and increment can
be any valid C statements with unrelated variables, and use any C datatypes including floats.
These types of unusual for statements may provide solutions to some rare programming
problems. For example, using a multiplication in the increment line will generate a
logarithmic progression:
Generates: 2,3,4,6,9,13,19,28,42,63,94
4.3 SYNTAX
38
4.5 COMPARISON OPERATORS
Examples
x = 2;
x += 4; // x now contains 6
x -= 3; // x now contains 3
x *= 10; // x now contains 30
x /= 2; // x now contains 15
4.7 #DEFINE
#define is a useful C component that allows the programmer to give a name to a constant
value before the program is compiled. Defined constants in arduino don't take up any program
memory space on the chip. The compiler will replace references to these constants with the
defined value at compile time.
This can have some unwanted side effects though, if for example, a constant name that
had been #defined is included in some other constant or variable name. In that case the text
would be replaced by the #defined number (or text).
In general, the const keyword is preferred for defining constants and should be used
instead of #define.
39
Syntax:
#define constantName value
Note that the # is necessary
Example:
#define ledPin 3
// The compiler will replace any mention of ledPin with the value 3 at compile time.
Tips:
There is no semicolon after the #define statement. If you include one, the compiler will throw
cryptic errors further down the page.
Similarly, including an equal sign after the #define statement will also generate a cryptic
compiler error further down the page.
4.8 #INCLUDE
#include is used to include outside libraries in your sketch. This gives the programmer access
to a large group of standard C libraries (groups of pre-made functions), and also libraries
written especially for Arduino.
Note that #include, similar to #define, has no semicolon terminator, and the compiler
will yield cryptic error messages if you add one.
4.9 VARIABLES
40
Table 4-1 Data Type
Data Type RAM Number Range
void keyword N/A N/A
boolean 1 byte 0 to 1 (True or False)
byte 1 byte 0 to 255
char 1 byte -128 to 127
unsigned char 1 byte 0 to 255
int 2 byte -32,768 to 32,767
unsigned int 2 byte 0 to 65,535
word 2 byte 0 to 65,535
long 4 byte -2,147,483,648 to 2,147,483,647
unsigned long 4 byte 0 to 4,294,967,295
float 4 byte -3.4028235E+38 to 3.4028235E+38
double 4 byte -3.4028235E+38 to 3.4028235E+38
string 1 byte + x Arrays of chars
array 1 byte + x Collection of variables
41
4.11 SERIAL COMMUNICATION
Serial.begin()
Sets the data rate in bits per second (baud) for serial data transmission. For communicating
with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200,
28800, 38400, 57600, or 115200. You can, however, specify other rates - for example, to
communicate over pins 0 and 1 with a component that requires a particular baud rate.
Serial.print()
Prints data to the serial port as human-readable ASCII text. This command can take many
forms. Numbers are printed using an ASCII character for each digit. Floats are similarly
printed as ASCII digits, defaulting to two decimal places. Bytes are sent as a single character.
Characters and strings are sent as is.
Serial.println()
Prints data to the serial port as human-readable ASCII text followed by a carriage return
character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n'). This command takes
the same forms as Serial.print().
Serial.available()
Get the number of bytes (characters) available for reading from the serial port. This is data
that's already arrived and stored in the serial receive buffer (which holds 64 bytes). available()
inherits from the Stream utility class.
Serial.read()
Reads incoming serial data. read() inherits from the Stream utility class. Stream is the base
class for character and binary based streams. It is not called directly, but invoked whenever
you use a function that relies on it. Stream defines the reading functions in Arduino.
42
Chapter 5 Getting Started (Windows)
5.1 GET AN ARDUINO UNO / UNO COMPATIBLE BOARD AND USB CABLE
43
Figure 5-3 Installation 1.
44
Figure 5-5 Installation 3.
45
5.3.2 UNO compatible board user (used in this module)
You may have to install extra drivers for CH340. For those attend this course, please find this
driver inside the Software folder. You only need to double click on the driver file and then
Windows will finish up the driver installation from there.
Figure 5-6 Windows 7: Click Control Panel > Hardware and Sound> Device Manager. For Windows 10: You
have to search Device Manager.
46
Figure 5-7 Check the port number (COM number) for USB-SERIAL CH340. In this case, its port number is
COM7. You have to memorise this number because you will use this number for serial communication later (e.g.
Upload code, serial monitor, graphical user interface (GUI), etc.)
47
Figure 5-8 Blink example.
Figure 5-9 Select your board (e.g. In our case is Arduino UNO).
48
5.8 SELECT YOUR SERIAL PORT
Select the serial device of the board from the Tools | Serial Port menu. This is likely to be
COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find
out, you can disconnect your board and re-open the menu; the entry that disappears should be
the Arduino or Genuino board. Reconnect the board and select that serial port.
A few seconds after the upload finishes, you should see the built-in LED that has been
connected to pin 13 on the UNO board start to blink. You should see the LED on Arduino
sensor shield start to blink as well as shown in Figure 5-9. If it does, congratulations! Means
your UNO board is in good condition.
49
Figure 5-12 Results after Done Uploading.
50
Chapter 6 Tutorial
6.1 TUTORIAL 1: LED BLINK
6.1.1 Introduction
This tutorial shows the simplest thing you can do with an Arduino to see physical output: it
blinks an LED. In this tutorial, we are using build in LED on the Arduino board. Then plug
your Arduino board into your computer, start the Arduino program, and enter the code. Most
Arduino boards already have an LED attached to pin 13 on the board itself. If you run the
code with no hardware attached, you should see that LED blinks.
6.1.2 Hardwares
Arduino Board
Arduino Sensor Shield
6.1.3 Diagram
51
6.1.4 Code
Please refer Tutorial_1_LEDBlink in Code subfolder.
Tips:
Recall:
52
3) In void loop (Main Algorithm: repetition): Turn ON led for one second and then turn
OFF for one second.
Turn ON Led
digitalWrite(led, HIGH);
53
6.2 TUTORIAL 2: RIGHT MOTOR
6.2.1 Introduction
In this tutorial, we will learn on how to control the direction and the speed of right motor.
6.2.2 Hardware
Arduino board
Motor driver L298N
DC brush motor
Battery
6.2.3 Diagram
The following table describes the connection between motor driver L298N (red board) and
UNO Board.
54
6.2.4 Code
Please refer the source code: Tutorial_2_RightMotor
Tips:
- Try to get the direction of Right Motor for forward motion (CW)
- Then, you can play with HIGH/LOW signal in order to change the direction of
motor rotation as described in the following truth table.
Precaution:
55
BATTERY CONNECTION IF USING TWO UNITS OF LITHIUM BATTERY 3.7V.
A jumper wire (white) is needed to connect negative terminals from second battery to fourth battery.
Please follow this connection; otherwise it will cause short circuit and burning the battery holder!!!
56
6.3 TUTORIAL 3: LEFT MOTOR
6.3.1 Introduction
In this tutorial, we will learn on how to control the direction and the speed of left motor.
6.3.2 Hardware
Arduino board
Motor driver L298N
DC brush motor
Battery
6.3.3 Diagram
The following table describes the connection between motor driver L298N (red board) and
UNO Board.
57
6.3.4 Code
Please refer source code: Tutorial_3_LeftMotor.
Tips:
- Try to get the direction of Left Motor for forward motion (CCW)
- Then, you can play with HIGH/LOW signal in order to change the direction of
motor rotation as described in the following truth table.
58
6.4 TUTORIAL 4: FORWARD
6.4.1 Introduction
In this tutorial, we will learn on how to control both motor at the same time and try to make a
forward motion control. Actually, this tutorial is a combination of Tutorial 2 and Tutorial 3.
In MMGR, two calling functions are used for forward motion:
- Forward();
o To get a forward motion of robot by manipulating the direction of motor
rotation. As mentioned before:
Right Motor: CW
Left Motor: CCW
- Go(nom_Lspeed,nom_Rspeed);
o To control the speed of both right and left motors
nom_Lspeed is for left motor speed and this is a PWM value which can
be between 0 and 255.
nom_Rspeed is for right motor speed and this is a PWM value which
can be between 0 and 255.
It is a good practice to declare the values of nom_Lspeed and
nom_Rspeed at the top of program as a Global variable.
6.4.2 Hardware
Arduino board
Motor driver L298N
DC brush motor
Battery
6.4.3 Diagram
The following table describes the connection between motor driver L298N (red board) and
UNO Board.
59
6.4.4 Code
Please refer source code: Tutorial_4_Forward
60
6.5 TUTORIAL 5: ROBOT MOTION
In this tutorial, we will learn on controlling two motor at the same time, with it, we will make
the movement of our robot (MMGR). Try change the type of movement by change the calling
function inside the void loop.
For each calling function, do not forget to put Go(nom_Lspeed,nom_Rspeed); to control the
speed of right and left motors.
6.5.1 Hardware
Arduino board
Motor driver L298N
DC brush motor
Battery
6.5.2 Diagram
Same as presented in Tutorial 4.
6.5.3 Code
Please refer source code: Tutorial_5_RobotMotion
61
6.6 TUTORIAL 6: AT COMMAND
6.6.1 Introduction
AT commands are instructions used to control a modem. AT is the abbreviation of ATtention.
Every command line starts with "AT" or "at". That's why modem commands are called AT
commands.
Note that the starting "AT" is the prefix that informs the modem about the start of a command
line. It is not part of the AT command name. For example, D is the actual AT command name
in ATD, and +CMGS is the actual AT command name in AT+CMGS.
AT command can be used to rename, get the address, change passkey, baud rate and many
more about your Bluetooth transceiver.
For this tutorial, we want to change the name of our Bluetooth module.
6.6.2 Hardware
Arduino board
Bluetooth transceiver HC-05
6.6.3 Diagram
62
6.6.4 Code
Please refer source code: Tutorial_6_ATCommand
6.6.5 Steps
Step1:
Upload the code onto your Uno, make sure your VCC of your Bluetooth module does not
connected.
Step2:
After uploaded, press the reset button on the Bluetooth module (do not releases the button)
and plug in the VCC of your Bluetooth module, the LED on the Bluetooth module should
blink with 2s of interval (Bluetooth module in AT mode), after done you can releases the reset
button.
Step3:
Open Serial monitor and select option to “Both NL & CR” and bout rate of 9600 at the
bottom of serial monitor.
Step4:
Now give some AT commands at the upper bar. For example type “AT” and send it should
response with “OK”, if it does its mean that you can communicate with it, if it does not,
recheck your connection and restart from Step1. To rename the Bluetooth module (base from
the data sheet) type “AT+NAME=” and type any name you want to give to your Bluetooth
module and send, to inquire device’s name type “AT+NAME?” and send. It should give you
its latest name.
63
6.7 TUTORIAL 7: BLUETOOTH
6.7.1 Introduction
For this tutorial, we will learn on using serial communication, pin RX is use in receiving any
data, for our case, we are using RX on the Arduino to read ASCII from our Android
smartphone via Bluetooth module. We will also learn on print or send data to computer using
TX via USB cable. The speed of the serial communication that we will use in this tutorial is
9600bits/s. What is ASCII?
ASCII abbreviated from American Standard Code for Information Interchange, is a
character encoding standard (the Internet Assigned Numbers Authority (IANA) prefers the
name US-ASCII). ASCII codes represent text in computers, telecommunications equipment,
and other devices. Most modern character-encoding schemes are based on ASCII, although
they support many additional characters.
As mentioned before, we need an Android smartphone for sending data to out robot
(MMGR) via Bluetooth module. Therefore, an Android App is needed which is Arduino
Bluetooth RC Controller. This app will be used to control your manual. Please note, for this
course we will learn on use Bluetooth RC Controller app (android only).
64
Installation:
1) You can download Arduino Bluetooth RC Controller from App store (Google Play) or
2) You can get it from the Software folder in your module and its name is Arduino
Bluetooth RC Car_v1.7_apkpure.com.apk. Please copy this .apk file into your
smartphone and install it.
65
6.7.2 Hardware
Arduino board
Bluetooth transceiver HC-05
6.7.3 Diagram
TX pin on Bluetooth module is connected to RX pin (0) on UNO board.
RX pin on Bluetooth module is connected to TX pin (1) on UNO board.
State pin on Bluetooth module is connected pin 2 on UNO board.
6.7.4 Code
Please refer source code: Tutorial_7_Bluetooth.
66
4. Click Connect to car
67
6. Select your Bluetooth ID (e.g. MMGR-04). Basically, Bluetooth module depends on
your MMGR labelled number. If your MMGR’s labelled number is 4. Thus, your
Bluetooth ID is MMGR-04 (default). Actually, you can change the Bluetooth ID by
using AT Command as presented in Tutorial 6. But, for this tutorial, just use the
default ID.
7. Then, Bluetooth pairing request will be opened for the first time connection with the
new device.
68
8. Enter the password: 1234
9. Now, you can play with your App. Try to press any button and see the response in
your serial monitor. For example, if you press the forward button on your App, then
you can see F character (Char) on your serial monitor. Don’t forget to refer your
ASCII table.
10. Actually you can check the list of Commands/characters sent to the robot by selecting
Setting in option menu. Then, you have to scroll down to see its list.
69
Congratulation!!! Now, you can develop your Bluetooth Ground Robot based on
Tutorial 1 - Tutorial 7. Please refer Section 7.1 for this project.
70
6.8 TUTORIAL 8: ANALOG IR
6.8.1 Introduction
For this tutorial, we will learn on using infrared sensor and read the value using analog input
pin. As we know that infrared sensor module can be both digital and analog, but in this course
we are using analog. We also might need to print the value in the serial monitor for each
infrared sensor. The speed of the serial communication that we will use in this tutorial is
9600bits/s.
Recall:
As mentioned before, analog IR sensor will provide analog signal interm of DC voltage such
as 1V or 2V or 3V up to 5V and this kind of signal is called as analog signal. However, in
computer system, all data must be described in digital. Therefore, we need an Analog to
Digital Converter (ADC) to transform analog signal to digital signal as shown in the
following figure. Arduino UNO board has six analog pin where there is an ADC for each pin.
The output of ADC is a digital signal and the value is between 0 and 1023. You can check this
value by using serial monitor.
6.8.2 Hardware
Arduino board
Infrared Sensor
6.8.3 Diagram
IR Left analog pin (AO) is connected to A0 pin on UNO board.
IR Middle analog pin (AO) is connected to A1 pin on UNO board.
IR Middle analog pin (AO) is connected to A2 pin on UNO board.
IR Right analog pin (AO) is connected to A3 pin on UNO board.
71
6.8.4 Code
Please refer source code: Tutorial_8_AnalogIR.
- Try to check the sensor reading using serial monitor when you place your sensors
on white background and black line.
Important steps:
For this project, we will use analog infrared sensor which will be attached to the bottom of the
robot to give information about robot position on the floor that has two different colours such
as white background and black line. These 4 sensors will be classified as left sensor, middle
left sensor, middle right sensor and right sensor, as shown in the following figure.
72
In this tutorial, we will check the sensor reading when it is placed on the white and black
colours by using serial monitor via Bluetooth interface (or USB serial communication). In
theory, the black surface will cause larger value of sensor reading (output of ADC) compared
to white surface.
1) Place your robot on the white surface and Turn ON it. Make sure your Bluetooth
module is Turn ON as well.
2) Then, go to Control Panel > Hardware and Sound and then select Add a Bluetooth
device
73
3) Then, you can see your target Bluetooth device’s ID. In this case, its ID is MMGR-07.
74
5) Select Enter the device’s pairing code.
6) Enter the default pairing code for the device which is 1234 and then click Next.
75
7) Now, your Bluetooth device is successfully added. Please go to Device Manager to
check your Bluetooth device’s COM number.
8) You can check the COM number of your device under Ports. In this case, its number is
COM45.
76
9) Now, open your Arduino software and then select the desired port number. In this
case, its number is COM 45. This number has been obtained from previous step.
77
11) Now, you can check the sensor reading for each sensor when it is placed on the white
surface. Their values are below 100.
78
13) Now, you can check the sensor reading for each sensor when it is placed on the black
line. Their values are above 100.
Congratulation!!! Now, you can develop your Line Following Robot based on
Tutorial 1 - Tutorial 8. Please refer Section 7.2 for this project.
79
6.9 TUTORIAL 9: ULTRASONIC
6.9.1 Introduction
This tutorial reads a HC-SR04 ultrasonic rangefinder and returns the distance to the closest
object in range. To do this, it sends a pulse to the sensor to initiate a reading, and then listens
for a pulse to return. The length of the returning pulse is proportional to the total time taken
for pulse to be transmitted and return and that total time taken is proportional to distance of
the object from the sensor divided by two.
6.9.2 Hardware
Arduino Board
Ultrasonic Sensor
6.9.3 Diagram
Trig pin on ultrasonic is connected to digital pin 9 on UNO.
Echo pin on ultrasonic is connected to digital pin 4 on UNO.
6.9.4 Code
Please refer Tutorial_9_Ultrasonic in Code subfolder.
Tips:
#define echoPin 4
#define trigPin 9
80
2) Declare Global variables for reading the pulse and for storing distance in cm
Recall:
Serial.begin(speed)
- Sets the data rate in bits per second (baud) for serial data transmission. For
communicating with the computer, use one of these rates: 9600, 14400, 19200,
28800, 38400, 57600, or 115200.
distance_cm = calculateDistance();
Serial.println(distance_cm);
81
FOR ADVANCED STUDENTS:
int calculateDistance(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pulseTime = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel
time in microseconds
return distance_x;
}
82
6.9.5 Experimental Result
1) Connect your UNO board with computer using USB cable number.
2) Select the serial device of the board from the Tools | Serial Port menu.
83
4) Select “Both NL & CR” and “9600 baud”
84
6.10 TUTORIAL 10: SERVO
6.10.1 Introduction
In this tutorial, we will learn to sweeps the shaft of a servo motor back and forth across 180
degrees. This example makes use of the Arduino servo library.
Servo Library
This library allows an Arduino board to control RC (hobby) servo motors. Servos have
integrated gears and a shaft that can be precisely controlled. Standard servos allow the shaft to
be positioned at various angles, usually between 0 and 180 degrees. Continuous rotation
servos allow the rotation of the shaft to be set to various speeds.
The Servo library supports up to 12 motors on most Arduino boards and 48 on the
Arduino Mega. On boards other than the Mega, use of the library disables analogWrite()
(PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the
Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to
23 motors will disable PWM on pins 11 and 12.
- attach()
o Attach the Servo variable to a pin
- write()
o Set the position of servo motor (0-180 deg)
- writeMicroseconds()
- read()
- attached()
- detach()
In MMGR, we provide two calling function to rotate servo motor from 0 degrees to 180
degrees and from 180 degrees to 0 degrees:
- Rotate_Servo_0_to_180();
- Rotate_Servo_180_to_0();
6.10.2 Hardware
Arduino Board
Servo Motor
6.10.3 Diagram
Servo signal pin (orange colour) is connected to pin 5 on UNO board.
85
6.10.4 Code
Please refer Tutorial_10_Servo in Code subfolder.
void Rotate_Servo_0_to_180(){
for (pos = 0; pos <= 180; pos++) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position. Increse this
value to get slow response.
}
void Rotate_Servo_180_to_0(){
for (pos = 180; pos >= 0; pos--) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position.
}
86
6.11 TUTORIAL 11: RADAR
6.11.1 Introduction
In this tutorial we are going to make a radar system to detect obstacles. Stable distance
measurement is between 2 cm and 400 cm as mentioned in SR-04 Ultrasonic sensor
datasheet. Ultrasonic sensor will measure the value of distance for each angle (0-180 degrees).
Therefore, this tutorial is a combination of previous tutorials in Section 6.9 and 6.10.
6.11.2 Hardware
Arduino Board
Ultrasonic Sensor
Servo Motor
6.11.3 Diagram
Trig – pin 9
Echo – pin 4
Servo signal – pin 5
6.11.4 Code
Please refer source code: Tutorial_11_Radar
Tips:
In MMGR, two calling functions are used in radar system:
1) To rotate servo motor from 0 degrees to 180 degrees and measure distance for each
angle.
Radar_0_to_180();
2) To rotate servo motor from 180 degrees to 0 degrees and measure distance for each
angle.
87
Radar_180_to_0();
88
6.12 TUTORIAL 12: ADVANCED RADAR
6.12.1 Introduction
As can be seen in previous tutorial, some noise occurred in distance measurement. Therefore,
a filter is needed to obtain more accurate measurement. In this tutorial, an average filter is
introduced where average distance measured will be obtained from 10 different readings as
described in the following equation:
∑10
𝑖=1 𝑑𝑖 𝑑1 + 𝑑2 + 𝑑3 + 𝑑4 + 𝑑5 + 𝑑6 + 𝑑7 + 𝑑8 + 𝑑9 + 𝑑10
𝑑̅ = =
10 10
In MMGR, two calling functions are used in advanced radar system which a combination of
normal radar system in previous tutorial and average filter:
1) To rotate servo motor from 0 degrees to 180 degrees and measure average distance for
each angle.
Advanced_Radar_0_to_180();
2) To rotate servo motor from 180 degrees to 0 degrees and measure average distance for
each angle.
Advanced_Radar_180_to_0();
6.12.2 Hardware
Arduino Board
Ultrasonic Sensor
Servo Motor
6.12.3 Diagram
Trig – 9
Echo – 4
Servo signal – 5
89
6.12.4 Code
Please refer source code: Tutorial_12_AdvancedRadar.
Tips:
In MMGR, two calling functions are used in radar system:
1) To rotate servo motor from 0 degrees to 180 degrees and measure distance for each
angle.
Advanced_Radar_0_to_180();
2) To rotate servo motor from 180 degrees to 0 degrees and measure distance for each
angle.
Advanced_Radar_180_to_0();
90
ii. Open GUI_radar Processing Source Code file.
iii. Once GUI_radar file is opened, change the COM number at line 29 (which COM your
USB is connected to computer).
iv. Now, click Run button to launch the GUI for radar system
91
v. Congratulation!!! Now your Radar GUI is opened. Now, monitor the measurement for
angle (degrees) and distance (cm).
92
6.13 TUTORIAL 13: COMPASS
6.13.1 Introduction
In this tutorial, we will learn how to use compass (or magnetometer) sensor to estimate the
value of heading (bearing) which is the angle in the local horizontal plane (clockwise)
from a true North direction in earth’s polar axes. The earth’s field is always pointing
toward magnetic north for horizontal direction. This direction can be used to determine
compass direction of the system.
The magnetic field components in the body frame (𝑚𝑥 , 𝑚𝑦 , 𝑚𝑧 ) which are measured
from compass sensor can be used to calculate heading. In this module, a compass library is
used to do this task and it consists of compass.h and compass.cpp. These two files are given in
compass.zip inside your Tutorial_13_Compass folder.
First, we need to add compass.zip into our library folder by selecting Add.ZIP Library.
93
Now, we already added the compass library!!!
Let’s continue talking about this library. The most important feature of this library is it can
estimate heading in degrees and can do auto calibration with specified procedures.
This library will only work for HMC5883L magnetometer/ compass sensor with I2C address
of 0x1E. It is configured for single measurement. This means when the
compass_scalled_reading() function is called, the HMC5883L is woken up and
measurement is taken and then put back in sleep mode. Moreover, the measurements are
averaged by 8 samples and is hardcoded.
The library requires #include <Wire.h> before #include “compass.h”. Moreover, it also
require to initialize I2C port by writing command “Wire.begin();” before calling any of the
given functions.
94
Functions
95
Calibration
The magnetic north calculation will be not correct until the measurements are not calibrated,
especially for the constant offset in the measurement. The biggest factor effecting this error is
the electronics around it (including on breakout board). So you cannot get rid of it and as long
as the hardware around HMC5883L is same, the error more or less will remain the same. It is
a good idea to re-calibrate the magnetometer every time the hardware is changed. The
calibration procedure is shown in given video in Video subfolder. Note: In our module, it is
in Tutorial_13_Compass folder (NOT Tutorial_7_Compass folder).
96
Then, comment (deactivate) compass_offset_calibration(3) calling function in void setup().
97
Finally, you can upload your code to MMGR and then test the result via serial monitor.
In this tutorial, a GUI based on Python is provided. You need to install all given software in
GUI subfolder. There are four software: python, pyserial, pywin and VPython.
After all four software have been installed, right click imutest (Python File) and then select
Edit with IDLE.
98
Then, two files will be opened.
99
Don’t forget to SAVE before you close this file.
Now, you have to double click imutest_1 Python file in order to run your GUI.
100
Congratulation, now you can play with your GUI as shown in the video.
One of the important feature of this GUI is you can find all data log inside GUI folder. For
example, Serial1492707517.8 in Text Document as shown in the following figure.
101
6.13.2 Hardware
Arduino board
Compass module
6.13.3 Diagram
SCL on compass module is connected to SCL pin on UNO board.
SDA on compass module is connected to SDA pin on UNO board.
6.13.4 Code
Please refer source code: Tutorial_13_Compass.
Congratulation!!! Now, you can develop your Autonomous Mobile Ground Robot
based on Tutorial 1 - Tutorial 13. Please refer Section 7.3 for this project.
102
6.14 TUTORIAL 14 (EXTRA): IR REMOTE
6.14.1 Introduction
In this tutorial, we are using infrared receiver sensor and infrared transmitter remote. We will
read each value from the remote. For this tutorial, we will learn on using infrared remote
library (#include <IRremote.h>), a library that help us to get the value of the remote. Note: IR
receiver IN is connected to pin 3 on UNO board. You can get this library (.zip) from your
code folder Tutorial_14_IRRemote.
6.14.2 Hardware
Arduino board
Infrared receiver sensor VS1838B
Infrared transmitter remote SE-020401
6.14.3 Diagram
Pin IN on IR receiver is connected to pin 3 on UNO board.
6.14.4 Code
Please refer source code: Tutorial_14_IRRemote and check the response using serial monitor.
Try to think how to get several modes by manipulating the results of this tutorial and how
to control a mobile ground robot by using data that have been transmitted from IR remote
103
Chapter 7 Project
7.1 BLUETOOTH GROUND ROBOT (MANUAL MODE)
7.1.1 Introduction
For this project, we will be using Bluetooth module and motor driver for motor. The aim of
this project is to control our ground robot using smartphone or computer via Bluetooth. To do
so, we need to read the value that Bluetooth module receive using serial communication (Tx
and Rx pin), the robot will do motion control from the value it receive, for example if the
value of ‘F’ is receive, the robot will move forward. The following figure describes the
overall system that will be implemented in this tutorial.
As can bee seen, in the above figure, we have to manipulate several subsystems that have
been described in previous chapter (Tutorial 1 – 7).
A special calling function is used in MMGR for Bluetooth Control mode which is
Manual_Bluetooth();. This calling function is added in void loop in order to activate the
desired mode. For those are interested to know more details about this function, you have to
understand if..else if basic control structure as describe below:
104
if (pinFiveInput < 500)
{
// do Thing A
}
else if (pinFiveInput >= 1000)
{
// do Thing B
}
else
{
// do Thing C
}
Normally, we will use this kind of control structure when we deal with more than two options.
7.1.2 Hardware
Arduino board
Bluetooth transceiver HC-05
Motor driver L298N
DC brush motor
Battery
105
7.1.3 Diagram
106
7.1.4 Code
Please refer code: ManualGroundRobot_Bluetooth in Project subfolder.
107
7.2 LINE FOLLOWING ROBOT
7.2.1 Introduction
For this project, we will be using analog infrared sensor which will be attached to the bottom
of the robot to give information about robot motion. These 4 sensors will be classified as left
sensor, middle left sensor, middle right sensor and right sensor, as shown in the following
figure.
The distance between 2 sensors depends on the width of line. The sensor should be placed in
such a way that maximum distance of two sensors is equal to the width of the line as shown in
figure below. We want to make sure at least 1 sensor can detect the line. (Please note, in our
module, the width of line is 19 mm)
7.2.2 Hardware
Arduino board
Infrared Sensor
Motor driver L298N
DC brush motor
Battery
108
7.2.3 Diagram
109
7.2.4 Code
Please refer code: LineFollowingRobot in Project subfolder.
In this project, we have to manipulate several subsystems that have been described in previous
chapter (Tutorial 1 – 8).
Based on experimental results in Tutorial 8, we found that the best threshold value for this
project is 100 in order to differentiate black and white colour in robot’s algorithm. Now, we
have to use this information to maintain the position of robot with respect to black line.
Let’s see how robot follow the line based on the response from sensors. In our
discussion, we define the threshold value of sensors is equivalent to 100. Therefore, in
LineFollowingRobot code, LimitBlackLine is defined as a global variable to represent this
threshold value.
In code, “a” is defined as a global variable to store the last location update (right or
left side).
Two main functions are used in MMGR code for line following mode:
110
1) Read_Analog_IR();
- Collect analog sensor reading as described in Tutorial 10. We will use analogRead
function to convert analog signal provided by IR to digital signal and its reading is
between 0 and 1023.
- Once a particular sensor sensed black line (If the value of sensor reading is larger
than or equal to LimitBlackLine (threshold value = 100), then it will send logic 1
to sensor_x variable (x can be 4, 3, 2, and 1).
2) linefollowing();
- Using sensor_x (x can be 4, 3, 2, and 1) value to control the robot motion by
manipulating the direction of motor’s rotation and its speed.
- Example of robot response based on condition of sensors (Black line on white
floor):
3) Output_IR();
- Used to printout sensor reading.
111
7.3 AUTONOMOUS MOBILE GROUND ROBOT
7.3.1 Introduction
For this project, we will be using ultrasonic sensor, servo motor, compass and motor driver
for motor. The aim of this project is that it can move on its own and will avoid obstacle in its
front and go back on its direction. To do so, first compass need to take around 10 reading to
know its direction before moving. Ultrasonic sensor is use to get the distance in its front and if
the distance is more than 20cm, it will move forward using compass as guidance and if the
distance is less than 20cm, the robot do advance radar, to get the area that has less obstacle
and avoid the obstacle using compass as its guidance. In general, this tutorial is a combination
of several tutorials that have been covered in previous chapter especially:
- Tutorial 5: Robot Motion
- Tutorial 7: Bluetooth
- Tutorial 9: Ultrasonic
- Tutorial 10: Servo
- Tutorial 11: Radar
- Tutorial 12: Advanced Radar
- Tutorial 13: Compass
Note:
Autonomous mobile ground robot is a robot that capable to move around to non-fixed
surrounding (unknown environment), without being controlled by the user. Without human
control the robot will move to the designated unknown area with unknown obstacles position,
according to the navigation and control algorithm and that has been programmed by the user.
7.3.2 Hardware
Arduino board
Ultrasonic sensor
Servo motor
Compass GY-271
Motor driver L298N
DC brush motor
Battery
7.3.3 Diagram
In this project, ENB on L298N motor driver must be connected to pin 3 on UNO board.
We don’t use IR remote in this project.
112
7.3.4 Code
Please refer code: AutonomousGroundRobot in Project subfolder.
113