Arduino
Arduino
Arduino
Interrupt 1
Interrupt 0
In-circuit Serial
(SPI)MISO
(SPI)MOSI
(I2C)SCL
(I2C)SDA
(SPI)SCK
(SPI)SS
Programmer for Serial Out
USB interface (TX) Serial In
(RX)
Reset Button
In-circuit Serial
USB to
Programmer for
Computer
Atmega328
MISO VCC
SCK MOSI
/RESET GND
7-12V DC
Input
(I2C)SDA
(I2C)SCL
Reset
3.3V Power Ground
5V Power Voltage
In Analog In
The Arduino Uno pinout is printed in the silkscreen in the top section. While
this pinout is a good start, it is not a comprehensive guide. At first, you mainly use
the pins in the female headers at the edge of the board (top and bottom in the
photo), as well as the USB, and maybe the power
Tx and Rx are serial UART pins used for RS-232 and USB communications
I2C is another serial communications method that uses a bidirectional data line
(SDA) and a clock line (SCL)
SPI is another serial communications method that uses one line for the master to
transmit (MOSI—Master Out Slave In), another for the master to receive (MISO),
and a third as a clock (SCK)
A/D, the Analog to Digital input, converts an analog voltage into a digital
representation
PWM (Pulse Width Modulator) is used to create a square wave with a specific
duty cycle (high time vs low time)
ICSP is the In Circuit Serial Programming—another way to program the processor
Vcc is the voltage supplied to the processor (+5VDC regulated from a higher input
voltage)
3.3VDC is a regulated voltage (from the higher input voltage) for peripherals
requiring that voltage—50 mA maximum
Fig. 1.2 Arduino Uno R3 pinout diagram
IOREF provides a voltage reference so shields can select the proper power source
AREF is a reference INPUT voltage used by the A/Ds
GND is the ground reference
RESET resets the processor (and some peripherals)
2. DFRobot RoMeo BLE
The DFRobot Romeo BLE All-in-one Microcontroller (ATMega 328) is an
all-in-one Arduino-compatible microcontroller specifically designed for robotic
applications. It benefits from the Arduino open-source platform; it is supported by
thousands of open-source codes, and can easily be expanded with your Arduino-
compatible shields.
This robot controller uses an Atmel ATmega328p as the main microcontroller.
It comes preprogrammed with an Arduino bootloader for compatibility with the
user-friendly Arduino Uno platform.
A secondary Texas Instruments CC2540 microcontroller handles the BLE
Bluetooth Low Energy communication services. It comes preprogrammed with a
firmware that supports transparent serial over Bluetooth and an AT command
interpreter. Both microcontrollers are full programmable.
The Romeo robot controller contains a built in L298 dual channel motor driver
chip. This motor driver can be used to drive two 5–23 V DC motors at up to 2
amps. Screw terminals are provided for connecting two motors and an external
motor power supply.
The Romeo BLE microcontroller board also has a large number of pin headers
to simplify connections to your robot project. A full set of 3-pin analog and digital
GPIO headers provide access to signal, voltage, and ground lines at each connec-
tion to simplify wiring arrangements. The digital GPIO headers can also be used
to drive servos and a screw terminal can provide an external servo power
supply. A full set of Arduino Uno compatible headers allow you to choose from a
large number of Arduino-compatible shields for expansion. A triplet of I2C
connectors is also provided.
Additional features include five optional user push buttons, a reset button, and a
number of LED status indicators to assist with diagnostics. The optional user
buttons are conveniently wired to a single analog input. They can be enabled or
disabled via a slider switch (Fig. 1.3).
2.1 Overview
The code you learn to write for your Arduino is very similar to the code you write
in any other computer language. This implies that all the basic concepts remain the
same and it is simply a matter of learning a new dialect. In the case of Arduino,
the language is based on the C/C++ and can even be extended through C++
libraries. The IDE enables you to write a computer program, which is a set of step-
by-step instructions that you then upload to the Arduino. Your Arduino will then
carry out those instructions and interact with whatever you have connected to it.
The Arduino includes many basic embedded functions, such as the functions for
reading and writing to digital and analog input and output pins, interrupt functions,
mathe- matical functions, and serial communication functions. Arduino functions
are a convenient way to write code such as those for device drivers or commonly
used utility functions. Furthermore, Arduino also consists of many built-in-
examples. You just need to click on the toolbar menu:! File Examples to access
them. These simple programs demonstrate all basic the Arduino commands. They
span from a Sketch Bare Minimum, Digital, and Analog IO, to the use of Sensors
and Displays.
For more information on the Arduino language, see the Language Reference
section of the Arduino web site, http://arduino.cc/en/Reference/HomePage. All
Arduino instructions are online.
2.2 Structure
The basic function of the Arduino programming language is fairly simple and runs
in at least two parts. These two required parts, or functions, enclose blocks of
statements.
setup(): A function present in every Arduino sketch. Run once before the
loop() function. The setup() function should follow the declaration of any
variables at the very beginning of the program. It is the first function to run in the
program, is run only once, and is used to set pinMode or initialize serial
communication.
loop(): A function present in every single Arduino sketch. This code happens
over and over again—reading inputs, triggering outputs, etc. The loop() is where
(almost) everything happens and where the bulk of the work is performed.
Digital I/O will allow us to read the state of an input pin as well as produce a
logical high or low at an output pin. If every potential external connection between
a microcontroller and the outside world had a dedicated wire, the pin count for
controller packages would be high. The ATmega 328P in the Romeo board has
four 8-bit ports plus connections for power, ground and the like, yet it only has 28
physical pins. In general, each bit of a port can be programmed independently;
some for input, some for output, or all of them for the same purpose.
1. pinMode(pin, mode)
Before we use a port, we need to inform the controller about how it should
operate. In the Arduino system, this is usually done via a call to the library
function pinMode(). Here is a description of the function from online
references:
It should be noted that the pin could be a number or variable with a value
ranging from 0 to 13 or A0 to A5 (when using the Analog Input pins for digital
I/O) corresponding to the pin number printed on the interface board. Furthermore,
Digital pins default as input, so you really only need to set them to OUTPUT in
pinMode().
2. digitalWrite(pin, value)
Once a pin is established as an OUTPUT, it is then possible to turn that pin on or
off using the digitalWrite() function. Its syntax is as follows:
3. digitalRead(pin)
With a digital pin configured as an INPUT, we can read the state of that pin using
the digitalRead() function. Its syntax is as follows:
The pin can be specified as either a variable or constant (0–13) and the result is
either HIGH or LOW.
1. analogReference(type)
The Arduino interface board, however, has a convenient pin called AREF located near
digital pin 13 along with a function called analogReference() to provide the Arduino ’s
ADC a reference voltage other than +5 V. This function will effectively increase
the resolution available to analog inputs that operate at some other range of lower
voltages below +5 V. The syntax for this function is as follows.
1. shiftOut(dataPin,clockPin,bitOrder,value)
Shifts out a byte of data one bit at a time. Starts from either the most (i.e., the
leftmost) or least (rightmost) significant bit. Each bit is written in turn to a data
pin, after which a clock pin is pulsed (taken high, then low) to indicate that the bit
is available. The syntax is as follows.
This is known as synchronous serial protocol and is a common way that
microcontrollers communicate with sensors, and with other microcontrollers. The
two devices always stay synchronized, and communicate at close to maximum
speeds, since they both share the same clock line. Often referred to as SPI (syn-
chronous protocol interface) in hardware documentation.
2. pulseIn(pin,value,timeout)
Reads a pulse (either HIGH or LOW) on a pin. For example, if the value is HIGH,
pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go
LOW and stops timing. Returns the length of the pulse in microseconds. Gives up
and returns 0 if no pulse starts within a specified time out. The timing of this
function has been determined empirically and will probably show errors for longer
pulses. Works on pulses from 10 ls to 3 min in length. The syntax is as follows.
1. delay(ms)
Pauses the program for the amount of time (in milliseconds) specified as the
parameter. The syntax for the function is as follows.
Time is specified in milliseconds, where a delay of 1000 ms equals 1 s, 2000
ms equals 2 s, and so on. This value can be expressed as a constant or variable in
the unsigned long data type.
The use of delay() in a sketch has significant drawbacks. No other reading of
sensors, mathematical calculations, or pin manipulations can function during the
delay function, so in effect, it brings most other activities to a halt.
2. delayMicroseconds(us)
Rather than a long delay, the delayMicroseconds() function is used to delay for a
much shorter time. The syntax is as follows:
By calling the function, it returns a value in milliseconds that can be used like
any other variable as part of a conditional test, to perform arithmetic operations, or
to be assigned to other variables. Because this function returns a value in an
unsigned long data type, it will overflow, or reset to 0, in about 50 days. It can
also result in undesired problems if an expression is performed on it using other
data types like integers.
4. micros()
Where the millis() function returns the current operating time in milliseconds, the
micros() function does the same, but in microseconds. This could be used in
exactly the same manner as millis(), just on a much smaller scale, effectively
returning the value 1000 for every 1 that millis() would return.
1. Serial.begin(speed)
Opens the serial port and sets the baud rate for serial data transmission. The
typical baud rate for communicating with the computer is 9600, although other
speeds are also supported, i.e., 300, 600, 1200, 2400, 4800, 9600, 14,400,
19,200, 28,800,
38,400, 57,600, or 115,200.
It should be noted that the digital pins 0 (RX) and 1 (TX) cannot be used at the
same time when using serial communication.
2. Serial.available()
Receives the number of bytes (characters) available for reading from the serial
port. This is data that has already arrived and been stored in the serial receive
buffer.
3. Serial.printIn(val,format)
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’).
The println() function is a little easier to use and helps to clean up the output
that we receive from the Serial Monitor. You will often see both the print() and
println() functions used in conjunction to format the output, making the text
easier to read.
2.8 Interrupt Functions
1. attachInterrupt(digitalPinToInterrupt(pin),ISR,mode)
The attachInterrupt() function enables hardware interrupts and links a hardware pin
to an ISR to be called when the interrupt is triggered. This function also specifies
the type of state change that will trigger the interrupt. Its syntax is as follows:
5V 5V
0V 0V
LOW CHANGE
5V 5V
0V 0V
RISING FALLING
Interrupts allow certain important tasks to run in the background and are
enabled by default. Some functions will not work while interrupts are disabled,
and incoming communication may be ignored. Interrupts can slightly disrupt the
timing of a code, however, and may be disabled for particularly critical sections
of code.
4. noInterrupts()
To deactivate all interrupts, we can use the function noInterrupts(). The syntax is
as follows.
2.9 Math Functions
The Arduino language supports many math functions which make it possible to
perform sophisticated data processing in a data logger sketch that would otherwise
have to be performed offline in some other software application.
1. min(x,y)
Calculates the minimum of two numbers
2. max(x,y)
Calculates the maximum of two numbers3.
3.abs(x)
Computes the absolute value of a number
Because of the way the abs() function is implemented, avoid using other func-
tions inside the brackets, it may lead to incorrect results.
3. Trigonometric functions
The trigonometric functions include sin(rad), cos(rad), and tan(rad). All trigono-
metric functions accept as input and return as output angles in radians, not
degrees:radians ¼degrees p=180 and vice versa to convert radians back to
degrees.
4. pow(base,exponent)
Calculates the value of a number raised to a power. pow() can be used to raise a
number to a fractional power. This is useful for generating exponential mapping of
values or curves.
5. sqrt(x)
Calculates the square root of a number.
6. constrain(x,a,b)
Constrains a number to be within a range.
7. map(value,fromLow,fromHigh,toLow,toHigh)
Remaps a number from one range to another. That is, a value of fromLow would be
mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-
between, etc.
8. random(min,max)
The random() function returns a semi-random number up to the parameters spec-
ified. If no parameters are specified, it will return a value in the signed long data
type, with a range of −2,147,483,648–2,147,483,647. Its syntax is as follows:
3.1 ltrasonic Sensors
3.1.1 Introduction
When creating an autonomous target tracking robot, one of the most crucial
aspects is obstacle detection and avoidance. Often, a target may move in a
scenario where there is an object between the target and robot. A sensor must be
able to detect the object, with adequate range to allow the robot to respond and
move accordingly. Ideally, the sensor must be small, low in cost, and easy to
manufacture and must be usable on a large scale. A readily available sensor that
fits all of these requirements is the ultrasonic sensor.
The ultrasonic sensor uses sonar to determine the distance from an object,
similar to bats and dolphins. The sensor is a non-contact distance measurement
equipment that uses a timing variable t, measured from the transmission of some
kind of a pilot signal till a reflected signal is received from the object (Fig. 3.19).
The distance L to the object can be calculated as follows:
vt cos h
L¼ 2 ð3:3Þ
where, v is the speed of ultrasonic waves in the media (i.e., 340 m/s), h is the
reflection angle. If the transmitter and the receiver are close to each other, then
cos h ≈ 1.
Fig. 3.19 The principle of
ultrasonic sensor Object
Transmitter
θ
Receiver
L
For example, if the object is L = 10 cm away from the sensor, and the speed of
sound is 340 m/s or 0.034 cm/µs, the sound wave will need to travel about 294 µs.
However, what you will get from the receiver will be double that number because
the sound wave needs to travel forward and bounce backward. Therefore, in order
to obtain the distance in cm we need to multiply the received travel time value
from the receiver by 0.034 cm/µs and divide it by 2.
3.1.2 HC-SR04
3.1.3 Demonstration
1. Components
• DFRobot UNO R3 board and USB cable × 1.
• HC-SR04 (ultrasonic distance sensor) × 1.
• Jumper wires × n.
10us TTL
Trigger Input
To module
Output proportional
Echo Pulse to range
Output To User
Timing Circuit
2. Hardware Setting
The ultrasonic sensor HC-SR04 has four pins: VCC, TRIG, ECHO, and GND.
The VCC should be connected to 5 V and the GND to a common ground with
your Arduino. TRIG is used for emitting the transmitted signal. The output pin of
the Ultrasonic sensor should be plugged into a defined pin on the DFRobot UNO
R3 board. The ECHO pin is what is used for detecting the response from the
ultrasonic wave; this two should be plugged into a separate defined pin on the
DFRobot UNO R3 board (Fig. 3.21).
Tutorials
Adafruit Industries, Beginning electronics, sensors, and other Arduino tutorials (www.adafruit.
com/tutorials)
Arduino, Official Arduino tutorial website (http://arduino.cc/en/Tutorial/HomePage)
Tutorialspoint, Arduino Tutorial
(https://www.tutorialspoint.com/arduino/index.htm)
Jeremy Blum, Video tutorials from Jeremy Blum (http://jeremyblum.com/category/arduino-
tutorials)
SparkFun Electronics, Embedded electronics, surface mount soldering, projects, and other
tutorials (www.sparkfun.com/tutorials)
Spooky Projects, Class notes and tutorials from Tod E. Kurt (http://todbot.com/blog/
spookyarduino)
Tronixstuff, An ever expanding series of Arduino tutorials from John Boxall (http://tronixstuff.
wordpress.com/tutorials)
Wiring, Tutorials for the Wiring platform, similar to and mostly compatible with Arduino (http://
wiring.org.co/learning/basics)