Arduino Compatible Robot Kit Activity Manual: (C) Innovative Experiment Co., Ltd. WWW - Inex.co - TH

Download as pdf or txt
Download as pdf or txt
You are on page 1of 204

POP-BOT XT : The Arduino Compatible Mobile Robot kit 1

Arduino compatible robot kit


activity manual

(c) Innovative Experiment Co. ,Ltd.


www.inex.co.th
www.inexglobal.com
2POP-BOT XT : The Arduino Compatible Mobile Robot kit

Credits
POP-XT ; the robot controller board are trademarks of Innovative Experiment Co., Ltd.

POP-BOT XT, POP-BOT XT logo, INEX, and INEX logo are trademarks of Innovative Experiment
Co., Ltd.

AVR, Atmel, Atmel logo, AVR Studio are registered trademarks of Atmel Corporation.

WinAVR is trademark of SourceForge, Inc.

AVR-GCC is copyright of Free Software Foundation, Inc.

Arduino and Arduino Leonardo is an open source project supported by many. The Team
is composed of Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, and David
Mellis. Nicholas Zambetti has contributed since the beginning. Yaniv Steiner and Giorgio
Olivero have been supporting the project and are working at using it with the Instant
Soup platform. The Arduino platform used to include the avr-gcc tool chain, uisp, and
the Procyon AVR-LIB by Pascal Stang. The Arduino language syntax is based on Wiring
by Hernando Barragan. The Arduino environment is based on Processing by Ben Fry and
Casey Reas. Thanks to all the people who are supporting arduino.

I2C is a registered trademark of NXP Semiconductors.

Microsoft, Windows are registered trademarks of the Microsoft Corporation.

Windows 2K, Windows XP, Windows Vista and Windows7 are registered trademarks of
the Microsoft Corporation.

Macintosh, MAC OSX are registered trademarks of the Apple computer.

All product and service names mentioned herein are the trademarks of their respective
owners.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 3

Contents
1 : POP-BOT XT robot kit introduction and part list...........................................................................5

2 : Building the POP-BOT XT mobile robot.......................................................................................17

3 : Arduino 1.0 installation.............................................................................................................25

4 : Arduino programming.............................................................................................................55

5 : POP-BOT XT program development by Arduino 1.0................................................................87

6 : POP-BOT XT controller board hardware experiment......................................................93

7 : POP-BOT XT library file...........................................................................................................109

8 : POP-BOT XT movement control ...............................................................................................139

9 : POP-BOT XT object avoidance by contact.........................................................................153

10 : POP-BOT XT line tracking mission.............................................................................................161

11 : POP-BOT XT touchless object avoiding.............................................................................183

12 : POP-BOT XT with Servo motor...........................................................................................191


4POP-BOT XT : The Arduino Compatible Mobile Robot kit
POP-BOT XT : The Arduino Compatible Mobile Robot kit 5

Chapter 1
POP-BOT XT robot kit
introduction and part list
POP-BOT XT is an Arduino compatible, mobile robotic platform. It comes complete
with wheels, motors, sensors, software, documentation, etc. The POP-BOT XT controller
board is preloaded with the Arduino Leonardo bootloader. The Arduino 1.0 or higher
software is recommended.

For students and teachers; this kit comes with a comprehensive set of activities
and introducing sensors and microcontrollers using the well-popular Arduino platform. No
soldering is required so the kit is perfectly safe for the classroom. The POP-BOT XT robot kit
comes with 2 versions :

1 . POP-BOT X T Lite kit. It includes the POP-XT controller board that uses the
ATmega32U4 microcontroller and on-board color graphic LCD. It also includes simple sensors
(touch sensors and infrared reflector sensors), DC motor gearboxes and many mechanical
parts that allow you to make an autonomous robot suitable for learning of the C/C++
programming language. This version is most affordable for beginners in robotics.

2. POP-BOT XT Standard kit . It also includes all components that are in the Lite kit
with additional sensors and other extra part such as the Infrared ranger, 2 extra pieces of
the Infrared reflector sensor (total are 4 sets), a standard servo motor and extra quantities
of the mechanical part. With the standard kit version, it allows users to learn more about
robotics in education as well as competition.

1.1 Part list


1. POP-XT ; the Arduino Leonardo compatible robot controller board with the color
graphic LCD includes 4-AA battery holder

2. LED output board with JST cable (2 sets)

3. Switch/Touch sensor with JST cable (2 sets)

4. Infrared reflector board with JST cable (2 sets)*

5. GP2D120 Infrared distance sensor with JST cable**

6. 48:1 ratio 4.5 to 6Vdc motor gearbox with IDC cable (2 sets)

7. Standard servo motor (Operating voltage is 4.8 to 7.2Vdc)**

8. Circle wheel and Threaded rubber wheel set with 2mm. tapped-screw. (2 sets)
6POP-BOT XT : The Arduino Compatible Mobile Robot kit

9. 80 x 60 cm. and 80 x 80 cm. Plastic Grid plate set (2 sets)


10. Circle base with idle ball wheels
11. Plastic joiner and Strip joiner set ***
12. Right-angled metal shaft set (4 pieces of each 1x 2, 2 x 2 and 2 x 5 holes)
13. Nuts and Screws set
14. Line tracking demo paper sheet
15. The standard USB-miniB cable for downloading and communication
16. CD-ROM contains software tools, source code and documentation
* Increase to 4 sets for Infrared reflector sensor for the Standard kit version
** Only available in the Standard kit version
*** There is 30 pieces of 3-type mix colored plastic joiner and 4 pieces of each 3/5/
12 holes of Strip joiner for Lite kit and 6 0 pieces of 3-type mix colored plastic joiner for
Standard kit

1.2 Microcontroller components information


1.2.1 The POP-XT controller board
POP-XT is a controller board using the Atmel AVR microcontroller ATmega32U4
(www.atmel.com). It is connected to the USB port directly for communication and
download the running code. It is easy to use and very convenient . POP-XT is a hardware
that is Arduino Leonardo compatible (www.arduino.cc). The board can be used with
Arduino1.0 development software. The POP-XT controller board is a complete, low-cost
development platform designed for those interested in learning and using Arduino in robotic
applications. Its compact size, convenient features, and low price make it an ideal tool
for the student and educator. Figure 1-1 shows the layout of POP-XT board and complete
schematic diagram of its is shown in the figure 1-2.

The summarized technical feature of the POP-XT board is as follows :

The main microcontroller is 8-bit microcontroller from ATmel; ATmega32U4. It


includes 10-bit A/D converter with 12-channel, 32KB of flash program memory, 1KB of
EEPROM, 2.5KB of RAM and 16MHz clock frequency.

25-I/O port and assign to 12 of 3-pin JST connectors for interfacing with sensors
and peripherals

Screw terminal block for battery connections. It supports +4.8 to +12Vdc and has
an on-board power switch.

+5Vdc switching regulator power supply circuit. Its regulates the supply voltage
for microcontroller devices and all sensor ports.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 7

Figure 1-1 The layout of POP-XT controller board

128x160 pixels color graphic LCD stack board. includes KNOB, OK and RESET
button. This display board onlu supports line-art graphic, vector graphic, color background
and text (no support the image file).

8-Universal port support Analog input functions and Digital input/output function;
A0 to A7 (18 to 23, 4 and 6 digital pin)

I2C bus port; SDA (2) and SCL (3)

UART port; RxD (0) and TxD (1)

2-ch. DC motor driver with indicators. Supports motor voltage of 2.5 to 13.5Vdc.

3-Servo motor output; connect with the digital port 30 (SV1), 12 (SV2) and 13 (SV3).

Piezo speaker connections. It is connected with digital port 11.

LED power and Low battery indicator

Direct USB port connection for communication and upload the running code

ISP pad for upgrading and firmware recovery by using the external In-System
Programming (AVR-ISP mark II from Atmel is recommended)
8POP-BOT XT : The Arduino Compatible Mobile Robot kit

PF1 PF5 PF7 +Vm SWITCH


A4 22 A2 20 A0 18 ON
+5V

K3
BATT
4.8-7.2V

3 +
PF0 PF4 PF6 L1
D1 +5V
A5 23 A3 21 A1 19 10 H
MBRS340
1 IC3 2
KIA278R05 1 2
C6 C10 5,6,7,8 C13
100F 470 F C11 IC4 220 F
4 3
10V 16V 470 F NCP1450 10V
16V 4 5 - 5.0
Q3 4 C12
+5V FDS6680A 1,2,3 0.1F
C5
0.1F G
xx Arduino Leonardo pin name
+5V
C7
C4 0.1F R4
4k7
Pxx Atmel pin name GND
GND
Port assignment is
AREF

+5V 0.1F
AVcc

K1 compatible with
GND

GND

RST
PF0
PF1
PF4
PF5
PF6
PF7

Vcc

mini B-USB +USB LED1


BLUE + Arduino Leonardo
USB port PE6 44 43 42 41 40 39 38 37 36 35 34 PE2 17
1 33 31

Ext.
R1 R2

SPI
VUSB UVcc 32 PC7 15
27 27 2
D- D- PC6 16 +
3 31
D+ D+ 30
PB6 14 7
4
ID UGnd IC1 29
PB5 3 GND
5
GND UCap PB4 2 REF
6 ATMega32U4 28 8 +5V +5V 0 23
VBus 27
PD7
PB0
7 (TQFP44) PD6 1 22
C1 17 8 26 R5 R6
PB1 9 PD4 4 21
1F 15 25 Q1 4k7 Q2 4k7 30 20
16
PB2 10 24 AVcc
KRC102 KRC102 12 19
14
PB3 11 23 GND
12 13 14 15 16 17 18 19 20 21 22 6 18
Vcc

XTAL2
XTAL1
PB7

PD0
PD1
PD2
PD3
PD5
RST

GND

C8

10
11

13
31
+5V

8
9

5
0.1 F C9
0.1F

PB4

PE2
C2
0.01 F
R3

A8
4k7
ISP +Vm +Vm

PWMB
PWMA
+Vm

+Vm
+Vm
AIN2
AIN1

BIN1
BIN2
GND
STB
Vcc

SW2
RESET RST CR1 24 23 22 21 20 19 18 17 16 15 14 13
16MHz
IC2
+5V TB6612FNG +Vm
11
SP1 1 2 3 4 5 6 7 8 9 10 11 12
PIEZO GND
PG
PG

PG
PG
A1
A1

A2
A2
B2
B2

B1
B1

Speaker +Vm SV3


13
C3
10F PC6 PE6
R7 R8
16V ADIR 5 1k 1k 7 BDIR GND
3 SCL 0 RXD 6 A7
+Vm SV2
PD0 PD2 PD7 APWM 9 10 BPWM
12
PB5 PB6
-+ -+
GND
+Vm SV1
A B 30

2 SDA 1 TXD 4 A6
DC. MOTOR
PD1 PD3 PD4
OUTPUT

+5V +3.3V

IC5
GLCD LM1117-3.3V
128x160 pixel C14
C16
C15 10F
10F 0.1F 16V
21-character 16V
16-line
R11
4.7k
17 PB0
R12
4.7k
R13
4.7k
15 PB1
R14
MISO

LEDK
LEDA
/RST
GND

GND

GND

4.7k +5V
CLK

D/C
N/C

N/C
Vcc
Vcc
CS

R15
4.7k R11
1 2 3 4 5 6 7 8 9 10 11 12 13 14
16 PB2 1k C18
R16 8 PB4 0.1F
4.7k +3.3V R9 VR1
R17 SW5 KNOB
4.7
4.7k OK R11
31 PE2 1k
R18 +3.3V
4.7k R10
4.7k
+3.3V RST
C17 D1 SW3
0.1F 1N4148 RESET

Figure 1-2 The completely schematic diagram of POP-XT controller board


POP-BOT XT : The Arduino Compatible Mobile Robot kit 9

1.3.1 DC motor gearbox


This robot kit provides 48:1 ratio DC motor gearbox; model BO-2 with IDC connector
cable. Features include :

Operating voltage is +3 to +9Vdc

Current consumption 130mA @ +6Vdc and no load)

Average speed 170 to 250 round per minute (RPM) @ +6V and no load

Weight is 30 grams

Minimum torque is 0.5 kg.cm.

Attached with the plastic mounting with 5 of insert nuts

42 x 45 x 22.7 mm. (WxLxH) dimension

1.3.2 ZX-LED : the simple output board


This module use 8mm. diameter LED. It requires logic 1 or high for driving LED.
The schematic diagram is shown in trhge figure 1-3.

LED1

R1
(Default = 510)

+ Q1
S

KRC102
(DTC114)

Figure 1-3 The ZX-LED completely schematic diagram


10POP-BOT XT : The Arduino Compatible Mobile Robot kit

1.3.3 Standard RC servo motor (available only in Standard kit)

The standard servo is ideal for robotics and basic movement projects. These servos
will allow a movement range of 0 to 180 degrees. The servo output gear shaft is a standard
Futaba configuration. Technical specifications are :

Operating voltage is 6Vdc max.

Speed 0 deg to 180 deg in 1.5 seconds on average.

Weight 45.0 grams/1.59oz

Torque 3.40 kg-cm/47oz-in

Size mm (L x W x H) 40.5x20.0x38.0

1.4 Sensor module features


1.4.1 Switch module/Touch sensor

LED1 Indicator +V

R2
10k
R1
510 R3
DATA
220

Signal output
S1
GND
Switch

The switch input is used to detect collision at logic 0. Two sets along with the
connecting cable are provided.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 11

1.4.2 ZX-03 : Infrared reflector sensor


The heart of this sensor is TCRT5000 reflective object sensor. It is designed for close
proximity infrared (IR) detection. Theres an infrared diode behind its transparent blue window
and an infrared transistor behind its black window. When the infrared emitted by the diode
reflects off a surface and returns to the black window, it strikes the infrared transistors base,
causing it to conduct current. The more infrared incident on the transistors base, the more
current it conducts. When used as an analog sensor, the ZX-03 can detect shades of gray on
paper and distances over a short range if the light in the room remains constant.

Signal connector

+V

OUT TCRT5000

GND 510
10k
Infrared Reflector

The suitable distance from sensor to line or floor is during 3 to 8 mm. The output
voltage is during 0.1 to 4.8V and digital value from10-bit A/D converter is 20 to 1,000. Thus,
ZX-03 will suitable to apply to line tracking sensor.

1.4.3 GP2D120 Infrared distance sensor (available only in Standard kit)


One of the special sensors in robotics is the GP2D120. It is an Infrared Distance
sensor. Some people call it the IR Ranger. With the GP2D120 module, it adds the distance
measuring and Obstacle detection using infrared light feature to your robot. POP-BOT XT
robot can avoid obstacles without having to make any physical contact.

Infrared LED transmitter Infrared Receiver

GP2D120

Vout GND Vcc

Features of the GP2D120 module

Uses Infrared light reflection to measure range


Can measure a range from 4 to 30cm.
4. 5 to 5 V power supply and 33mA electric current
The output voltage range is 0.4 to 2.4V when supplied by +5V
12POP-BOT XT : The Arduino Compatible Mobile Robot kit

GP2D120 Infrared Ranger module has 3 terminals: Power input (Vcc), Ground (GND)
and Voltage output (Vout). To read the voltage values from the GP2D120, you must wait
till after the acknowledgement period which is around 32 to 52.9 ms.
The output voltage of GP2D120 is at a range of 30cm. and +5V power supply is
between 0.25 to 0.55V, with the mean being 0.4V. At the range of 4cm., the output voltage
will change at 2.25V 0.3V.

1.5 POP-BOT XT cable information


The POP-BOT XT mobile robot kit includes some signal cables for the interfacing
between the controller board, sensor module and the computer. They includes the JST3AA-
8 cables for interconnection to the sensor module and the standard USB-miniB cable for
interfacing with the computer.

1.5.1 JST3AA-8 cable


This is an INEX standard cable, 3-wires combined with 2mm. The JST connector is at
each end. 8 inches (20cm.) in length. Used for connecting between microcontroller board
and all the sensor modules in the POP-BOT robot kit. The wire assignment is shown in the
diagram below.

2mm. pitch 2mm. pitch


GND
GND
S S/Data
+5V
+5V

1.5.2 Standard USB-miniB cable


This is used to connect between the computers USB port and the POP-XT controller
board. Its length is 1.5 metres approximation.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 13

1.6 Mechnical prt features


1.6.1 Circle wheel and Tire set
Includes 2 pairs of the suittable circle wheel for BO-2 DC motor gearbox and tread
rubber tire. Fix the wheel with gearbox shaft by 2mm. self-tapping screws

1.6.2 Plastic grid plate set


Includes each of the universal plastic grid palte 2 sizes; 80x60mm. and 80x80mm.
Each plate provides 3mm. diameter holes with 5mm. pitch.

1.6.3 Circle base


This base is injected from high quality ABS plastic. Diameter is 250mm. It has 2 free
ball wheels at both side. This base has many 3mm. holes for fixing the controller board,
sensors and more mechanical parts.
14POP-BOT XT : The Arduino Compatible Mobile Robot kit

1.6.4 Plastic joiners


30 pieces (60 pieces in Standard kit version) of varied color joiners made from PVC
plastic. They can be connected together or by using screws and 3 mm nuts in installation.
There are 3 types; Right angle, Obtuse and Straight joiner.

1.6.5 Strip joiners


They are made from plastic. Each joiner has 3mm. hole 5mm. pitch. Each joiner
can connect for lenght expansion. They are 4 pieces of 3 sizes; 3, 5 and 12 holes type.
Total 12 pieces.

1.6.6 Box holder


It is injected plastic box for supporting the POP-XT controller board. It has some of
3mm. hole for fixing with any platform.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 15

1.6.7 Right-angle metal shaft


It is 7.5mm. width right-angle metal shaft. Each shaft has 3mm. hole for inserting the
screw to fix with another structures. The set includes 4 pieces of 1x2, 2x2 and 2x5 holes
metal shaft.

1.6.8 Screw and Nut set


Includes 2 of 2mm. self-tapping screws, 4 of 3x8mm. M3 screws, 30 of 3x10mm. M3
screws, 4 of 3x15 mm. M3 screws, 4 of 3x40mm. M3 screws, 10 of 3x8mm. flat-head screws
and 30 of 3mm. M3 nuts.

1.6.9 Metal spacer


They are metal parts for supporting the plate and sensor board. They are made
from nikle plating metal. Includes 6 of 32mm. metal hexagonal spacers. Each standoff has
3mm. thread through-hole.

1.6.10 Plastic spacer


They are some mechanical parts for supporting the plate and sensor board. This kit
includes 4 pieces set of plastic spacer (3mm., 10mm., 15mm. and 25mm.) 4 sets
16POP-BOT XT : The Arduino Compatible Mobile Robot kit
POP-BOT XT : The Arduino Compatible Mobile Robot kit 17

Chapter 2
Building the POP-BOT XT robot
The POP-BOT XT robot is a small autonomous robot controlled by ATmega32U4
microcontroller. Although it is built with minimum components and parts, the user will
many learning oppotunities. Learn how DC motor are controlled. Learn about how to
read data from various sensors both digital and analog types. Learn how to write
conditional statements for a given task. Learn how to interface with the Graphical Color
Display and much more

This chapter presents how to build the POP-BOT XT robot with the standard platform.
We will use this platform to learn and try out all the activities.

POP-BOT XT
Arduino Leonardo compatible robot
Movement with DC motor gearboxes and wheels.

Controlled by POP-XT controller board

Programmable via direct USB port

Support a variety of sensors such as


Infrared refelctor for line tacking,
Touch sensor for object avoiding,
Infrared ranger or Distance sensor
for touchless object avoiding.
Supports wired remote control which
includes the PlayStation controller and
the Wii Nunchuk controller.
Supports wireless serial data
communication module such as Xbee and Bluetooth.

Includes the 128x160 pixels color graphic LCD for monitoring and display status.

3 servo motor driver ports. Support small RC servo motor 4.8 to 6V.

Requires 4 of AA batteries. The Alcaline, Evolta and Rechargeable Ni-MH are


recommendded.
18POP-BOT XT : The Arduino Compatible Mobile Robot kit

2.1 Part list

Circle base x 1 POP-XT controller board x1 Box holder x 1

Circle wheel and tire x 2 DC motor gearbox x 2 32mm. metal spacer x 4

Strip joiner 3, 5 and 12 holes


(4 pieces each) Infared reflector x 2
Switch input board
(Touch sensor) x 2

2mm. self-tapping screw x 2

Right angled
metal shaft 2x2 x 2
Plastic joiners

Plastic spacer set Screw and Nut set


POP-BOT XT : The Arduino Compatible Mobile Robot kit 19

2.2 Building procedure

(1) Attach both the DC motor gearboxes with the Box holder by using 3 x 8mm. flat screws.

3x8mm. flat screws

3x8mm.
flat screws

3x8mm. flat screws

(2) Attach 2 of 33mm. metal spacers with the Box holder by 3 x 8mm. flat screws at the
following positions as shown in the pictures below.

32mm. metal spacer 3x8mm. flat screws

3x8mm. flat screws


32mm.
metal spacer

(3) Insert the wheel with tire to DC motor gearboxs shaft and fix with 2mm. self-tapping
screws.

2mm. self-tapping
screw x 2

Circle wheel and tire x 2


20POP-BOT XT : The Arduino Compatible Mobile Robot kit

(4) Attach the gearbox structure as shown in step (3) with the circular base by using 3 x
8mm. flat screws at the following positions shown in the pictures below. See the wheels
position is the center of the base.

screw fixing position

screw fixing position

(5) Attace the ZX-03 sensor with 5-hole strip joiner by using 3 x 15mm. screws and 3mm.
nuts at the first hole of strip joiner. Make 2 sets for the left and right sensors of robot.

5-hole strip joiner

(6) Attach the strip joiner and ZX-03 from step (5) at front left side and right side by using
3 x 10mm. screws and 3mm. nuts.

ZX-03

ZX-03
POP-BOT XT : The Arduino Compatible Mobile Robot kit 21

(7) Attach 2 pieces of 5-hole strip joiner with the front side of the robot chasis following
the picture below by using 3 x 10mm. screws and 3mm. nuts also.

(8) Attach the ZX-01 switch/touch sensor with the right angle joiner by using 3 x 10mm.
screw and 3mm. nut. Next, insert an obtuse joiner at the end of the right angle joiner
following the picture below. Make 2 sets.

3mm. nut
Obtuse joiner
Right angle
joiner
3 x 10mm.
screw
22POP-BOT XT : The Arduino Compatible Mobile Robot kit

(9) Connect the switch arms from step (8) to the end of both of the strip joiners.

(10) Place the POP-XT controller board into the box holder on the top of robot chasis.Turn
the sensor port side (red connectors) to the front as shown in the picture below.

Sensor port side


POP-BOT XT : The Arduino Compatible Mobile Robot kit 23

(11) Connect the motor cable to the Motor output. Check the polarity by turning the
wheel, if pole connection is correct - LED at motor output will be green and change to
red if turn back. If not, please change the connection to opposite.

Motor B cable (right side)

Motor A cable (left side)

(12) Connect the left ZX-03 cable to port A1/19, right ZX-03 cable to port A0/18, left switch
to A5/23 and right switch to A4/22.

left ZX-03 : A1/19

right ZX-03 : A0/18


left ZX-01 : A5/23

right ZX-01 : A4/22

Motor B - right wheel

Motor A - left wheel


24POP-BOT XT : The Arduino Compatible Mobile Robot kit

(13) This is the POP-BOT XT that is ready to be programed and run.


POP-BOT XT : The Arduino Compatible Mobile Robot kit 25

Chapter 3
Arduino 1.0 installation
This chapter describes the details of the Arduino1.0 software used in POP-BOT XT
programming development. It is used for creating, compiling and uploading the code to
the POP-BOT XT robot. It also supports Windows XP or higher, MAC OS and Linux.

3.1 Software installation for Windows 7


3.1.1 Software and USB driver installation
The software that comes with the POP-BOT XT robot kit includes Arduino 1.0 software
that containing the driver and interfacing information of POP-XT controller with Arduino
IDE, a library file of the POP-BOT XT robot named popxt.h and some example codes. The
installation procedure is as follows.

(3.1.1.1) Insert the CD-ROM that comes with the POP-BOT XT kit into the CD-ROM
drive of your computer. Find and double-click the file arduino1.0.1release_setup120531.exe
(or any similar name). The Welcome window will appear, click on the Next button to install.
Next, the windows installer will ask where to install the program, click on the Next button to
continue.
26POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.1.1.2) The installer will ask for a name to be created at Start Menu, click on the
Next button. The installer will show the installation summary, click on the Install button to
begin installation. Installation will take some time, be patient ti allow the installation to
finish.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 27

(3.1.1.3) Next, the USB device drivers installer window will appear. It is the pre-driver
installer of the POP-XT controller board. Click on the Next button to continue.

(3.1.1.4) Click on the Install this driver software anyway box. The USB driver installation
will require you to click twice to continue. Make sure you click the Install this driver software
anyway box twice.
28POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.1.1.5) The driver installation process takes place. Wait until the installation is
complete. It will appear that driver installation is complete and it will show the name of
the installed drivers at Arduino LLC. Click on the Finish button to finish the installation.

3.1.2 Upload testing


(3.1.2.1) Prepare the robot first. Open the batter holder cover and put 4 x AA
batteries. The alcaline or rechargeable 1800mAH type is recommended. After that, put
the POP-XT controller back into the robot chasis.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 29

(3.1.2.2) Turn on power. Wait for a few seconds and then plug in the USB-miniB
cable to the robot. The other end of the USB cable plug into the USB port of your computer.
This step is very important.

YOU MUST TURN ON THE POWER SUPPLY FIRST and WAIT A


FEW SECONDS before connecting the USB cable. It will not work if
these few steps are not done properly.

(3.1.2.3) After connecting the POP-XT controller board to the USB port, the system
will start to verify your hardware. After this is done, check the connection by going to My
Computer, click on the right mouse button select Properties. Enter to Control panel and
select Device Manager
30POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.1.2.4) See the Ports listing, will find a list of Unicon & POP-XT (COMxx) by the
number of COM port could be changed on each computer. For eample is COM26
Remember this COM port number as its required for operation with Arduino1.0.

(3.1.2.5) Open the Arduino 1.0x software. The connection between the POP-XT
controller and computer via USB port still exist.

(3.1.2.6) Choose the example sketch file for upload testing. For example, choose
the Example_glcdFillCircle file from File > Example > POP-BOT XT > Example_glcdFillCircle
POP-BOT XT : The Arduino Compatible Mobile Robot kit 31

(3.1.2.7) Select the hardware by Tools > Board > POP-XT (Caterina).

(3.1.2.8) Select the COM port from Tools > Serial port > COMxxx . This example is
COM26.

(3.1.2.9) Upload the sketch file by clinking on the button or select menu File >

Upload
32POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.1.2.10) Wait until the uploading finish. The status message; Done uploading is
appeared on the staus bar at the bottom of Arduino IDE window.

(3.1.2.11) After uploaded; the POP-XT controller board run immediately. The GLCD
screen displays the margenta solid rectangle.

(3.1.2.12) At the Device Manager window; the new hardware will be appeared. It
is Unicon Board & POP-XT (COMxx) . The number of COM port will be changed to COM27.
The next uploading requires the new port. User must check the port availibility before
uploading by using the Device Manager or check by menu Tools > Serial port of Arduino
IDE

Note : The USB driver installation of the POP-XT contoller board


will generate 2 COM ports that have number is consequently.
If user meet the uploading problem :
(1) Check the current COM port again or
(2) Remove the USB cable and plug again. Check the current
COM port before uploading from Device manager or menu Tools >
Serial port of Arduino IDE.

3.1.3 Troubleshooting if system cannot be find the driver for


POP-XT board when change of USB port connection
After installing the USB drivers completed, user should continue to use the same
USB port. In case of any change to the USB port; there maybe a need to install new drivers
which may be different from the above explained normal steps.

If the system can not find drivers for the hardware interface. Follow the steps below.

(3.1.3.1) Open the Device Manager by clicking the right mouse button at the My
Computer and choose Property. After that select the Device Manager. At the Device
Manager; found the device that has ! symbol in front. Click the right mouse button at that
device name and select to Update Driver
POP-BOT XT : The Arduino Compatible Mobile Robot kit 33

(3.1.3.2) The update driver window will appear. Choose the Browse my computer
for driver software option to locate the drivers manually.

(3.1.3.3) Set the driver location to C:\Arduino\drivers\Unicon POP-XT Driver. Click


on the Next button to update the driver.
34POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.1.3.4) System will warn about the safety of the drivers are installed. Select Install
this driver software anyway to confirm the installation.

(3.1.3.4) Windows will take a while to install the drivers. After which the Device
Ma na g er window will display the device name; Unicon Board & POP-XT (COMxx) with the
COM port number based on the registration of each computer.

The driver installtion requires many steps. Therefore, proper following of instructions
is required to reduce errors in this installation.

After the driver has been installed, the POP-BOT XT robot is ready for programming.

When updating or installing the drivers is complete. The user should check
the port number is always before upload programs to the POP-XT controller board.
The Arduino 1.0x IDE has the ability to find the port to connect the entire system is
automated. And the driver of the Arduino Leonardo (Caterina) that is used in the
POP-XT controller board create the virtual COM port to connect to the computer
to alternate between two port numbers in each RESET and upload a new sketch.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 35

3.2 Software installation for Windows XP


3.2.1 Software and USB driver installation
The software installation in Windows XP is also similar Windows 7.

(3.2.1.1) Insert the CD-ROM that comes with the POP-BOT XT kit into the CD-ROM drive
of your computer. Find and double-click the file arduino1.0.1release_setup120531.exe (or
any similar name). The Welcome window will appear, click on the Next button to install.
Next, the windows installer will ask where to install the program, click on the Next button to
continue.
36POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.2.1.2) the installer will ask for a name to be created at Start Menu, click on the
Next button. The installer will show the installation summary, click on the Install button to
begin installation. Installation will take some time, be patient ti allow the installation to
finish.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 37

(3.2.1.3) Next, the USB device drivers installer window will appear. It is the pre-driver
installer of the POP-XT controller board. Click on the Next button to continue.

(3.2.1.4), The driver installation process takes place. Wait until the installation is
complete. It will appear that driver installation is complete and it will show the name of
the installed drivers at Arduino LLC. Click on the Finish button to finish the installation.
38POP-BOT XT : The Arduino Compatible Mobile Robot kit

3.2.2 Upload testing and install the USB driver


Only the POP-BOT XT USB driver installation process is different in Windows XP. The
procedures are as follows :

(3.2.2.1) Prepare the robot first. Open the batter holder cover and put 4 x AA
batteries. After that, put the POP-XT controller back into the robot chasis.

(3.2.2.2) Turn on power. Wait for a few seconds and then plug in the USB port of
your computer.

(3.2.2.3) After plugging the cable into the robot; the computer detects new hardware
a s a USB c o m p osite a nd a sk fo r the lo c a tion of the d rive r file to insta ll. C lic k o n the Install
from a list or specific location (Advanced) and click on the Next button to next step.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 39

(3.2.2.4) Choose the location as C:\Arduino\Drivers . Click on the Next button.

(3.2.2.5) The driver installation starts. Wait until the installation is completed. Click on
the Finish button.

(3.2.2.6) Check the COM port number of POP-XT that is created by the driver
installtion at Control Panel > System > Hardware > Device Manager > Ports > Unicon Board
& POP-XT (COM xx). An example would be COM179
40POP-BOT XT : The Arduino Compatible Mobile Robot kit

The installation for the USB drivers for Windows XP


is not complete as yet. There is still another procedure
that has to be done. Please ensure you finish all
procedures follow this.

(3.2.2.7) Open the Arduino 1.0x software. The connection between the POP-XT
controller and computer via USB port still exist.

(3.2.2.8) Choose the example sketch file for upload testing. For example, choose
the Example_glcdRect file from File > Example > POP-BOT XT > Example_glcdRect

(3.2.2.9) Select the hardware by Tools > Board > POP-XT (Caterina).
POP-BOT XT : The Arduino Compatible Mobile Robot kit 41

(3.2.2.10) Select the COM port from Tools > Serial port > COMxxx . This example is
COM26.

(3.2.2.11) Upload the sketch file by clinking on the button or select menu File
> Upload

(3.2.2.12) Wait until the uploading finish. The status message; Done uploading is
appeared on the staus bar at the bottom of Arduino IDE window.

(3.2.2.13) After uploaded; the POP-XT controller board run immediately. The GLCD
screen displays the red rectangle shape. Now the first USB driver installation is completed.

(3.2.2.14) Next, the computer detects new hardware and ask for the location of the
driver file to install again. It is second round of USB driver installation. Click on the Install from
a list or specific location (Advanced) and click on the Next button to next step.
42POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.2.2.15) Choose the location as C:\Arduino\Drivers . Click on the Next button.

(3.2.2.16) The driver installation starts. Wait until the installation is completed. Click
on the Finish button.

(3.2.2.17) Wait a second. The Found New Hardware Wizard is appeared again.
Click on the Install from a list or specific location (Advanced) and click on the Next button
to next step.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 43

(3.2.2.18) Choose the location as C:\Arduino\Drivers again. Click on the Next


button.

(3.2.2.19) The driver installation start. Wait until the installation is completed. Click
on the Finish button.
44POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.2.2.20) At the Device Manager window; the new hardware will be appeared. It
is Unicon Board & POP-XT (COMxx) . The number of COM port will be changed to COM180.
The next uploading requires the new port. User must check the port availibility before
uploading by using the Device Manager or check by menu Tools > Serial port of Arduino
IDE.

The driver installtion requires many steps. Therefore, proper following of instructions
is required to reduce errors in this installation.

After the driver has been installed, the POP-BOT XT robot is ready for programming.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 45

3.2.3 USB driver installation for changing the USB port


After installing the USB drivers completed; user should continue to use the same
USB port. In case of any change to the USB port; there maybe a need to re-install new
drivers which may be different from the above explained normal steps.

The driver installation starts with USB composite device driver installation. After that,
install the POP-XT controller board driver. It is called Caterina in boot mode. This step requires
the OK switch pressing on the POP-XT controller board.

(3.2.3.1) After connect the POP-XT controller board to new USB port, the computer
detects new hardware and ask for the location of the driver file to install again. It is second
round of USB driver installation. Click on the Install from a list or specific location (Advanced)
and click on the Next button to next step.

(3.2.3.2) Also choose the location as C:\Arduino\Drivers . Click on the Next button.
46POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.2.3.3) The driver installation starts. Wait until the installation is completed. Click on
the Finish button.

(3.2.3.4) With the USB cable still connected to the POP-XT board and the computer,
turn-off power of the POP-XT controller board. Then, press and hold at the OK switch near
the GLCD on the POP-XT controller board. Turn-on power and release the OK switch.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 47

(3.2.3.5) The Found New Hardware Wizard is appeared immediately. Click on the
Install from a list or specific location (Advanced) and click on the Next button to next step.

(3.2.3.6) Choose the location as C:\Arduino\Drivers . Click on the Next button.


48POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.2.3.7) The driver installation starts. Wait until the installation is completed. Click on
the Finish button.

(3.2.3.8) Check the current COM port for interfacing at Control Panel > System >
Hardware > Device Manager. See the Ports listing, will find a list of Unicon & POP-XT (COMxx)
by the number of COM port could be changed on each computer. Remember this COM
port number as its required for operation with Arduino1.0.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 49

3.3 Arduino1.0 software installation for MAC OSX10.6


The installation of Arduino1.0 siftware for Macintosh computer is not complicated.
Since all files are contained in a ZIP file. The installation step is as follows :

(3.3.1) Copy the Arduino1.0.zip from CD-ROM or downloaded from www.inex.co.th


or www.uniconboard.com to Desktop.

(3.3.2) Extract this file by Open With > Archive Utility.

(3.3.3) The extracted file are the Arduino files. There is a software icon below.

(3.3.4) Open the Finder window. Drag the Arduino icon to Applications
50POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3.3.5) Double-click to open Arduino software. Select menu Tool s > Board > POP-XT

(3.3.6) Tunr on the POP-XTcontroller board. Wait a few seconds for initialization. Plug
the USB cable to board and computer.

(3.3.7) Select menu Tools > Serial Port > /dev/tty.usbmodemxxxx. (xxxx is number
of usbmodem)

If user can do follows all steps, it means the software installation is completed. The
POP-BOT XT also ready for operating with Macintosh computer and MAC OSX10.6.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 51

3.4 Arduino environment


After starting Arduino IDE, the main window will appear as shwon in the figure 3-1.
The Arduino includes the environments as follows.

Menu : Select the operation command

Toolbar : Includes all most command button

Tabs : Allows you to manage sketches with more than one file (each of
which appears in its own tab).
Text editor : Text editor area for creating the sketch.

Message area : Shows the program operation status such as compiling result.

Text area : The space demonstrates compiling information and Serial data
Terminal window if enable.

Menu
Tools bar Serial Monitor
Click to open the
Tab other window for
transmitting and
receiving the
serial data
between Aruino
hardware and
computer

Text Editor

Message area

Figure 3-1 The Arduino1.0 environment


52POP-BOT XT : The Arduino Compatible Mobile Robot kit

Serial Monitor This button is on the top right corner. Click this button to
open the serial communications and display information. Requires the Arduino hardware
must connect with the COM port always.

Serial Monitor is a important for displaying the serial data on the


computer. Arduino has this command ; Serial.print to display data. For sending data from
computer to Arduino is very easy. Only type the data on the text box and click on the
Send button at the top right corner of Serial monitor window. For using Mcintosh computer
or Linux computer; the Arduinoi hardware will need be reset when the Serial monitor is
opened every time.

3.4.1 Menu bar


3.4.1.1 File
The Arduino calls the code as Sketch. This menu contains many commands like
open, save and close the sketch as follows :

New : Creates a new sketch, named is the current date format "sketch_
YYMMDDa".

Open : Open the exist sketch.

Sketchbook : Opne the latest sketch file

Example : Open the example sketch.

Save : Save the current sketch


POP-BOT XT : The Arduino Compatible Mobile Robot kit 53

Save as : Save the current sketch as another name.

Upload to I/O board : Uploads your code to the Arduino I/O board (POP-
XT). Make sure to save or verify your sketch before uploading it.

Page setup : Set up the page layout for the current sketch

Print : Print the current sketch code to the printer

Preference : Set some preference of Arduino environment

Quit : Exit the Arduino IDE

3.4.1.2 Edit
The Edit menu provides a series of commands for editing the Arduino files.

Undo : Reverses the last command or the last entry typed.

Redo : Reverses the action of the last Undo command. This option is only
available, if there has already been an Undo action.

Cut : Removes and copies selected text to the clipboard.

Copy : Copies selected text to the clipboard.

Paste : Inserts the contents of the clipboard at the location of the cursor,
and replaces any selected text.

Select All : Selects all of the text in the file which is currently open in the text
editor.

Find : Finds an occurance of a text string within the file open in the text
editor and gives the option to replace it with a different text.

Find Next : Finds the next occurance of a text string within the file open in
the text editor.

3.4.1.3 Sketch
This menu provides a series of commands for compile the code and manage library.
Verify/Compile : Verify and compiles the code

Stop : Stops current activity.

Add file : Opens a file navigator. Select a code files to add it to the sketches
"data" directory.

Import Library : Import the addition library.

Show Sketch folder : Opens the directory for the current sketch.
54POP-BOT XT : The Arduino Compatible Mobile Robot kit

3.4.1.4 Tools
This menu provides commands about tools for developing the Arduino sketch and
setting up the Arduino hardware.
Auto Format : Attempts to format the code into a more human-readable
layout. Auto Format was previously called Beautify.
Archive Sketch : Compress the current sketch to the zip file.

Export Folder : Open the folder that contain the curretn sketch.

Board : Choose the Arduino hardware. For POP-BOT XT, choose POP-XT

Serial Port :Allows to select which serial port to use as default for uploading
code to the Arduino I/O Board or monitor data coming from it. The data coming from the
Arduino I/O Board is printed in character format in the text area region of the console.

3.4.1.5 Help
This menu contains many information in HTML format for supporting the Arduino user.

Getting Start : Opens the How to start Arduino.

Troubleshooting : Suggest the solution when meet the problem in Arduino.

Environment : Describe about Arduino environments

Reference : Opens the reference in the default Web browser. Includes


reference for the language, programming environment, libraries, and a language comparison.

Frequently Asked Question : See the popular question and answer

Visit www.arduino.cc : Opens the web browser to the Arduino homepage.

About Arduino : Opens a concise information panel about the software.

3.4.2 Tools bar

Verify/Compile : Checks your code for errors.

Upload to I/O Board : Uploads your code to the Arduino I/O board
(POP-168 module). Make sure to save or verify your sketch before uploading it.

New : Creates a new sketch.

Open : Presents a menu of all the sketches in your sketchbook.

Save : Saves your sketch.


POP-BOT XT : The Arduino Compatible Mobile Robot kit 55

Chapter 4
Arduino programming
Programming for POP-XT boards and POP-BOT XT robots is done by using the Arduino
programming language (based on C++) with version 1.0 or higher, in which the language
of Arduino itself is developed from the open-source project framework for microcontrollers
called Wiring and the language of Arduino is grouped into two parts as follows:

1. Language structure, variables, and constants

2. Functions

Arduino language is based on the C/C++ languages so that when programming


for Arduino (including POP-XT controller board) one can use the functions and libraries
which already exist for the C language. This makes it convenient for those who do not
understand the intricacies of microcontrollers to write command programs for them.

This chapter will mainly describe the structure of Arduino. For a complete text written
about the function of the C programming language behind Arduino, see details in help
menu of Arduino IDE or their website; www. arduino.cc

4.1 Program structure of Arduino


An Arduino program is composed of two sections including
void setup ( )
and
void loop ( )

The function of setup () : when a program runs, it will make a statement for this
function only once to define a default value for operation.

The function of loop () is a procedure in the program that contains statements


which are repeated.

Normally, this procedure is performed to specify working modes of the various pins
in the serial communication bus, and so on. The loop contains the program code which is
executed, such as reading input values, processing, displaying output etc. Any
configuration of default values, or components such as variables, need to be declared at
the beginning of the program before reaching the function part. In addition, you should
consider whether to use small letters or capital letters for variables, and name the functions
meaningfully.
56POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.1.1 setup () function description


This function is written at the beginning of a program and executes just once when
the program starts. It is used to declare variables, operating modes of various pins, or the
initialization of libraries, etc.

Example 4-1
int buttonPin = 3;
void setup()
{
beginSerial(9600);
pinMode(buttonPin, INPUT);
}
void loop()
{
if (digitalRead(buttonPin) == HIGH)
serialWrite('H');
else
serialWrite('L');
delay(1000);
}

While the standard C programming language is written on AVR GCC (a kind of C


programming language using the GCC compiler for the AVR microcontroller) will be coded
as follows.
int main(void)
{
init();
setup(); compliance with void setup()
for (;;)
loop(); compliance with void loop()
return ;
}
POP-BOT XT : The Arduino Compatible Mobile Robot kit 57

4.1.2 loop () function description


After coding the function of setup ( ), which has already defined the default values
and initial state of the program, the next part is the loop( ) function. The program will
repeatedly execute this function until otherwise instructed to do so. Inside this function,
there are user programs which read values from ports, perform compilations, and control
output through various pins in order to control the performance of board.

Example 4-2
int buttonPin = 3; // Declare pin 3 to buttonPin variable
void setup()
{
beginSerial(9600);
pinMode(buttonPin, INPUT);
}
// A loop which detects the pressing of a switch
// that declared with buttonPin variable.
void loop()
{
if (digitalRead(buttonPin) == HIGH)
serialWrite('H');
else
serialWrite('L');
delay(1000);
}
58POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.2 Operational control statements


4.2.1 If
Used to test for evaluating conditions during program operation, for example, if an
input value is greater than a certain value, what should be done in that case. The syntax
is shown as follows.
if (someVariable > 50)
{
// do something here
}
The program will check whether the value of someVariable is greater than 50 or
not. If so, what will have to do but if it is not, just skip to the function of this section.

The function of this command is to test certain conditions, which are written in
brackets. If the condition is true, follow an instruction in braces but if the condition is false,
leave out the function of this section.

The conditional test which is in brackets will have to use these comparison operators
as follows.

x == y (x equal to y)

x != y (x not equal to y)

x < y (x less than y)

x > y (x greater than y)

x <= y (x less than or equal to y)

x >= y (x greater than or equal to y)

Techniques for programming


In the comparison of variables, you should use the operator ==, e.g. if (x==10). Do
not use =, such as if (x=10), because a statement like this assigns a value of ten(10) to the
variable x.

Moreover, If statements can be applied to control intersection of the program and


the If...else statements can be used as well.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 59

4.2.2 Ifelse
Applied to test for determining conditions of the program operation and they are
better than normal if statements. The process is that if a condition is true, what to do but
if it is false, what to do so. For example, If a readable value of analog input is greater than
500, what to do but if the value is greater than or equal to 500, do another one else.
Writing statements as follows:

Example 4-3
if (pinFiveInput < 500)
{
// A statement for a kind of operation if a value of pinFiveInput
//is less than 500
}
else
{
// A statement for another type of operation if a value of pinFiveInput
// is greater than or equal to 500
}

After the ifelse statement, able to be followed by the if command. Therefore,


syntax becomes ifelse...if. This is the test of conditions. When it is true, meet the
demand as the following example.

Example 4-4
if (pinFiveInput < 500)
{
// The statement for run a function, since pinFivelnput is less than 500
}
else if (pinFiveInput >= 1000)
{
// The statement for run another function
// because pinFivelnput is greater than or equal to 1000
}
else
{
// The statement to set the next step in case that
// pinFiveInput is not less than 500 and greater than or equal to
// 1000 (that is there will be response of the statement in this
// subprogram when a variable has a value between 501 to 999
}

After the else statement, able to be followed by unlimited if statements (or capable
of putting the switch case statement instead of if...else...if statement for testing
a lot of conditions)

When the if...else...statement has been made, it is important to determine


that if the examination does not match with any condition, what to do by specifying at
the last else statement.
60POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.2.3 For ()
For () is used to instruct a statement in braces in order to repeat operation following
number of cycles required. This statement is very useful for any function that needs to
repeat and know the exact number of repetition round. It is often applied with Array
variables in collection of readable values from many analog input pins that have pin
numbers in sequence.

The syntax of For () command is divided into three parts as follows :


for (initialization; condition; increment)
{
//statement(s);
}
Beginning with initialization used to assign a default value of loop control
variables. In each work cycle, a condition is checked. If the condition is true, a statement
in braces is responded and a variable value is increased or decreased according to the
order in increment. Repeating the test until the condition is false.

Example 4-5
for (int i=1; i <= 8; i++)
{
// The statement for function by using a value of variable i and
// repeating the function until the value of variable i is
// greather than 8 ;
}

For statement of C language is more flexible than whose other computer languages
are. It can ignore some parts or all three parts of the for statement. However, semicolon is
still necessary.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 61

4.2.4 Switch-case
The statement is used to examine conditions in the determination of program
operation. If a tested variable matches with a condition, the run will follow the determined
process.

Syntax
switch (var)
{
case 1:
// The statement for operation when the variable value is equal to 1
break;
case 2:
// The statement for operation when the variable value is equal to 2
break;
default:
// If the value of variable is neither 1 nor 2, comply with this order.
}

Parameters
var - a variable which requires to test matching with which condition.

default - make a statement follow the end if it does not match with any condition,

break - a statement to stop running and it should be written appended cases. If


it is not written, the program will perform repeatedly according to a condition.
62POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.2.5 While
It is a kind of loop statements in order to follow the instruction written in braces
continually until a while() statement is false. A loop statement has to change a value of
a variable, such as to increasing variable value, or has external conditions, such as ability
to start and stop reading values from a sensor, respectively. Otherwise, the condition in
the braces of while () is always true, it causes the loop statement works endlessly.

Syntax
while(expression)
{
// statement(s);
}

Parameters
expression is a conditional test statement (true or false)

Example 4-6
var = 0;
while(var < 200)
{
// The statement for operation by repeating the operation in
// total of 200 rounds
var++;
}
POP-BOT XT : The Arduino Compatible Mobile Robot kit 63

4.3 Arithmetic Operators


There are 5 operators consisted of + (addition), - (substraction), * (multiplicaiton),
and % (modulo reduction, remainder from integer division).

4.3.1 Arithmetic Operators, addition, substraction,


multiplication, and division
They are used to calculate the sum, difference, the product, and quotient of binary
operators to give answers that include the same type as both binary operatands, such as
9/4, which shows the answer as 2 because both 9 and 4 are integer variables (int).

Moreover, arithmetic operators may cause overflow if a result is larger than storing
in that type of variables. If operands are different in types, a result will be as large as the
type of biggest variable (such as 9/4 =2 or 9/4.0 = 2.25).

Syntax
result = value1 + value2;
result = value1 - value2;
result = value1 * value2;
result = value1 / value2;

Parameters
value1 - the value of any variables or constant

value2 - the value of any variable or any constant

Example 4-7
y = y + 3;
x = x - 7;
i = j * 6;
r = r / 5;

Techniques for programming


You should :

Choose the size of variables that is large enough to store the most result value
of calculation.

Know that what value of variables will return the value back and how it back,
for example, (0 to 1) or (0 to -32768)

Use float variables in the calculation of fraction but the difference should be
concerned. For example, large variables can cause slow calculation.

Change types of temporary variables by cast operators, such as (int)myfloat,


while a program is running
64POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.3.2 Modulus operator : %


The operator is able to compute remainder of 2 integers but not to apply for floating-
point variables (float).

Syntax
result = value1 % value2;

Parameters
value1 - a variable of byte, char, int or long type

value2 - a variable of byte, char, int or long type

Result
Remainder from performing integer division is integer data.

Example 4-8
x = 7 % 5; // x now contains 2
x = 9 % 5; // x now contains 4
x = 5 % 5; // x now contains 0
x = 4 % 5; // x now contains 4

This modulus operator is applied for operation which demands events occurring
at regular intervals or causes the memory, which stores array variables, to roll over.

Example 4-9
// Examine the value of a detector for 10 times per a operating cycle
void loop()
{
i++;
if ((i % 10) == 0)
// Divide a value of i by 10 and then check
// if the remainder of division is 0 or not
{
x = analogRead(sensPin); // Read from the detector for 10 times
}
}

In this example, the % statement is used to assign the cycle of operation in which
the program repeats performing to read value till the result of modulo division of the i %
10 statement is equal to 0 and this occurs when i = 10 only.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 65

4.4 Comparison operators


Comparison operators go with the if () statement to test conditions or compare
variable values by writing expression inside the mark of ().
x == y (x equal to y)
x != y (x not equal to y)
x < y (x less than y)
x > y (x greater than y)
x <= y (x less than or equal to y)
x >= y (x greater than or equal to y)

4.5 Logical operators


Performed a for comparison of if () statements and there are 3 types; &&, ||, and !.

4.5.1 && (logic and)


Let a value is true when the comparison result of both sides is true.

Example 4-10
if (x > 0 && x < 5)
{
// ...
}

The value is true when x is greater than 0 and less than 5 (a value of 1 to 4).

4.5.2 && (logic or)


The value is true when the comparison result shows that one of variables is true or
both variables are true.

Example 4-11
if (x > 0 || y > 0)
{
// ...
}

It shows the result is true when the value of x or y is greater than 0.

4.5.3 ! (used to convert the result to be contrary)


The value is true when the comparison result is false.

Example 4-12
if (!x)
{
// ...
}
The result is true if x is false (such as x = 0, the result is true)
66POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.5.4 Caution
Be careful for programming. If you want to use logical operators, you have to write
the mark of &&. If you write a mark of &, Bitwise AND operators and variables will show
different results.

As well in application of logic or writing the sign of || (two vertical bars next to
each other), if write the sign of | (one vertical bar) this means Bitwise OR operators and
variables.

A bitwise NOT operator is different from a conversion operator (!) so you should
choose the right one to apply.

Example 4-13
if (a >= 10 && a <= 20){}
// The result of performance is true when the value of a is between 10
// to 20.

4.6 Bitwise operators


Level operators will bring bit of variables to process and they are useful to solve
problems of programming widely.

There are 6 level operators of C language (including Arduino) consisted of & (bitwise
AND), | (OR), ^ (Exclusive OR), ~ (NOT), << (shift bits to the left) and >> (shift bits to the
right)

4.6.1 Bitwise AND operators (&)


AND in bitwise statements of C programming language can be represented by
using the mark of & in and you must write between expressions or integer variables. The
work will take data of each bit of both variables to operate with AND logic. The rules are
as follows.
0 0 1 1 Operand1
0 1 0 1 Operand2

0 0 0 1 Returned result

If both inputs are 1, both outputs are 1. Other cases, outputs are 0 as the
following example. In checking, a pair of operators should be in the vertical.

In Arduino, int variables have the size of 16 bits so when using AND bitwise operators,
there is logical action in conjunction with all 16- bit data as the example in the following
program.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 67

Example 4-14
int a = 92; // equal to 0000000001011100 binary
int b = 101; // equal to 0000000001100101 binary
int c = a & b; // result is 0000000001000100 binary or 68 demical

In this example, all 16-bit data of variable a and b are performed by AND logic
and then the result of all 16 bits will be stored at variable c, which the value is 01000100 in
binary number or 68 in decimal number.

It is popular to use bitwise AND operators to select desired bit-data (maybe one bit
or many bits) from int variables in which this selection of some bits is called masking.

4.6.2 Bitwise OR operator ( l )


A bitwise OR statement of C language is able to be written by using one mark of |
by writing between expressions or integer variables. The process is to bring data of each
bit of both variables to operate with OR logic. The rules are as follows.

If any input or both are 1, so the output is 1. In case that both input are 0 so the
output is 0 as following example.
0 0 1 1 Operand1
0 1 0 1 Operand2

0 1 1 1 Returned result

Example 4-15
The program shows application of bitwise OR operators.
int a = 92; // equal to 0000000001011100 binary
int b = 101; // equal to 0000000001100101 binary
int c = a | b; // The result is 0000000001111101 binary or 125 decimal

Example 4-16
The program demonstrates application of bitwise AND and OR operators.

The example of a program, which uses bitwise AND and OR operators, are called
by programmers as Read-Modify-Write on a port. For 8-bit microcontroller, values of reading
or writing to the port have the size of 8 bits and show input at all 8 pins. Writing values
sending to a port is done only one time to cover all 8 bits.

The variable named PORTD is the value used instead of the status of digital pin
numbers 0, 1, 2, 3, 4, 5, 6, 7. If any bit has a value as 1, this makes that pin have logic value
as HIGH (dont forget to specify that port pin to work as output with pinMode command
( )) Therefore, if configuration of PORTD is determined = B00110001; this is to design pin 2, 3,
and 7 as HIGH. In this case, it doesnt need to change the status values of pin 0 and 1.
Normally, hardware of Arduino is used in the serial communication. If you convert a value,
this will affect to the serial communication.
68POP-BOT XT : The Arduino Compatible Mobile Robot kit

Algorithm for the program is as follows

Read a value from PORTD and then clean up the value at only the
controlled bit (using a bitwise AND operator).

Take the modified PORTD value from above to add with the bit from above
(OR operators).

Write the program as follows :


int i; // counter variable
int j;
void setup()
{
DDRD = DDRD | B11111100; // determine the direction of the
// port pin 2 to 7 with the value of
// 11111100
Serial.begin(9600);
}
void loop()
{
for (i=0; i<64; i++)
{
PORTD = PORTD & B00000011; // determine data to pin 2 to 7
j = (i << 2);
PORTD = PORTD | j;
Serial.println(PORTD, BIN);
// show the value of PORTD at the serial monitor window
delay(100);
}
}
POP-BOT XT : The Arduino Compatible Mobile Robot kit 69

4.6.3 Bitwise Exclusive OR statement (^)


It is a special operator which is not usually used in C/C ++ language. The exclusive
OR operator (or XOR) is written by using the symbol of ^ and this operator has operation
resembled to a bitwise OR operator but they are different when both inputs are 1, output
is 0. The demonstration of work is as follows.
0 0 1 1 Operand1
0 1 0 1 Operand2

0 1 1 0 Returned result

Or it is also said that bitwise XOR operators give the output as 0 when both inputs
are the same and give the output as 1 when both inputs are different.

Example 4-17
int x = 12; // Binary number is 1100
int y = 10; // Binary number is 1010
int z = x ^ y; // Result is 0110 as binary or 6 as decimal

Bitwise XOR operators are much used in value swap of some bits of int variables,
such as changing from 0 to be 1 or from 1 to 0.

When using bitwise XOR operators, if a bit of mask is 1 so this affects the swop of bit
value. Otherwise, if a value of mask is 1 the bit value remains the same. The following
example is a program shown the instruction that logic of the digital pin 5 is switched all the
time.

Example 4-18
void setup()
{
DDRD = DDRD | B00100000; // Assign pin 5 as output
}
void loop()
{
PORTD = PORTD ^ B00100000; // Invert logic at pin 5
delay(100);
}
70POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.6.4 Bitwise NOT operator (~)


Bitwise NOT will write by using symbol ~. This operator will be performed with only
one operand on the right by switching all bits to become opposite values, i.e. from 0 to
be 1 and from 1 to be 0 as the example.
0 1 Operand1

1 0 ~ Operand1

int a = 103; // binary: 0000000001100111


int b = ~a; // binary: 1111111110011000

When operated already, this makes the value of variable be as -104 (decimal) in
which the answer is negative because of the most important bit (the bit on the far left) of
an int variable. An int variable is the bit which notifies whether the number is positive or
negative. The value is 1, meant that this value is negative. A computer will store the
number value as both positive and negative according to 2s complement system.

Declaration of int variables, which has the same meaning as the signed int, should
be aware that the value of the variable may be negative.

4.6.5 Left shift (<<) and Right shift (>>)


In C/C++ programming language, there is an operator shifts bits to the left << and
shifts bits to the right >>. This operator will instruct to slide bits of operands written on the left to
the left or the right in accordance with the amount of bits stated on the right of the operator.

Syntax
variable << number_of_bits
variable >> number_of_bits

Parameter
variable - an integer variable which has the amount of bits less than or equal
to 32 bits (or a byte, int or long variable).

Example 4-19
int a = 5; //equal to 0000000000000101 binary
int b = a << 3; // the result is 0000000000101000 binary or 40
int c = b >> 3; // the result is 0000000000000101 binary or 5 decimal

Example 4-20
When instructing to slide variable x to the left following the amount of y bit (x <<
y), the bit data on the far left of x with the amount of y will be disappeared because it is
moved to the left hand.
int a = 5; //equal to 0000000000000101 binary
int b = a << 14; // the result is 0100000000000000 binary
POP-BOT XT : The Arduino Compatible Mobile Robot kit 71

Moving bits to the left will affect the value of the variable on the left of the operator
is multiplied by two and power the number of bits that shift to the left as follows.

When you instruct to slide variable x to the right with the amount of y bit (x >> y),
the difference depends on types of variables. If x is an int variable, the sum can appear
both positive and negative. Wherewith, the bit on the far left will be sign bit and if it is a
negative, the bit on the far left will be 1. After instructing to move a bit to the right, the
program will bring the value of sign bit to add up to the bit on the far left. This phenomenon
is called sign extension as the example below.

Example 4-21
int x = -16 // equal to 1111111111110000 binary
int y = x >> 3 // shift bits of x variable to the right for 3 times
// the result is 1111111111111110 binary

If you would like to slide the bit to the right and then put 0 at the bit on the far left
(which happens with a case that a variable is unsigned int), you can do by changing
types of temporary variables (typecast) in order to convert variable x to unsigned int
temporarily as the following example.

Example 4-22
int x = -16 // Equal to 1111111111110000 binary
int y = unsigned (x) >> 3 // Shift bits of x variable (not concerned
// about the sign) to the right for 3 times
// The result is 0001111111111110 binary

After being aware of the sign extension, you will use the operator to move bits to
the right for dividing the variable value by 2 and power any number. For example

Example 4-23
int x = 1000;
int y = x >> 3; // Divide the value of 1000 by 8, from 23
// The result is y = 125
72POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.7 Syntax of Arduino


4.7.1 ; (semicolon)
Used to end a statement

Example 4-24
int a = 13;

Forgetting to end a statement line in a semicolon will result in the complier error.
Wherewith, a complier may complain that it cannot find the semicolon or notify as other
mistakes. In case that a line which is noticed some mistakes but cannot be found any
mistake so you should check a previous line.

4.7.2 { } (Curly-braces)
Curly braces are a major part of C programming language and used to determine
operation in each period. An opening brace {must always be followed by a closing brace}
or it is said that parentheses must be balanced. In Arduino IDE software that is used for
programming will have an ability to check the balance of curly braces so users just click
at a parenthesis and its logical companion will be highlighted.

For beginning programmers and programmers coming to C language from BASIC


language might be confused with the application of brackets. In fact, curly braces can
be compared with the RETURN statement in subroutine (function) or replace the ENDIF
statement in comparison, and the NEXT statements in a FOR loop.

Because the use of the curly braces is so varied, it is good that you should type a
closing bracket immediately after typing the opening bracket. Next, press ENTER button in
between two braces to start a new line and write a desired statement. If you can follow
this suggestion, your braces will never become unbalanced.

Unbalanced braces can make mistakes while a programme is compiled. If a


programme is large, it is hard to track down any mistake. Location of each bracket
influences to the syntax of a program. Therefore, moving a brace one or two lines will
affect the meaning of a program.

The main use of curly braces


Functions
void myfunction(datatype argument)
{
statements(s)
}
POP-BOT XT : The Arduino Compatible Mobile Robot kit 73

Loops
while (boolean expression)
{
statement(s)
}
do
{
statement(s)
} while (boolean expression);
for (initialisation; termination condition; incrementing expr)
{
statement(s)
}
Conditional statements
if (boolean expression)
{
statement(s)
}
else if (boolean expression)
{
statement(s)
}
else
{
statement(s)
}

4.7.3 // (single line comment) and /** (multi-line comment)


Comments are part of a program and a programmer will write more information to
inform how the program operates. They are ignored by complier, and not exported to the
processor, so they are very useful to investigate the program later or inform colleagues or
others what this line is used for. There two kinds of comments in C lanague, including

(1) Single line comments write 2 slashes (//) in front of a line.

(2) Multi-line comments write a slash (/) paired with asterism to cover text of
comments, such as /*blabla*/.
74POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.7.4 # define
This statement is used a lot in determination of constants for a program. Defined
constants dont take up any memory space of microcontroller. When it is at the compile
time, the compiler will replace characters with the assigned value. Arduino will use the
same # define statement as C language does.

Syntax
#define constantName value (Note : the # is necessary)

Example 4-25
#define ledPin 3
// Determination to let variable ledPin equal to constant 3

There is no semicolon after the # define statement.

4.7.5 # include
It instructs to gather other files and our program file and then compile the program
later.

Syntax
#include <file>
#include file

Example 4-26
#include <stdio.h>
#include popxt.h

The first line will take file stdio.th to fuse with a developing program by searching
the file from a location where stores the file system of Arduino. Normally, it is a standard file
come up with Arduino.

The second line instructs to gather file popxt.h and a developing program by
looking for address of C language files. Generally, they are files users build.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 75

4.8 Variables
Variables are several characters determined in a program and used to store various
informative values, such as readable values from a sensor connected with analog port
pins of Arduino. There are many types of variables.

4.8.1 char : character type variable


The variable takes up 1 byte (8 bits) and it is provided for storing character values.
Characters in C language will be given inside single quotes, like this, A (for text, which
composed of many characters together, will be written in double quotes, such as ABD).
You can do arithmetic on characters, in case that you will apply ASCII values of the
characters, e.g. A+1 has the value of 66 because the ASCII code value of character A is
equal to 65.

Syntax
char sign = ' ';

Example 4-27
char var = 'x';

var is a name of a character variable you desired.

x is a desired value to assign to that variable and here is one letter.

4.8.2 byte : a variable of numeric type 8 bit or 1 byte


A byte variable is used to store a numeric value with the size of 8 bits and the value
can be between 0 to 255.

Example 4-28
byte b = B10010;
// Show the value of b in the form of a binary number
// (equal to 18 of a decimal number)

4.8.3 int : a variable of integer type


It is abbreviated from integer, which means an integer number. The int is a basic
variable for preserving numbers. One variable has the size of 2 bytes and stores a value
from -32,768 to 32,767, from -215 (minimum value) and 215-1 (maximum value). In storage of
negative numbers uses a technique called 2s complement and the maximum bit
sometimes called sign bit. If a value is 1, it is shown the value is negative.

Syntax
int var = val;
76POP-BOT XT : The Arduino Compatible Mobile Robot kit

Parameters
var - a name of a desired variable of int type.

val - a desired value to define to a variable.

Example 4-29
int ledPin = 13; // Assign variable ledPin to have a value = 13

When a variable is greater than a maximum capacity, the value will roll over to a
minimum capacity, however, when a value is less than a minimum capacity, the value
will roll over to a maximum capacity as the following example.

Example 4-30
int x
x = -32,768;
x = x - 1; // When you follow the instruction,
// the value of x will change -32,768 into 32,767.
x = 32,767;
x = x + 1; // When the statement is done,
// the value of x will change from 32,767 to -32,768

4.8.4 unsigned int : a variable of unsigned integer type


This type variable is similar to an int variable but will store only positive integers by
storing the value 0 to 65,535 (216-1).

Syntax
unsigned int var = val;

Parameters
var - the name of the desired int variable.

val - the desired value to assign to a variable.

Example 4-31
unsigned int ledPin = 13;
// Determine ledPin variable to have the value equal to 13 of unsigned type

When a variable has a maximum capacity, it will roll over back to a minimum
capacity later. Additionally, when a variable has a minimum capacity, it will roll over and
become a maximum capacity when there is value reduction again. As the example

Example 4-32
unsigned int x
x = 0;
x = x - 1; // After executed, the x value change from 0 to 65535.
x = x + 1; // After executed, the x value change from 65535 into 0
POP-BOT XT : The Arduino Compatible Mobile Robot kit 77

4.8.5 long : a variable of 32-bit integer type


The variable stores integer values and extends its capacity from an int variable. A
long variable uses a memory space of 32 bits (4 bytes) and is capable of storing values
from -2,147,483,648 through 2,147,483,647.

Syntax
long var = val;

Parameters
var - the long variable name.

val - the value that assign to the variable.

Example 4-33
long time; // Specify a time variable to be the long type

4.8.6 unsigned long : a variable of unsigned 32-bit integer type


A variable stores positive integers. One variable uses a memory space of 32 bits (4
bytes) and stores a value in range of 0 to 4,294,967,295 or 232-1.

Syntax
unsigned long var = val;

Parameter
var - the name of unsigned long variable.

val - the value that assign to the variable.

Example 4-34
unsigned long time; // Determine a time variable to be unsigned long type

4.8.7 float : float-point variable


Float is a variable for storing a value of decimal number values. It is popular to be
used to keep an analog signal value or a continuous value. Because this variable gives
values more precise than an int variable does, a float variable can store in a range of
4.4028235 x 1038 through -4.4028235 x 1038 and one variable will cover 32-bit memory space
(4 bytes).

In a mathematical calculation with the float variable will be slower than a


calculation of int variable so you should avoid calculating with float variables when doing
loop statement with the highest speed of a time function because it must be very precise.
Some programmers will convert decimal numbers to integer numbers before a calculation
for faster operation.
78POP-BOT XT : The Arduino Compatible Mobile Robot kit

Syntax
float var = val;

Parameters
var - the float variable name

val - the value that determine to the variable

Example 4-35
float myfloat;
float sensorCalbrate = 1.117;

Example 4-36
int x;
int y;
float z;
x = 1;
y = x / 2; // y is equal to 0 no storage of values of
// remainder from division
z = (float)x / 2.0; // z is equal to 0.5

When there is a usage of a float variable, numbers that are operated with this
float variable will be decimals as well. From the example is that number 2 calculated with
float variable x, so the number 2 is written as 2.0.

4.8.8 double : Double precision floating-point variable


Double has the size of 8 bytes and the highest stored value is 1.7976931348623157
x 10308 . In Arduino, there is limited capacity so it doesnt use this type of variables.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 79

4.8.9 string : variable of text type


String is a variable that stores text and it is usually array of a char variable in C
language.

Example 4-37 : Example of declaration of string variables


char Str1[15];
char Str2[8] = {'a','r','d','u','i','n','o'};
char Str3[8] = {'a','r','d','u','i','n','o','\0'};
char Str4[ ] = "arduino";
char Str5[8] = "arduino";
char Str6[15] = "arduino";

Str1 is a declaration of a string variable in which a default value is not defined.

Str2 announces a string variable along with defining a value of each character
for a text. If it is not completed following the announced number, a complier will add null
string until completing (from the example, 8 characters are declared but the text has only
7 characters so a complier fill one null string).

Str3 states a string variable together with determining a value to give a text
and close the end with a closing character which is\0.

Str4 declares a string variable together with a determining a variable value in


quotes. From the example, it doesnt assign the size of a variable, so a complier will assign
the size according to a number of letters.

Str5 proclaims a string variable along with specifying a variable value in a


quotation mark and the size of the variable, from the example, is 8 letters.

Str6 reveals a string variable and defines the size reserving for another text
that is longer than this.

4.8.9.1 Addition of characters which inform null termination


A string variable in C language specifies that the last character is an indicator of a
null string. The indicator is 0. In determination of size of variables (value in square brackets),
the size is equal to the amount of characters +1, as shown in the variable Str2 and Str3 in the
example 4-37. In the text of Arduino, there are 7 characters, declaration must specify as [8].

In announcement of a string variable, you should keep a space for storing a


character, which notifies the null termination. Otherwise, a complier will warn a mistake
happening. In the example, variable Str1 and Str6 can store messages with a maximum of
14 characters.

4.8.9.2 Single and double quotes


Normally, a string variable is determined inside quotes, such as ABC. For a char
variable, it is defined inside single quotation marks A.
80POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.8.10 Array variable


An array is a variable containing multiple variables which are stored in variables of
the same name.

Each variable is referred by an index number written inside square brackets. An


array variable of Arduino will be cited according to C language. It may look complicated
but if using an array variable directly, it is easy to understand.

Example 4-38 : Example of declaration of array


int myInts[6];
int myPins[] = {2, 4, 8, 3, 6};
int mySensVals[6] = {2, 4, -8, 3, 2};
char message[6] = hello;

A program developer is able to declare an array without determination of a


myInts variable.

Announcement of variable myPins is a declaration of an array variable without


specifying its size.

In declaration of an array, a program developer can announce and determine


a size of an array in the same time, as the example of declaration of variable mySensVals
to proclaim a size and specify values.

The last example is the declaration of a message variable, which is a char


variable, and there are 5 characters, including hello. However, determination of a variable
size will have to preserve a space for a character that informs null termination, so the
index value is specified as 6.

4.8.10.1 Usability of array variables


The usability of arrays can be done by typing a variable name together with
specifying an index value inside square brackets. An index value of an array variable
starts with value 0, so the value of a mySensVals variable is as follows.
mySensVals[0] == 2, mySensVals[1] == 4 ,
Determination of a value for an array variable can do as follows
mySensVals[0] = 10;
Calling a member value of an array value is done as this example
x = mySensVals[4];
POP-BOT XT : The Arduino Compatible Mobile Robot kit 81

4.8.10.2 Arrays and for loop instructions


Generally, application of an array variable is found in a for statement. An index
value of an array variable is given from using a value of a loop variable of the for statement
as the following example.

Example 4-39
int i;
for (i = 0; i < 5; i = i + 1)
{
Serial.println(myPins[i]); // Showing a member value of an array
// variable at a serial monitor window
}

The completed program example of application of array variables are available


in the example of KnightRider in the topic of Tutorials at the website www. arduino.cc.

4.9 Scope of variables


Variables in C language used in Arduino have a specification called scope. This is
different from BASIC language that all variables have the same status and the status is
called global.

4.9.1 Local and global variables


Global variables are variables all functions in a program knowed by declaring the
variables outside functions. Local variables are variables proclaimed inside braces of
functions and known only in functions.

When programs are larger and more complex, usage of local variables is very
useful because only functions can apply the variables. This helps to protect mistakes when
a function modifies variable values used by other functions.

Example 4-40
int gPWMval; // All functions can see this variable.
void setup()
{}
void loop()
{
int i; // Variable i will be seen and performed inside only
// a loop function.
float f; // Variable f will be seen and applied only inside a
// loop function.
}
82POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.9.2 Static variables


A static variable is a reserved word and used when declaring variables, which
have scope of use only inside functions. It is different from a local variable that a local
variable will be created and deleted every time to run functions. For a static variable,
when a function finishes, it is still appeared (not deleted). This is a preservation of a variable
value during function performs.

A declared variable as static will build and define a value at the first time to run a
function.

4.10 Constants
Constants are a group of characters or text preconfigured, so a complier of Arduino
will recognise these constants and it is not neccesary to notify or determine constants.

4.10.1 HIGH, LOW : used to assign logical values


In reading and writing values for digital port pins, two possible values are HIGH or
LOW.

HIGH is determination of values for digital pins and has voltage equal to +5V. If you
can read a value equal to +3V or greater, a microcontroller will read the value as LOW. A
constant of LOW is 0 or compared to logic as false.

LOW, which is configuration of digital pins, has voltage equal to 0V. If you can read
a value as +2V or less, a microcontroller will read the value as LOW and a constant of LOW
is 0 or compared to logic as false.

4.10.2 INPUT, OUTPUT : Determination of direction of digital


port pins
Digital port pins can serve for 2 types including being input and output:

When defined as INPUT means to assign that port pin as an input pin.

When specified as OUTPUT means to assign that port pin as an output pin.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 83

POP-Note

Assignment of integer constants to be in various number bases of


Arduino
An integer constant is a number you write in a program of Arduino directly, such
as 123, and normally, these numbers are decimal numbers. If you would like to specify
them into other number radix systems, you will have to use special marks to specify. For
example

Base Example

10 (decimal) 123

2 (binary) B1111011

8 (octal) 0173

16 (hexadecimal) 0x7B

Decimal is a decimal number used in daily life

Example : 101 = 101. It is from (1* 102) + (0 * 101) + (1 * 100) = 100 + 0 + 1 = 101

Binary is a binary number in which a number in each position can be only 0 or 1.

Example : B101 = 5 in decimal. It is from (1 * 22) + (0 * 21) + (1 * 20) = 4 + 0 + 1 = 5

Binary numbers can be used less than 8 bits (not greater than 1 byte) and
have values from 0 to (B0) 255 (B11111111).

Octal is an octal number and a number in each position has a value from 0 to 7
only.

Example : 0101 = 65 in decimal. It is from (1 * 82) + (0 * 81) + (1 * 80) = 64 + 0 +1


= 65

Caution in configuration of constants is to not put 0 in the front, otherwise, a


compiler will translate a meaning incorrectly that a number value is octal.

Hexadecimal (Hex) is a hexadecimal number. A number in each position is worth


from 0 to 9 and character A is 10 and B is 11 until F which is equal to 15.

Example : 0x101 = 257 in decimal. It is from (1 * 162) + (0 * 161) + (1 * 160) = 256 +


0 + 1 = 257
84POP-BOT XT : The Arduino Compatible Mobile Robot kit

4.11 Other operators related to variables


4.11.1 cast : changing kinds of variables temporarily
Cast is an operator that instructs changing of a type of variables into another type
and controls calculation of a variable value to become a new kind.

Syntax
(type)variable
type is a type of any variables (such as int, float, long)

variable is any variable or constant

Example 4-41
int i;
float f;
f = 4.6;
i = (int) f;

In the change of a variable type from float into int, a remainder of an obtained
value will be cut out, so (int) 4.6 becomes 4.

4.11.2 sizeof : notifying the size of variables


Sizeof is used to identify the amount of byte of variables you are interested and it
can be both a normal variable and an array.

Syntax
written into two patterns as follows
sizeof(variable)
sizeof variable
Therefore; Variable is a normal variable or an array variable (int, float, long)
user would like to know the size.

Example 4-42
Sizeof operators are very useful in management with array variables (including
string variables).

The following example will type text out through a serial port, each character a
time.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 85

char myStr[] = this is a test;


int i;
void setup()
{
Serial.begin(9600);
}
void loop()
{
for (i = 0; i < sizeof(myStr) - 1; i++)
{
Serial.print(i, DEC);
Serial.print( = );
Serial.println(myStr[i], BYTE);
}
}

4.12 Reserved words of Arduino


A reserved word is a constant, a variable, and a function defined as a part of of C
language of Arduino. Dont take these words to denominate variables. They are shown as
follows :
# Constants # Literal Constants # Datatypes # Methods/Fucntions
HIGH GLCD_RED boolean sw_ok
LOW GLCD_GREEN byte sw_ok_press
INPUT GLCD_BLUE char analog
OUTPUT class
GLCD_YELLOW knob
SERIAL default
GLCD_BLACK glcd
DISPLAY do
PI GLCD_WHITE glcdChar
double
HALF_PI GLCD_SKY int glcdString
TWO_PI GLCD_MAGENTA long glcdMode
LSBFIRST private glcdGetMode
# Port Constants
MSBFIRST protected glcdFlip
CHANGE DDRB
public glcdGetFlip
FALLING PINB
return colorRGB
RISING PORTB
short setTextColor
false DDRC
signed
PINC setTextBackgroundColor
true static setTextSize
PORTC
null switch
DDRD getTextColor
throw
PIND getTextBackgroundColor
try
PORTD getTextSize
unsigned
void glcdFillScreen
# Names
glcdClear
popxt
glcdPixel
glcdRect
glcdFillRect
glcdLine
glcdCircle
86POP-BOT XT : The Arduino Compatible Mobile Robot kit

glcdFillCircle # Other float -


=
glcdArc floor switch
abs
for tan
getdist acos
< this
in +=
<= true
+
out HALF_PI TWO_PI
[]
motor if void
asin
motor_stop ++ while
=
!= Serial
fd atan
int begin
bk atan2
<< read
fd2 &
< print
&=
bk2 <= write
|
tl log println
|=
tr && available
boolean
! digitalWrite
sl byte
|| digitalRead
sr case
^ pinMode
ceil
servo ^= analogRead
char
sound loop analogWrite
char
beep max attachInterrupts
class
millis detachInterrupts
uart_set_baud ,
min beginSerial
uart_get_baud //
- serialWrite
?:
uart_putc % serialRead
constrain
uart_puts /* serialAvailable
cos
uart * printString
{}
new printInteger
uart_available
null printByte
uart_getkey default
() printHex
uart1_set_baud delay
PII printOctal
delayMicroseconds
uart1_get_baud return printBinary
/
uart1_putc >> printNewline
/**
uart1_puts ; pulseIn
.
Serial shiftOut
uart1 else
Setup
uart1_available ==
sin
exp
uart1_getkey sq
false
uart1_flush sqrt
float
POP-BOT XT : The Arduino Compatible Mobile Robot kit 87

Chapter 5
POP-BOT XT program
development by Arduino1.0
The POP-BOT XT robots program development can be summarize in the diagram
shown in figure 5-1.

Installtion software tools Create the sketch file


- Arduino 1.0 IDE : Make the C/C++ code on Arduino IDE
C/C++ programming development tools.
Includes Text editor, Compiler and Upload the
code to microcontroller
- USB driver of the POP-XT controller board Compile

Upload the code

USB port

Upload the code via USB port


1. Turn on and wait a few second for
USB initialize. Then plug the USB-miniB
cable to POP-XT controller board.
2. Check the USB Serial port address.
3. Upload the code.

Run the code


After uplaod the code successfully, press
RESET switch on the POP-XT controller
board ; brain of the POP-BOT XT.
The POP-BOT XT run following the
uploaded code.

Figure 5-1 Programming development diagram of POP-BOT XT robot kit by


using Arduino IDE
88POP-BOT XT : The Arduino Compatible Mobile Robot kit

5.1 Getting start POP-BOT XT with Arduino


Run the Arduino IDE by clickng on the Start > All Programs > Arduino1.0 > Arduino

The first launch of Arduino is shown the screen below.

5.1.1 POP-BOT XT hardware configuration with Arduino IDE


5.1.1.1 Select microcontroller chip
Select the menu Tools > Board > POP-XT
POP-BOT XT : The Arduino Compatible Mobile Robot kit 89

5.1.1.2 Select the COM port


Uploading the sketch from Arduino IDE to POP-BOT X T requires serial port
communication. It can work with virtual COM port that created from USB driver installation.

Select menu Tools > Serial Port . You can select the target COM port.

5.1.2 Create the new sketch


(1) Create the new sketch file by selecting File > New . Next, type the following
code.
#include <popxt.h> // Include POP-XT library
void setup()
{
glcd(1,0,"Hello World"); // Display message on the GLCD screen
}
void loop()
{}

(2) Save to HelloWorld.ino


90POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3) Compile the code by selecting Sketch > Verify/Compile following the picture
below or click at the button.

(4) The status bar at the bottom of main screen will display the compilation status.
If compile no error, it reports Done compiling and the Text area will display message of
binary sketch size.

5.1.3 Uploading the code


(1)Turn on the POP-BOT XT . Wait a few second for USB initialize. Plug the USB-miniB
cable to connect the robot with computer.

Connect with
USB-miniB cable computer's USB port

Computer
F
0
2
2
F
0
0
1

0
0
1

AT Mega32U 4

TB6612

POP-BOT XT
POP-BOT XT : The Arduino Compatible Mobile Robot kit 91

(2) Upload the sketch by clicking button or select menu File > Upload

(3) Wait until the uploading is successfully. The status bar at the bottom of main
screen will display message Done Uploading .Code will run immediately or press a RESET
switch again.

This example code is sending the message ; Hello World to display on line 1
column 0 of the GLCD screen of the POP-BOT XT

All this is preparation for the programming language C / C + + with Arduino for the
POP-BOT XT robot. The program development of this robot is very easy and comfort.
Because all steps are finish within a single window.
92POP-BOT XT : The Arduino Compatible Mobile Robot kit
POP-BOT XT : The Arduino Compatible Mobile Robot kit 93

Chapter 6
POP-BOT XT controller board
hardware experiment

In this chapter we will learn about some activities for the POP-BOT XT controller
board. Its POP-XT board. They include 4 main activities as follow :

1. Color GLCD activities (5 activities)

2. Generating of sounds

3. Reading the OK switch and KNOB data from the GLCD-XT board of POP-XT
board

4. Controlling simple output devices.

The development program procudures in each activity also similar. Open the
Arduino IDE 1.0, create the code, compile and upload onto the POP-BOT XT. Lastly, test
the operation.

It's important to emphasize that every time you turn on the power
supply of POP-BOT XT, must wait for USB initialize first. It takes about 7 to 10
seconds after turning the power switch or by pressing the RESET circuit before they are
uploaded to POP-XT.

And may cause errors in connection. Or upload code to not work as it should be.
But it does not affect the circuit board damage. Only the operation may malfunction or
incorrect.
94POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 1 : Display message on POP-BOT XT


controller
Activity 1-1 Hello World
(A1.1.1) Open the Arduino1.0. Type the Listing A1-1 and save as.

(A1.1.2) Turn on the robot. Connect USB cable between a robot and computer.

Connect with
USB-miniB cable computer's USB port

Computer
F
0
2
2
F
0
0
1

0
0
1

AT Mega32U 4

TB6612

POP-BOT XT

(A1.1.3) Select the correct hardware; select menu Tools > Board > POP-XT following the
picture below.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 95

#include <popxt.h> // Include the main library


void setup()
{
glcd(1,0,"Hello World"); // Show messsage on display
}
void loop()
{}

Code description
This code sends the message; Hello World to line 1 column 1 of POP-BOT XT display. It will
work only once because this code is located in the setup() function

Listing A1-1 : HelloWorld.ino; sketch file for displaying message on


the POP-BOT XT color display

(A1.1.4) Choose the serial port at menu Tools > Serial Port

(A1.1.5) Compile and upload the code or sketch to POP-BOT XT controller board by clicking

on button or select menu File > Upload

At the color LCD screen shows Hello World message.

Hello World 100 F


ATMega32U4

220 F

100
TB6612
96POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 1-2 Multiple line display


The graphic color display of POP-BOT XT controller board resolution is 128 x 160
pixels. It can display 21 of the 5 x 7 dot characters 16 lines (maximum at standard size) User
possible to set the line and column display via glcd command of the popxt.h library file.
The glcd command also supports the special character for setting the display position.
This activity will be demonstrate this features.

(A1.2.1) Open the Arduino1.0. Type the Listing A1-2 and save as.

(A1.2.2) Turn-on the robot. Connect USB cable between a robot and computer.

#include <popxt.h> // Include the main library


int i,j;
void setup()
{
glcdFillScreen(GLCD_WHITE); // Change backgrounbd color to white
setTextColor(GLCD_BLACK); // Set text color to black
setTextBackgroundColor(GLCD_WHITE); // Set text background color to white
for (i=0;i<16;i++) // Set loop 16 times
{
glcd(i,i,"Row %d ",i); // Display message ROWxx on each line
}
}
void loop()
{}

Code description
This sketch add 3 functions of the glcd library as follows :
1. glcdFillScreen - fill the background color of screen
2. setTextColor - set the text color
3. setTextBackground - set the text background color
After setting the display; send the message; Row following the line number that get from
increasing of i variable. The column also increase follows i parameter. Therefore, at the first line
shows Row0 message on column 0 and line 0. After that at the second line shows messge ;
Row1 at line 1 column 1. It run continue until finish on Row 15 column 15 and stop.

Listing A1-2 : MultipleTextLine.ino; sketch file for displaying


mutiple messages on each line of the POP-BOT XT color display
POP-BOT XT : The Arduino Compatible Mobile Robot kit 97

(A1.2.3) Compile and upload the code or sketch to POP-BOT XT controller board by clicking
on button or select menu File > Upload

The color LCD screen will show the messages from Row 0 to 15 in that order.

Row00 100 F
Row01
RRRow02
RRRRow03
RRRRRow04
RRRRRRow05
RRRRRRRow06
RRRRRRRRow07
RRRRRRRRRow08
ATMega32U4

RRRRRRRRRRow09
RRRRRRRRRRRow010
RRRRRRRRRRRRow011
RRRRRRRRRRRRRow012
RRRRRRRRRRRRRRow013
RRRRRRRRRRRRRRRow014 220 F
RRRRRRRRRRRRRRRRow015

100
TB6612
98POP-BOT XT : The Arduino Compatible Mobile Robot kit

Avtivity 1-3 Set size and display orientation


The default chararacter font size of POP-BOT XT display is the smallest. It is 6 x 10
dots (The real space is 5 x 7 dots). To adjust the font size to be bigger, it requiers the
setTextSize function of the popxt.h library file. The value assigned to a multiple of the
normal. For example :

setTextSize(2) refers double size of the font. It is 12 x 20 dots per character.

setTextSize(3) refers the 3 times of defualt size. It is 18 x 30 dots per character.

When the font size is bigger. Number of characters per line is decreased from 21
characters 16 lines. On the x2 size, tt will display 10 characters 8 lines.

In addition to change the font size. User coulde be change the orientation of the
display screen by using the function glcdMode (). The default is mode 0 (glcdMode (0)).
It is vertical orientation. For modes 1, 2 and 3 are applied, the display is orientated 90
degrees each. In mode 1 orientate 90 degrees, Mode 2 orientate 180 degrees and mode
3 orientate 270 degrees.

(A1.3.1) Open the Arduino1.0. Type the Listing A1-3 and save as.

#include <popxt.h>
int x,m;
void setup()
{
setTextColor(GLCD_RED); // Set text color to red
}
void loop()
{
for (x=1;x<6;x++)
{
setTextSize(x); // Set text size 2x
for(m=0;m<4;m++)
{
glcdClear(); // Clear screen
glcdMode(m); // Set display mode
glcd(0,0,"%dX",x); // Show text size
glcd(1,0,"M=%d",m); // Show mode number
sleep(500);
}
}
}

Listing A1-3 : SetText_FlipDisplay.ino; sketch file for testing font


size setting and orientation display
POP-BOT XT : The Arduino Compatible Mobile Robot kit 99

(A1.3.2) Turn-on the robot. Connect USB cable between a robot and computer.
(A1.3.3) Com p ile a nd up loa d the c od e o r ske tc h to PO P-BOTXT controller board by clicking
on button or select menu File > Upload

The graphic display of the POP-BOT XT controller board shows message of font size
and mode of orientation. Start with upper left, upper right, lower right and lower left corner.
Surrounding the display of the size are 1X, 2X, 3X, 4X and 5X each round will be show 4
orientation refer the M character message.

These are some example of the operation pictures.


M = 0 ; vertical M = 1 ; right orientate 90 degress
3X font size 4X font size

M = 2 ; orientate 180 degrees M = 3 ; orientate 270 degrees


The dispaly is inverted from Mode 0 5X font size
4X font size
100POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 1-4 Line art display


The main function of the color graphic LCD screen of the POP-BOT XT is glcd. This
function contains many subfunction for display message and create the line art graphic.
It includes :

glcdRect (int x1, int y1, int width, int height, uint color) :
draw a rectangle.

glcdFillRect (int x1, int y1, int width, int height, uint color)
: fill rectangle color.

glcdLine (int x1, int y1, int x2, int y2, uint color) : draw the line.

glcdCircle (int x, int y, int radius, uint color) : draw a circle.

glcdFillCircle (int x, int y, int radius, uint color) : fill circle


color.

glcdClear (uint color) : clear the display.

The testing program is shown in Listing A1-4, and then upload it to test with POP-BOT
XT controller board. The result is following the picture below.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 101

#include <popxt.h> // Include the main library


int i,j;
void setup()
{}
void loop()
{
glcdClear; // Clear screen and set to black color
sleep(300);
for (i=0;i<160;i+=4)
{
glcdLine(0,0,128,i,GLCD_WHITE); // Draw the white line from 0,0 to 128,i
}
for (i=0;i<128;i+=4)
{
glcdLine(0,0,i,160,GLCD_RED); // Draw the red line from 0,0 to i,160
}
sleep(2000);
glcdRect(32,40,64,80,GLCD_BLUE); // Draw the blue rectangle
sleep(300);
glcdFillCircle(32,40,31,GLCD_GREEN); // Fill the green circle
glcdFillCircle(96,40,31,GLCD_YELLOW); // Fill the yellow circle
glcdFillCircle(32,120,31,GLCD_MAGENTA); // Fill the magenta circle
glcdFillCircle(96,120,31,GLCD_SKY); // Fill the blue sky circle
sleep(1000);
glcdCircle(64,40,31,GLCD_GREEN); // Draw the green circle
glcdCircle(32,80,31,GLCD_BLUE); // Draw the blue circle
glcdCircle(64,120,31,GLCD_YELLOW); // Draw the yellow circle
glcdCircle(96,80,31,GLCD_SKY); // Draw the blue sky circle
sleep(1000);
glcdFillRect(0,0,128,160,GLCD_YELLOW); // Fill the yellow rectangle
sleep(1000);
}

Listing A1-4 : SimpleGraphic.ino; sketch file for testing the glcd


function
102POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 1-5 Draw a curve


Besides the circle and square, curve also is an essential ingredient in creating
graphics. The glcd function includes the curve drawing function. It is glcdArc (). It
requires many parameters for setting. See details in Chapter 7.

(A1.5.1) Open the Arduino1.0. Type the Listing A1-5 and save as.

(A1.5.2) Turn-on the robot. Connect USB cable between a robot and computer.
(A1.5.3) Compile and upload the code or sketch to POP-BOT XT controller board by clicking
on button or select menu File > Upload

#include <popxt.h>
int i;
// Smile face function
void face()
{
glcdFillCircle(64,70,50,GLCD_WHITE);
glcdArc(48,60,16,30,150,GLCD_RED);
glcdCircle(48,55,5,GLCD_BLUE);
glcdCircle(80,55,5,GLCD_BLUE);
glcdArc(80,60,16,30,150,GLCD_RED);
glcdFillCircle(64,70,7,GLCD_YELLOW);
glcdArc(64,80,30,220,320,GLCD_RED);
glcdArc(64,80,29,220,320,GLCD_RED);
}
void setup()
{}
void loop()
{
for(i=0;i<4;i++)
{
glcdClear();
glcdMode(i); // Flip display
face();
sleep(1000);
}
}

Listing A1-5 : SmileFace_ArcTest.ino; sketch for drawing the curve


POP-BOT XT : The Arduino Compatible Mobile Robot kit 103

(A1.5.4) Run this sketch on the POP-BOT XT.

The display shows an animated smiley face for a second, then rotate 90 degrees
and then back to the start page to run again and again.
104POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 2 : Sound driving


POP-XT has the sound driving device. It is a piezo speaker. It response at 300 to 3kHz
frequency range. The popxt.h library also available the function for sound driving. They
are beep () and sound () functions

In the Listing A2-1 is an example of the beep () function to drives a beep signal.

In the Listing A2-2 is an example of using the sound () function for generating the
different frequency signal.

Testing both listing with same procedures. Open the Arduino1.0 to create a new
sketch. Type the code folloiwng the Listing A2-1 and A2-2. Compile and upload to POP-XT
(POP-BOT XT controller board).

#include <popxt.h> // Include the main library


void setup()
{}
void loop()
{
beep(); // Beep signal to speaker
sleep(1000);
}

Listing A2-1 : BeepTest.ino ; sketch for beep() function demonstration

#include <popxt.h> // Include the main library


void setup()
{}
void loop()
{
sound(500,500); // Generate 500Hz signal 0.5 second interval
sound(2500,500); // Generate 2500Hz signal 0.5 second interval
}

Listing A2-2 : SoundTest.ino ; sketch for sound() function demonstration


POP-BOT XT : The Arduino Compatible Mobile Robot kit 105

Activity 3 : Reading the OK switch and KNOB


In the control system must be configured with the switch in the circuit to work Also
on POP-XT board provides a user interface as well. It includes a OK button and KNOB
buttons for the menu selecting.

Create the new sketch and type Listing A3-1. Save as KnobSwitchTest.ino. Then
compile nad upload to POP-BOT XT Controller board. Run to try the operation.

The display show message as follows

Press OK (2X font size)


Press the OK switch to start.

The controller board beeps a sound at once and change display to

Knob value (2X font size)

XXXX (3X font size)

therefore : xxxx is 80 to 1023 values

Try to turn a KNOB button

The Knob value will be changed following the adjustment

Press the OK switch again.

The controller board drives a 500Hz signal 0.5 second. It will drive this signal
everytime when the OK switch is pressed.
106POP-BOT XT : The Arduino Compatible Mobile Robot kit

#include <popxt.h> // Include the main library


void setup()
{
glcdClear; // Clear screen and sdt backgound to black
setTextSize(2); // Set text size is x2
glcd(1,0,"Press OK"); // Display the stat message
sw_ok_press(); // Check the OK switch pressing
beep(); // Drive the beep
glcdClear; // Clear screen and sdt backgound to black
}
void loop()
{
if (sw_ok()) // The OK switch is pressed ?
{
sound(500,500); // Drive 500Hz sound 0.5 second
// after the OK switch is pressed
}
glcd(1,0,"Knob value"); // Display the KNOB message on screen
setTextSize(3); // Change text size to x3
glcd(2,2,"%d ",knob()); // Display the KNOB value on screen
setTextSize(2); // Change trext size back to x2
}

Listing A3-1 : KnobSwitchTest.ino ; sketch file for testing the OK


and KNOB button operation.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 107

Activity 4 : Controlling simple output devices


In the popxt.h library file provides the function to send a logic 1 and 1 to output
port. It is out (int num, int _dat) function. This activity demonstrates the simple
outpuit device control. The simple deive is ZX-LED module.

The ZX-LED will on if the logic 1 is applied and off when the logic 0 is applied.

(A4.1) Connect 2 sets of ZX-LED to port 6/A7 and 4/A6.

ZX-LED

#include <popxt.h> // Include the main library


void setup()
{
setTextSize(2); // Set text size to 2x
glcd(1,1,"Press OK"); // Display start message
sw_ok_press(); // Check the OK switch pressing
}
void loop()
{
out(4,1); // Turn on LED at pin 4
out(6,0); // Turn off LED at pin 6
sleep(400);
out(4,0); // Turn off LED at pin 4
out(6,1); // Turn on LED at pin 6
sleep(400);
}

Listing 4-1 : LEDtest.ino ; sketch file for testing out() function to


controlling simple output devices
108POP-BOT XT : The Arduino Compatible Mobile Robot kit

(A4.2) Turn-on the robot. Connect USB cable between a robot and computer.

(A4.3) Compile and upload the code or sketch to POP-BOT XT controller board by clicking

on button or select menu File > Upload

(A4.3) Run the sketch and observe the ZX-LED operation.

The display of POP-BOT XT controller board shows start message :

Press OK
Then, press the OK switch for starting the operation.

Both ZX-LED blinks alternating continuously.


POP-BOT XT : The Arduino Compatible Mobile Robot kit 109

Chapter 7
POP-BOT XT library file
C/C++ program development with Arduino1.0 for POP-BOT XT is supported by the
popxt.h library file. With this library, user can create the control program for POP-BOT XT
easier and faster.

The sturcture of the popxt.h library file is shown below.

popxt.h library



































110POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.1 Sub-library of the popxt.h library file


glcd contains the functions and statements of the display message, number
and line art graphic on the color graphic LCD of POP-BOT XT (not support the image file)

sleep contains the function and statements of delayed time

in_out contains the functions and statements of reading digital input port and
sending digital data to digital output port.

analog contains the functions and statements of reading analog input.

sound contains the functions and statements of sound generation.

motor contains the functions and statements of DC motor driving.

servo contains the functions and statements of servo motor control

serial contains the functions and statements of serial data communication via
USB and TxD/RxD of the POP-BOT XT controller board.
To run the instructions for POP-BOT XT program development; developers have to
include popbot.h mainly library file at the beginning of the C/C++ code with this command
:
#include <popxt.h>
to declare the compiler know all statements of the popxt.h library.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 111

7.2 Main function details of the popxt.h library


7.2.1 Color graphic LCD function
7.2.1.1 glcd
It is the function for display message on the color graphic LCD screen. The default
display is 21 characters, 16 lines with smallest font size.

Syntax
void glcd(unsigned char x, unsigned char y ,char *p,...)

Parameter
x is line number. Value is 0 to 15

y is character position. Value is 0 to 20

*p is the display message and special character or symbol for determine the
display as follows :
%c or %C - display one character
%d or %D - display integer from -32,768 to 32,767
%l or %L - display integer from -2,147,483,648 to 2,147,483,647
%f or %F - display floating point ( 3-digit maximum)

Example 7-1
glcd(2,0,"Hello World");
// Show message; Hello World at left end position of line 2

100 F

HelloRWorld
RRRRow03
RRRRRow04
RRRRRRow05
RRRRRRRow06
RRRRRRRRow07

Example 7-2
int x=20;
glcd(1,2,"Value = %d",x); // Display both charater and number same line
// Start from column 2 of line 1

Row00 100 F
RRValueR=R20
RRRow02
RRRRow03
RRRRRow04
RRRRRRow05
RRRRRRRow06
RRRRRRRRow07
112POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.1.2 colorRGB
It is color changing function in RGB (Red Blue Green) format to 16-bit data. It divides
5-bit for Red , 6-bit for Green and last 5-bit for Blue.

Syntax
unsigned int colorRGB(uint red,uint green,uint blue)

Parameter
red - Red value is between 0 to 31. If applied data is greater than 31, adjsut to 31

green - Green value is between 0 to 63. If applied data is greater than 63,
adjust to 63

blue - Blue value is between 0 to 31. If applied data is greater than 31, adjsut to 31

Example 7-3
#include <popxt.h>
int colors;
void setup()
{
int colors;
colors=colorRGB(31,0,0); // Determine 16-bit data of red to
// variable colors
glcdFillScreen(colors); // Set the background screen to red
}
void loop()
{}

Row00 100 F
RRValueR=R20
RRRow02
RRRRow03
RRRRRow04
RRRRRRow05
RRRRRRRow06
RRRRRRRRow07
RRRRRRRRRow08
ATMega32U4

RRRRRRRRRRow09
RRRRRRRRRRRow010
RRRRRRRRRRRRow011
RRRRRRRRRRRRRow012
RRRRRRRRRRRRRRow013
RRRRRRRRRRRRRRRow014 220 F
RRRRRRRRRRRRRRRRow015

100
TB6612
POP-BOT XT : The Arduino Compatible Mobile Robot kit 113

7.2.1.3 color[ ]
It is array type variable. It is uesd for set the 8 basic colors. Developers can also use
color[] directly or use the color name.

Syntax
unsigned int color[]= { GLCD_RED,
GLCD_GREEN,
GLCD_BLUE,
GLCD_YELLOW,
GLCD_BLACK,
GLCD_WHITE,
GLCD_SKY,
GLCD_MAGENTA};

Parameter
GLCD_RED - Select red

GLCD_GREEN - Select grren

GLCD_BLUE - Select blue

GLCD_YELLOW - Select yellow

GLCD_BLACK - Select black

GLCD_WHITE - Select white

GLCD_SKY - Select sky blue color

GLCD_MAGENTA - Select magenta

Example 7-4
glcdFillScreen(color[5]) // Set background color to white

Example 7-5
glcdFillScreen(GLCD_BLUE) // Set background color to blue
114POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.1.4 setTextColor
This function is used to set the text color that diaply with glcd() function. The default
color is white.

Syntax
void setTextColor(unsigned int newColor)

Parameter
newColor - This is to set the target color. It is 16-bit data or variable data which is
defined from the variable color[]

Example 7-6
setTextColor(GLCD_YELLOW); // Set text color to yellow

7.2.1.5 setTextBackgroundColor
It is to set the text background color function. The default color is black. The text
background color is not screen background. Setting the scrren background color, need
to use the glcdFillScreen function.

Syntax
void setTextBackgroundColor(unsigned int newColor)

Parameter
newColor - This is to set the target color. It is 16-bit data or variable data which is
defined from the variable color[]

Example 7-7
setTextBackgroundColor(GLCD_GREEN);
// Set the text background color to green

Hello World 100 F


RRValueR=R20
RRRow02
RRRRow03
RRRRRow04
RRRRRRow05
RRRRRRRow06
RRRRRRR Row07
RRRRRRRRRow08
ATMega32U4

RRRRRRRRR Row09
RRRRRRRRRR Row010
RRRRRRRRRRR Row011
RRRRRRRRRRRR Row012
RRRRRRRRRRRRR Row013
RRRRRRRRRRRRRR Row014 220 F
POP-BOT XT : The Arduino Compatible Mobile Robot kit 115

7.2.1.6 glcdClear
It is clear screen function. The background color will be latest the text backgorund
color. If not defined before, the background color will be black

Syntax
void glcdClear()

Example 7-8
glcdClear(); // Clear all contents on the screen

7.2.1.7 glcdFillScreen
This will clear the scrren and change to the background color function. After
executing this function, all contents on scrren will be cleared and it will change to the
backgtround color to the target color.

Syntax
void glcdFillScreen(unsigned int color)

Parameter
color - The target color. It is 16-bit data or variable data which is defined from
the variable color[]

Example 7-9
glcdFillScreen(GLCD_BLUE);
// Clear screen and set background color to blue

[BLACK] [BLUE]
116POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.1.8 glcdMode
It is for setting the display orientation. There are 4 modes; 0 (0 degree), 1 (oritentate
right 90 degrees), 2 (orientate 180 degrees or invert) and 3 (orientate 270 degrees from
origin)

Syntax
glcdMode(unsigned int modeset)

Parameter
modeset - Orientation mode number. It is 0 to 3 for determine 0, 90, 180 and 270
degrees orientation. The default is 0 degree in vertical.

Example 7-10
#include <popxt.h>
void setup()
{
setTextSize(2); // 2X text sice
}
void loop()
{
glcdClear(); // Clear screen
glcdMode(0); // Set orientation display mode 0
glcd(0,0,POP-BOTXT); // Show message
sw_ok_press(); // Wait for OK pressing for changing
// the orientation diplay mode
glcdClear(); // After OK switch is pressed; clear screen
glcdMode(1); // Change orienatation display to mode 1
glcd(0,0,POP-BOTXT);
sw_ok_press();
glcdClear(); // After OK switch is pressed; clear screen
glcdMode(2); // Change orienatation display to mode 2
glcd(0,0,POP-BOTXT);
sw_ok_press();
glcdClear(); // After OK switch is pressed; clear screen
glcdMode(3); // Change orienatation display to mode 3
glcd(0,0,POP-BOTXT);
sw_ok_press();
}
POP-BOT XT : The Arduino Compatible Mobile Robot kit 117

7.2.1.9 setTextSize
This function is used to set the text size. The text size is 1x time by default. It requires
6 x 10 dots include character gap. With the default size, this display shows 21 characters
16 lines maximum in vertical.

Syntax
setTextSize(unsigned int newSize)

Parameter
newSize - times number of the default size. It is 1 to 16.

Example 7-11
#include <popxt.h>
void setup()
{
setTextSize(1); // Set text size to 1x
setTextColor(GLCD_GREEN); // Set text color to green
glcd(0,0,"Size1"); // Show message
setTextSize(2);
glcd(1,0,"Size2"); // Set text size to 2x
setTextSize(3);
glcd(2,0,"Size3"); // Set text size to 3x
setTextSize(4);
glcd(3,0,"Size4"); // Set text size to 4x
}
void loop()
{}
118POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.1.10 getTextColor
Get the current text color.

Syntax
unsigned int getTextColor()

Return value
textColor - It is 16-bit data. It refer colorRGB[] function

Example 7-12
unsigned int color;
color=getTextColor(); // Get the current color data to store in
// the color variable

7.2.1.11 getTextBackgroundColor
Get the current text background color.

Syntax
unsigned int getTextBackgroundColor()

Return value
textBackgroundColor - It is 16-bit data. It refer colorRGB[]function

Example 7-13
unsigned int color;
color=getTextBackgroundColor(); // Get and store the text color
// background to color variable

7.2.1.12 getTextSize
Get the currect text size.

Syntax
unsigned int getTextSize()

Return value
textSize - The size is times number from the default size. Range is 1 to 16.

Example 7-14
unsigned int textSize;
textSize=getTextSize(); // Store the current text size to textSize
// variable
POP-BOT XT : The Arduino Compatible Mobile Robot kit 119

7.2.1.13 glcdGetMode
Get the current orientation in display mode.

Syntax
unsigned int glcdGetMode()

Return value
mode - The orientation display mode number. It is 0 to 3. See details in glcdMode
function

Example 7-15
unsigned int Mode;
Mode=glcdGetMode(); // Get the current orientation display mode number

7.2.1.14 glcdPixel
This plots the dots on the coordinator of the display. It refers to 128 x 160 dots display.

Syntax
void glcdPixel(unsigned int x,unsigned int y,unsigned int color)

Parameter
x - Horizontal axis coordinator or x-axis. Value is 0 to 127.

y - Bertical axis coordinator or y-axis. Value is 0 to 159

color - The target color. It is 16-bit data or variable data which is defined from
the variable color[]

Example 7-16
#include <popxt.h>
int i;
void setup()
{
for (i=0;i<128;i+=4)
{
glcdPixel(i,80,GLCD_RED);
// Plot dot every 4 pixels on x-axis
// of center of the screen
}
for (i=0;i<160;i+=4)
{
glcdPixel(64,i,GLCD_RED);
// Plot dot every 4 pixels on y-axis
// of center of the screen
}
}
void loop()
{}
120POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.1.18 glcdRect
Draw the rectangular shape.

Syntax
void glcdRect(unsigned int x1,unsigned int y1,unsigned int
width,unsigned int height,unsigned int color)

Parameter
x1 - Start point of the rectangular shape on x-axis. Value is 0 to 127

y1 - Start point of the rectangular shape on y-axis. Value is 0 to 159

width - The width of rectangular shape. Value is 1 to 128

height - The height of rectangular shape. Value is 1 to 158

color - Line color. It is 16-bit data or variable data which is defined from the
variable color[]

Example 7-17
#include <popxt.h>
void setup()
{
glcdRect(32,40,64,80,GLCD_RED);
// Draw the red rectangle 64 x 80 pixels
}
void loop()
{}
POP-BOT XT : The Arduino Compatible Mobile Robot kit 121

7.2.1.19 glcdFillRect
This creates a filled rectangle. It is only fill color without an outline.

Syntax
void glcdFillRect(unsigned int x1, unsigned int y1, unsigned int
width, unsigned int height,unsigned int color)

Parameter
x1 - Start point of the rectangular shape on x-axis. Value is 0 to 127

y1 - Start point of the rectangular shape on y-axis. Value is 0 to 159

width - The width of rectangular shape. Value is 1 to 128

height - The height of rectangular shape. Value is 1 to 158

color - Fill color. It is 16-bit data or variable data which is defined from the variable
color[]

Example 7-18
#include <popxt.h>
void setup()
{
glcdFillRect(32,40,64,80,GLCD_RED);
// Create the solid red rectangle 64 x 80 pixels
}
void loop()
{}
122POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.1.20 glcdLine
Draw the straight line from point to point.

Syntax
void glcdLine(unsigned int x1, unsigned int y1, unsigned int x2,
unsigned int y2, unsigned int color)

Parameter
x1 - Start point on the x-axis. Value is 0 to 127.

y1 - Start point on the y-axis. Value is 0 ro 159

x2 - Destination point on the x-axis. Value is 0 to 127.

y2 - Destination point on the y-axis. Value is 0 ro 159

color - Line color. It is 16-bit data or variable data which is defined from the
variable color[]

Example 7-19
#include <popxt.h>
void setup()
{
glcdLine(0,0,127,159,GLCD_RED);
// Draw a red diagonal line from top left to bottom right
}
void loop()
{}
POP-BOT XT : The Arduino Compatible Mobile Robot kit 123

7.2.1.21 glcdCircle
Draw a circle function.

Syntax
void glcdCircle(unsgined int x, unsgined int y, unsgined int
radius,unsgined int color)

Parameter
x - Center of thge circle coordinator on x-axis. Value is 0 to 127

y - Center of thge circle coordinator on y-axis. Value is 0 to 159

radius - Radius value

color - Circumference color. It is 16-bit data or variable data which is defined


from the variable color[]

Example 7-20
#include <popxt.h>
void setup()
{
glcdCircle(32,120,31,GLCD_MAGENTA);
// Draw a magenta circle with 31 pixels radius
}
void loop()
{}
124POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.1.22 glcdFillCircle
Creates a filled circle without the circumference.

Syntax
void glcdFillCircle(unsigned int x, unsigned int y, unsigned int
radius, unsigned int color)

Parameter
x - Center of thge circle coordinator on x-axis. Value is 0 to 127

y - Center of thge circle coordinator on y-axis. Value is 0 to 159

radius - Radius value

color - Circle color. It is 16-bit data or variable data which is defined from the
variable color[]

Example 7-21
#include <popxt.h>
void setup()
{
glcdFillCircle(32,120,31,GLCD_MAGENTA);
// Create the solid magenta circle with radius 31 pixels
}
void loop()
{}
POP-BOT XT : The Arduino Compatible Mobile Robot kit 125

7.2.1.23 glcdArc
Draw the arc line function.

Syntax
void glcdArc(unsigned int x,unsigned int y, unsigned int r, int
start_angle, int end_angle, uint color)

Parameter
x - Center of thge circle coordinator on x-axis. Value is 0 to 127

y - Center of thge circle coordinator on y-axis. Value is 0 to 159

radius - Radius value of the arc

start_angle - Start angle of the arc

end_angle - Ending angle of the arc

color - Arc line color. It is 16-bit data or variable data which is defined from the
variable color[]

Example 7-22
#include <popxt.h>
void setup()
{
glcdArc(48,80,16,30,150,GLCD_RED);
glcdCircle(48,75,5,GLCD_BLUE);
glcdCircle(80,75,5,GLCD_BLUE);
glcdArc(80,80,16,30,150,GLCD_RED);
glcdFillCircle(64,90,7,GLCD_GREEN);
glcdArc(64,100,30,220,320,GLCD_RED);
}
void loop()
{}
126POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.2 Time function


7.2.2.1 sleep and delay
Delay time function in millisecond unit. Time value is an approximation.

Syntax
void sleep(unsigned int ms)
void delay(unsigned int ms)

Parameter
ms - Delay time in millisecond unit. Value is 0 to 65,535

Example 7-23
sleep(20); // Delay 20 milliseconds
delay(1000); // Delay 1 second

7.2.2.2 delay_us
Delay time function in microsecond unit. Time value is an approximation.

Syntax
void delay_us(unsigned int us)

Parameter
ms - Delay time in microsecond unit. Value is 0 to 65,535

Example 7-24
delay_us(100); // Delay 100 microseconds
POP-BOT XT : The Arduino Compatible Mobile Robot kit 127

7.2.3 Sound generation function


7.2.3.1 beep
This is a beep function. The beep signal is a 500Hz frequency sqaure wave signal.
Duration is 100 millisecond. This sginal is driven to the piezo speaker on the POP-BOT XT
controller board.

Syntax
void beep()

Example 7-25
beep(); // Drives the bepp signal at once.

7.2.3.2 sound
This is sound generation function. It allow developers to set the frequency and time
period.

Syntax
void sound(int freq,int time)

Parameter
freq - Frequnecy value in Hertz. Value is 0 to 32,787

time - Time period in millisecond. Value is 1 to 32,787

Example 7-26
sound(1200,500);
// Drives the signal 1200Hz 500ms to piezo speaker of the POP-BOT XT.
128POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.4 Input/Ouput port function


7.2.4.1 in
Reading the digital input port function.

Syntax
char in(x)

Parameter
x - Digial input port number

Return value
0 or 1
Example 7-27
char x; // Declare the x variable for storing the result
x = in(2); // Read data from the digital input port 2 to store in
// x variable

7.2.4.2 out
Out the digital value to the defined digital output port.

Syntax
out(char _bit,char _dat)

Parameter
_bit - Output pin port

Example 7-28
out(4,1); // Set port 4/A6 as output digital and out with data 1
out(6,0); // Set port 6/A7 as output digital and out with data 0

7.2.5 Sensor function


7.2.5.1 analog
Read the analog input port; A0 to A7

Syntax
unsigned int analog(unsigned char channel)

Parameter
channel - Analog input port. Value is 0 to 7. It is A0 to A7 port.

Return value
The converted digial data. It is 0 to 1023 from 10-bit analog to digital converter.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 129

7.2.5.2 knob
Read the KNOB button data of the POP-BOT XT controller board.

Syntax
unsigned int knob()

Return value
80 to 1023
Example 7-29
int val=0; // Declare variable to data storing
val=knob(); // Read data from the KNOB of POP-XT board to store to
// val variable

7.2.5.3 sw_ok()
Read status of the OK switch on the POP-BOT XT controller board (POP-XT board)

Syntax
unsigned char sw_ok()

Return value
1 (true) when the switch is pressed

0 (false) no press the switch

Note : Pressing the OK switch effects to KNOB value as 0 (zero)

Example 7-30
if(sw_ok())
{
beep(); // Beep after the OK switch is pressed
}

7.2.5.4 sw_ok_press()
Loop to check the OK switch pressing function

Example 7-31
........
sw_ok_press(); // Loop until the OK switch is pressed
......
130POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.6 DC motor control function


7.2.6.1 motor
Drive the DC motor function

Syntax
void motor(char _channel,int _power)

Parameter
_channel - DC motor output (1 or 2)

_power - Power value. It is -100 to 100

If set _power as positive value (1 to 100), motor moves forward

If set_power as negative value (-1 to -100), motor moves backward

If set as 0, motor stop but not recommended. Please choose the


motor_stop function better.

Example 7-32
motor(1,60); // Drive motor A with 80% power
motor(1,-60); // Drive motor A backward with 80% power

Example 7-33
motor(2,100); // Drive motor B with 100% power

7.2.6.2 motor_stop
Stop motor driving function

Syntax
void motor_stop(char _channel)

Parameter
_channel - DC motor output (1, 2 and ALL)

Example 7-34
motor_stop(1); // Stop motor A
motor_stop(2); // Stop motor B

Example 7-35
motor_stop(ALL); // Stop all motor
POP-BOT XT : The Arduino Compatible Mobile Robot kit 131

7.2.6.3 fd
Move forward function. It is to move the robot forward.

Syntax
fd(unsigned int speed)

Parameter
speed - percentage of motor power (0 to 100%)

Example 7-36
fd(60); // Robot moves forward with 80% power

7.2.6.4 fd2
This full name of this function is forward2. It is a dependent function of the motor
control command for forward.

Syntax
fd2(unsigned int speed1, unsigned int speed2)

Parameter
speed1 - Speed of motor A (0 to 100%)

speed2 - Speed of motor B (0 to 100%)

Example 7-37
fd2(30,80); // Move the robot in circle shape.
// Because the speed of motor B is greater than motor A

7.2.6.5 bk
Move backward function. It is to move the robot backward.

Syntax
bk(unsigned int speed)

Parameter
speed - percentage of motor power (0 to 100%)

Example 7-38
bk(90); // Robot moves backward with 90% power
132POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.6.6 bk2
This full name of this function is backward2. It is a dependant function of the motor
control command for backward.

Syntax
bk2(unsigned int speed1 ,unsigned int speed2)

Parameter
speed1 - Speed of motor A (0 to 100%)
speed2 - Speed of motor B (0 to 100%)

Example 7-39
bk2(80,80); // Move backward both motor with same power

Both fd2() and bk2() functions help and adjust the motor speed for improving
the robot moving. Normally each motor speed is not equal 100%. It is some different. With
these function, user possible to adjust the different speed for each motor to adjust the
moving direction to more straight.

7.2.6.7 tl and tr
They are from turn left (tl) and turn right (tr). The turning method is stop one motor
and move another one. The tunring point is the stop wheel.

Syntax
tl(unsigned int speed) / tr(unsigned int speed)
Parameter
speed - Speed of motor (0 to 100%)

Example 7-40
tl(60); // Turn left with 80% power
tr(100); // Turn right with full speed

7.2.6.8 sl and sr
They are from spin left (sl) and spin right (sr). This function control each motor turn in
opposit direction. The turning point is the center of robot

Syntax
sl(unsigned int speed) / sr(unsigned int speed)
Parameter
speed - Speed of motor (0 to 100%)

Example 7-41
sl(70); // Root spin left with 70% power
sr(100); // Robot spin right with full speed
POP-BOT XT : The Arduino Compatible Mobile Robot kit 133

7.2.6.9 ao
It is to off all motor function.

Syntax
ao()

Example 7-42
void setup()
{
fd(100); // Robot moves forward with full speed
sleep(2000); // in 2 seconds
ao(); // Stop all motors
}

7.2.7 Servo motor library


There is one function. It is servo.

Syntax
void servo(unsigned char _ch, int _pos)

Parameter
_ch - Servo motor output (1 to 3)

_pos - Set the sevo motor shaft poistion (0 to 180 and -1)

If set to -1, disable selected servo motor output


134POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.2.8 Serial data communication library


It is library that contains function and statement for supporting the serial data
communication with UART of micontroller

7.2.8.1 Hardware interface


UART0
Connect the POP-BOT XT controller obard with USB port of the computer. It is same
port for uploading.

UART1
Connect the interface cable to RXD1 (port 2) and TXD1 (port 3)

7.2.8.2 uart
This is serial data sending function via UART0 port.

Syntax
void uart(char *p,...)

Parameter
*p - Type of data. Support the special character for setting display method.

Command Operation
%c or %C Display 1 character
%d or %D Display the decimal value -32,768 to +32,767
%l or %L Display the decimal value -2,147,483,648 to +2,147,483,647
%f or %F Display floating point 3 digits
\r Set the message left justify of the line
\n Display message on the new line

7.2.8.3 uart_set_baud
This is baud rate setting function for UART0.

Syntax
void uart_set_baud(unsigned int baud)

Parameter
baud - Baud rate of UART0 2400 to 115,200

Example 7-43
uart_set_baud(4800); // Set baud rate as 4,800 bit per second

7.2.8.4 uart_available
POP-BOT XT : The Arduino Compatible Mobile Robot kit 135

This is receiveing data testing function of UART0.

Syntax
unsigned char uart_available(void)

Return value
- 0 : no data received
- more than 0 : received character

Example 7-44
char x =uart_available();
// Check the recieving data of UART0.
// If x value is more than 0; it means UART0 get any data.
// Read it by using uart_getkey function in the order next immediately.

7.2.8.5 uart_getkey
This is data reading function from receivers buffer of UART0

Syntax
char uart_getkey(void)

Return value
- 0 : no data received
- data : received character in ASCII code

Example 7-45
#include <popxt.h> // Include library
void setup()
{
glcdClear(); // Clear screen
setTextSize(2); // Set text sixe 2x
glcdMode(1); // Selectr orientation display mode 1
}
void loop()
{
if(uart_available()) // Check incoming data
{
if(uart_getkey()=='a') // Is it a ?
{
glcd(1,0,"Key a Active!");
// Reply message after get the a key
sleep(1000); // Delay 1 second
}
else
{
glcdClear; // Clear screen
}
}
}
136POP-BOT XT : The Arduino Compatible Mobile Robot kit

When run this program, Serial Monitor window od Arduno1.0 IDE is appeared.
Select the ending message with No line ending, baud rate is 115200 and uncheck at
Autoscroll box. Next, type a character and click on the Send button to send data from
your computer to the POP-XT board via USB port that is configured to run as a virtual COM
port over USB or USB Serial port

After POP-XT board get the a character, it shows message Key a Active!
on th color GLCD screen
POP-BOT XT : The Arduino Compatible Mobile Robot kit 137

7.2.8.6 uart1
This is serial data sending function via UART1 port. The default baud rate is 9,600 bit
per second.

Syntax
void uart1(char *p,...)

Parameter
*p - Type of data. Support the special character for setting display method. See
details in uart0 function.

7.2.8.7 uart1_set_baud
This is baud rate setting function for UART1.

Syntax
void uart1_set_baud(unsigned int baud)

Parameter
baud - Baud rate of UART1 2400 to 115,200

Example 7-46
uart1_set_baud(19200); // Set baud rate as 19,200 bit per second

7.2.8.8 uart1_available
This is receiving data testing function of UART1

Syntax
unsigned char uart1_available(void)

Return value
- 0 : no data received
- more than 0 : received character

7.2.8.9 uart1_getkey
This is data reading function from receivers buffer of UART1.

Syntax
char uart1_getkey(void)

Return value
- 0 : no data received
- data : received character in ASCII code
138POP-BOT XT : The Arduino Compatible Mobile Robot kit

7.3 GP2D120 Infrared ranger library


In addition, the library file popxt.h that is the main library . The POP-BOT XT robots
also have a library for communicating with sensors and other special functions of the
robot that is not included in the main library popxt.h. Therefore developers must include
at the beginning of the code or sketch.

POP-BOT XT Standard kit provides a module GP2D120 infrared ranger. To working


with it, require a ligrary file gp2d120_lib.h.

To using this library, must include at the beginning of the program with this statement :

#include <gp2d120_lib.h>
About hardware inrerfacing, connect this sensor to any analog port of the POP-BOT
XT. They are A0 to A7.

7.3.1 getdist
Get distance value from GP2D120.

Syntax
unsigned int getdist(char adc_ch)

Parameter
adc_ch - Analog port that connect with GP2D120 (A0 to A7)

Return value
Distance in centimetre unit

Example 7-47
dist = getdist(3); // Read distance from GP1D120 at A3 port
POP-BOT XT : The Arduino Compatible Mobile Robot kit 139

Chapter 8
POP-BOT XT movement control
The POP-BOT XT has 2 channels of DC motor drivers. You can control the speed
and direction of DC motor rotation with the software. Because DC motor is driven by PWM
(Pulse width modulation) signal. In this section describe how to drive DC motor with PWM
and how to generate PWM signal of POP-XT board with C/C++ programming and Arduino.

8.1 Basic operation of driving DC motor with PWM


By changing (modulating) the width of the pulse applied to the DC motor we can
increase or decrease the amount of power provided to the motor, thereby increasing or
decreasing the motor speed. Notice that, although the voltage has a fixed amplitude, it
has a variable duty cycle. That means the wider the pulse, the higher the speed.

Refer Figure 8 -1, the Vs supplies PWM signal to DC motor. The speed is dependent
on Ton time (ON time of motor). At this time, DC motor will receive the full voltage; Vm. If
Tons width is more, DC motor is received more voltage. It rotate in high speed. The ratio
of Ton time in percentage with period (T) is called Duty cycle. You can calculate this as
follows :

Ton
% duty cycle = 100 ................................................................(8.1)
Ton Toff

1 1
PWM frequency = ....................................................................(8.2)
Ton Toff T
Average DC motor voltage drop = Supply voltage x duty cycle (%) ............(8.3)

Rs
Vm

Vm t
Vs M Ton

Toff

Figure 8-1 : The PWM signal for driving DC motor


140POP-BOT XT : The Arduino Compatible Mobile Robot kit

Vm (V)

(A) 4.5 Duty cycle = 4 x 100% = 20%


20
t (ms) Average voltage = 4.5 x 20% = 0.9V
4 8 12 16 20 24 28 32
Vm (V)
10ms

(B) 4.5
Duty cycle = 10 x 100% = 50%
20
t (ms) Average voltage = 4.5 x 50% = 2.25V
4 8 12 16 20 24 28 32
Vm (V)
18ms

(C 4.5 Duty cycle = 18 x 100% = 90%


20
t (ms) Average voltage = 4.5 x 90% = 4.05V
4 8 12 16 20 24 28 32

Vm (V)

20ms Duty cycle = 20 x 100% = 100%


(D) 4.5 20
Average voltage = 4.5 x 100% = 4.5V
t (ms)
4 8 12 16 20 24 28 32

Figure 8-2 : Shows the relation between the different duty cycle
and voltage accross the DC motor.

Although the duty cycle is determine the motor speed. But DC motor can operate
at limit frequency. If the PWM frequrency is over the limit, DC motor will stop because its
operation reach to saturation point. The example PWM signal in figure 8-2 has 20 milliseconds
period and 50Hz frequency.

In Figure 8-2 (A) the PWM duty cycle is 20%. Motor will rotate with lowest speed
because the voltage drop is only 0.9V.When increase the duty cycle in Figure 8-2 (B) and
(C), voltage is applied to DC motor increase. Its speed is increase too.

In Figure 8-2 (D) the voltage is applied to DC motor full level because duty cycle is
100%. Thus, controlling the PWM duty cycle is a method of motor speed control.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 141

8.2 Arduino with PWM


Arduino has a special function to generate PWM signal and outs to any digital pins.
It is analogWrite(). User can adjust PWM duty cycle from 0 to 100% with value between
0 to 255.

At value = 0, no PWM signal is occured. Voltage output as 0V.

At value = 51, The PWM signal has positive pulse width 20% of period. The duty
cycle is equal to 20%.

At value = 127, The PWM signal has positive pulse width half of period. The duty
cycle is equal to 50%.

At value = 191, The PWM signal has positive pulse width 75% of period. The duty
cycle is equal to 75%.

At value = 255, The PWM signal has full positive pulse width. The duty cycle is
equal to 100%.

The figure 8-3 shows the PWM signal at any duty cycle.

0%

20%

50%

75%

100%

Figure 8-3 : Shows the PWM signal at any duty cycle.


142POP-BOT XT : The Arduino Compatible Mobile Robot kit

Output voltage of PWM signal is average value relate the duty cycle. You can
calcualte from this relation below :

Output_voltage = (on_time / off_time) x max_voltage

We can use the PWM signal from analogWrite() function to adjust the LED brightness
or amplify to drive the DC motor. The Arduinos pin that assigned to PWM output will out
the PWM continue until do the analogWrite() function in new period or excecute
digitalRead and digitalWrite funtion at same pin.

For Arduino Leonardo hardware (the POP-XT board is also compatible) has 5 analog
output pins; it includes pin 3, 5, 9, 10 and 11. However the POP-XT board assign pin 5, 9 and
10 to connect the motor control circuit both DC motor and servo motor. The pin 3 is assigned
to SDA pin for I2C bus and pin 11 is connected with piezo speaker.

The analogWrite function fornat is


analogWrite(pin,value);
Therefore; pin as The Arduino Leonardos port pin 3, 5, 9, 10 and 11

value as Duty cycle value 0 to 255.

8.3 DC motor function for POP-BOT XT


The programming language C / C + + to drive the motors of the robot POP-BOT XT
has been made easier with DC motor function in the popxt.h library file. Summary of all
functions are as follows :

motor(_channel,_power); Select the motor output and set speed.

motor_stop(_channel); Stop motor operation

fd(speed); Move forward

bk(speed); Move backward

tl(speed); Turn left

tr(speed); Turn right

sl(speed); Spin left

sr(speed); Spin right

ao(); Break all motors


POP-BOT XT : The Arduino Compatible Mobile Robot kit 143

8.3.1 motor
Drive the DC motor function

Syntax
void motor(char _channel,int _power)
Parameter
_channel - DC motor output (1 or 2)
_power - Power value. It is -100 to 100
If set _power as positive value (1 to 100), motor moves forward
If set_power as negative value (-1 to -100), motor moves backward
If set as 0, motor stop but not recommended. Please choose the
motor_stop function better.

Example 8-1
motor(1,60); // Drive motor A with 80% power
motor(1,-60); // Drive motor A backward with 80% power

Example 8-2
motor(2,100); // Drive motor B with 100% power

8.3.2 motor_stop
Stop motor driving function
Syntax
void motor_stop(char _channel)
Parameter
_channel - DC motor output (1, 2 and ALL)
Example 8-3
motor_stop(1); // Stop motor A
motor_stop(2); // Stop motor B

Example 8-4
motor_stop(ALL); // Stop all motor

8.3.3 fd
Move forward function. It is to move the robot forward.

Syntax
fd(unsigned int speed)
Parameter
speed - percentage of motor power (0 to 100%)

Example 8-5
fd(60); // Robot moves forward with 80% power
144POP-BOT XT : The Arduino Compatible Mobile Robot kit

8.3.4 fd2
This full name of this function is forward2. It is a dependent function of the motor
control command for forward.

Syntax
fd2(unsigned int speed1, unsigned int speed2)
Parameter
speed1 - Speed of motor A (0 to 100%)
speed2 - Speed of motor B (0 to 100%)

Example 8-6
fd2(30,80); // Move the robot in circle shape.
// Because the speed of motor B is greater than motor A

8.3.5 bk
Move backward function. It is to move the robot backward.
Syntax
bk(unsigned int speed)
Parameter
speed - percentage of motor power (0 to 100%)

Example 8-7
bk(90); // Robot moves backward with 90% power

8.3.6 bk2
This full name of this function is backward2. It is a dependant function of the motor
control command for backward.

Syntax
bk2(unsigned int speed1 ,unsigned int speed2)

Parameter
speed1 - Speed of motor A (0 to 100%)
speed2 - Speed of motor B (0 to 100%)

Example 8-8
bk2(80,80); // Move backward both motor with same power

Both fd2() and bk2() functions help and adjust the motor speed for improving
the robot moving. Normally each motor speed is not equal 100%. It is some different. With
these function, user possible to adjust the different speed for each motor to adjust the
moving direction to more straight.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 145

8.3.7 tl and tr
They are from turn left (tl) and turn right (tr). The turning method is stop one motor
and move another one. The tunring point is the stop wheel.

Syntax
tl(unsigned int speed) / tr(unsigned int speed)
Parameter
speed - Speed of motor (0 to 100%)

Example 8-9
tl(60); // Turn left with 80% power
tr(100); // Turn right with full speed

8.3.8 sl and sr
They are from spin left (sl) and spin right (sr). This function control each motor turn in
opposit direction. The turning point is the center of robot

Syntax
sl(unsigned int speed) / sr(unsigned int speed)
Parameter
speed - Speed of motor (0 to 100%)
Example 8-10
sl(70); // Root spin left with 70% power
sr(100); // Robot spin right with full speed

8.3.9 ao
It is to off all motor function.

Syntax
ao()

Example 8-11
void setup()
{
fd(100); // Robot moves forward with full speed
sleep(2000); // in 2 seconds
ao(); // Stop all motors
}
146POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 5 : POP-BOT XT basic movement

Activity 5-1 Forward and Backward movement


A5.1.1 Open the Arduino IDE and create the sketch code from Listing A5-1.

A5.1.2 Upload the sketch to the robot.

A5.1.3 Turn-off power and Remove the download cable.

A5.1.4 Make sure the robot is on a flat surface. Turn-on the power and observe the
operation.

The POP-BOT XT moves forward. See both LED motor indicators light in green color.
After 1 second, both indicators change color to red and the robot moves backward.

If this is incorrect you will need to re-connect the motor cable to its opposite port /
polarity. Do this until your robot moves correctly. Once its done, Use this motor port
configuration for all your programming activities from now on. The robot will move forward
and backward continually until you turn off its power.

#include <popxt.h>
void setup()
{}
void loop()
{
fd(80);
sleep(1000);
bk(80);
sleep(1000);
}

Listing A5-1 : ForwardBackward.ino ; sketch file for simple movement


control for POP-BOT XT
POP-BOT XT : The Arduino Compatible Mobile Robot kit 147

Activity 5-2 Circle-shape movement control


With setting the different speed for each motor, it cause the robot move in circle-
shape. You can try with this procedure as follows :

A5.2.1 Create a new sketch file and write the following C Codes shown in Listing A5-2.

A5.2.2 Upload the sketch to the robot.

A5.2.3 Turn-off power and Remove the download cable.

A5.2.4 Make sure the robot is on a flat surface. Turn-on the power and observe the robot.

The robot moves with circle-shape continually until you press the OK button on the
POP-BOT XT controller board to stop the robot movement.

#include <popxt.h>
void setup()
{
fd2(30,90);
sw_ok_press();
ao();
}
void loop()
{}

Listing A5-2 : CircleMove.ino; sketch for circle-shape movement of


the POP-BOT XT
148POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 5-3 Square-shape movement control


A5.3.1 Create a new sketch file and write the following C Codes shown in Listing A5-3.
A 5.3.2 Upload the sketch to the robot. Turn-off power and Remove the download cable.
A5.3.3 Turn-on the power and observe the robot.

The robot will be activated if the OK button on the robot is being pressed. The
robot will move forward and turn right continually to make the square routing.

#include <popxt.h> // Include Library for POP-BOT XT


void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Start message
glcd(2,1,"to Start");
sw_ok_press(); // Check OK switch pressing to start
glcdClear(); // Clear screen
glcd(1,1,"Moving..."); // Operation message
}

void loop()
{
fd(80); // Forward with 80% power
sleep(900); // Forward time
tr(80); // Turn right with 80% power
sleep(400); // Turn right time
}

Listing A5- 3 : RectangleMove.ino ; sketch file for rectangle-shape


movement of the POP-BOT XT robot
POP-BOT XT : The Arduino Compatible Mobile Robot kit 149

Activity 5-4 Multi-direction movement


The Listing 5-4 is sketch for control the robot to move on any direction. It includes
forward 0.6 second, turn left 0.4 second, backward 0.6 second, spin right 0.3 second,
backward again 0.6 second, spin left 0.3 second and back to repeat again continually.

#include <popxt.h> // Include the main library


void setup()
{
glcdClear(); // Clear screen and set to black
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
glcd(2,1,"to Start");
sw_ok_press(); // Loop for OK switch pressing
beep(); // Drive the beep signal
glcdClear(); // Clear screen and set to black
}
void loop()
{
glcdFillScreen(GLCD_RED); // Clear screen and set to red
fd(80); // Move forward with 80% power
sleep(600); // and 0.6 second
glcdFillScreen(GLCD_GREEN); // Clear screen and set to green
tl(60); // Turn left with 60% power
sleep(400); // and 0.4 second
glcdFillScreen(GLCD_BLUE); // Clear screen and set to blue
bk(80); // Backward with 80% power
sleep(600); // and 0.6 second
glcdFillScreen(GLCD_YELLOW); // Clear screen and set to yellow
sr(60); // Spin right with 60% power
sleep(300); // and 0.3 second
glcdFillScreen(GLCD_MAGENTA); // Clear screen and set to margenta
bk(80); // Backward with 80% power
sleep(600); // and 0.6 second
glcdFillScreen(GLCD_WHITE); // Clear screen and set to white
sl(60); // Spin left with 60% power
sleep(300); // and 0.3 second
}

Listing A5 -4 : MultiDirectionMove.ino ; sketch file for moving with


multi-direction of the POP-BOT XT
150POP-BOT XT : The Arduino Compatible Mobile Robot kit

After upload the sketch, turn off power and remove the USB cable. Place the robot
on the flat floor. Turn on power. The display of the robot show title message :

Press OK

to Start
Press the OK buttton on the robot. The POP-BOT XT begins to move. When it change
direction, the screen color will change following to report the direction changing.

Activity 5-5 Improve the straight movement of POP-BOT XT


with fd2() and bk2() function
The function fd2(speed1,speed2) and bk2(speed1,speed2)are DC motro control
functions similar fd() and bk() functions. The different are fd2() and bk2() have 2
more parameters to set the speed of each mortor independent.

The inequality of the motor may result in the movement of the robot can be tilted
to one side. With separate speed setting of each motor in fd2() and bk2() functions, it
compensates the different speed of each motor. The result is robot possible to move more
straight.

Listing A5-5 is simple program that use the simple statements to control the robot
moves forward by adjusting each motor speed with fd2() and bk2() function. The robot
will move forward straight as possible.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 151

#include <popxt.h> // Include the main library


void setup()
{
glcdClear(); // Clear screen and set to black
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
glcd(2,1,"to Start");
sw_ok_press(); // Wait for OK switch pressed
glcdClear();
glcd(1,1,"Moving..."); // Show operation message
fd2(70,70); // Move the robot forward with 70% power
}
void loop()
{}

Listing A5 -5 : MoveAlignment.ino ; sketch for speed adjusting with


fd2()and bk2() function to improve the robots movement to
more straight.

After uplaoding, see the robot movement.

Senarion 1 : robot move slant to left

It means the left DC motor speed is slower than the rigfht DC motor. Solution is
increase the left DC motor speed by adjusting at speed1 parameter of fd2() function.

Senarion 2 : robot move slant to right

It means the right DC motor speed is slower than the left DC motor. Solution is
increase the right DC motor speed by adjusting at speed2 parameter of fd2() function.
152POP-BOT XT : The Arduino Compatible Mobile Robot kit
POP-BOT XT : The Arduino Compatible Mobile Robot kit 153

Chapter 9
Object avoidance by contact
For proper movement of the robot, you will need to learn about taking in readings
from sensors and then to determine the outcome movements based on conditions set by
the robots code. The most basic sensor in robotics is the switch sensor. This chapter will
explain about to ussage of the switch sensor and it helps the robot to avoid collisions.

In POP-BOT XT robot kit, comes with 2 switch sensors; ZX-01. The schematic diagram
of this sensor is shown in the figure 9-1. When the switch is pressed (it means it has touched
or collided with an object. The logic output changes from 1 to 0 until the release of
the switch. Once the switch is release, the output signal is converted back to a 1 again.

This sensor is used to determine the conditions encountered by the robot. The
switches are installed at the front of the robot. Once the switch is pressed, the micro-
controller will drive the robot to move backwards and change its direction. The robot will
be able to move through obstacles.

LED1 Indicator +V

R2
10k
R1
510 R3
220 DATA
Operation :
If the switch is pressed; the logic
Signal output
0I is sent to output and the red S1
LED is on. GND
Switch
If no pressing, output is logic 1
and LED is off.

Figure 9-1 : ZX-01 switch sensor of the POP-BOT XT schematic and


operation details.
154POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 6 : Switch sensor testing


This activity presents a simple program to test the switch sensor operation. Get the
switch status to drive a beep to the piezo speaker

(A6.1) Connect the ZX-01 switch sensor to port 22/A4 and 23/A5 of the POP-BOT XT controller
board.

Press OK
to Start
ATMega32U4

100
TB6612

(A6.2) Open Arduino1.0 IDE. Type the Listing A6-1 and save as TouchSwitchTest.ino file.

(A6.3) Turn-on the robot. Connect the USB cable between the robot and the computer.

(A6.4) Compile and upload the code or sketch to POP-BOT XT controller board by clicking

on button or select menu File > Upload

(A6.5) Run the sketch. At the robots display, it shows message :

Press OK

to Start
Press the OK switch on the robot to start
POP-BOT XT : The Arduino Compatible Mobile Robot kit 155

Try pressing the ZX-01 switch sensor at port 22/A4.

The 1kHz signal is driven to piezo speaker 0.3 second and the background screen
color is change to red. If still press the switch, the signal also is driven continually

Try pressing the ZX-01 switch sensor at port 23/A5.

The 2kHz signal also is driven with 0.3 second period and display color is yellow.

#include <popxt.h> // Include the main library


void setup()
{
glcdClear(); // Clear screen and set to black
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
glcd(2,1,"to Start");
sw_ok_press(); // Wait for OK switch pressed
glcdClear();
glcd(1,1,"Let's go!"); // Show operation message
}
void loop()
{
if(in(22)==0) // If swtich at pin 22 is pressed
{
sound(1000,300); // Generate the 1kHz signal
glcdFillScreen(GLCD_RED); // Change the screen color to red
}
if(in(23)==0) // If switch at pin 23 is pressed
{
sound(2000,300); // Generate the 2kHz signal
glcdFillScreen(GLCD_YELLOW); // Change the screen color to yellow
}
}

Listing A6-1 : TouchSwitchTest.ino ; sketch file for testing the ZX-


01 switch sensor operation
156POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 7 : Wired remote control


Install 2 switches for the mobile robot for the 4 scenarios as follows :

1. No switches pressed : the robot stops. Does not move.

2. Both switches are pressed in the same time : the robot moves forward.

3. The left switch that is connected with port 22/A4 is pressed only : the robot
turns left

4. The right switch that is connected with port 23/A5 is pressed only : the robot
turns right.

#include <popxt.h> // Include the main library


void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
glcd(2,1,"to Start");
sw_ok_press(); // Wait for OK switch pressed
glcdClear();
glcd(1,1,"Let's go!"); // Show operation message
}
void loop()
{
if(in(22)==0&&in(23)==0) // Both switches are pressed ?
{
fd(60); // If correct, move forward with 60% power
}
else if(in(22)==0) // Only switch at pin22 is pressed ?
{
tl(60); // If correct, turn left with 60% power
}
else if(in(23)==0) // Only switch at pin23 is pressed ?
{
tr(60); // If correct, turn right with 60% power
}
else
{
ao(); // No pressing any switch, stop the robot
}
}

Listing A7-1 : RemoteSwitch.ino ; sketch file for wired remote


control activity of the POP-BOT XT
POP-BOT XT : The Arduino Compatible Mobile Robot kit 157

From all the 4 conditions, we will write the condition for making the control program
for the POP-BOT XT following the Listing A7-1

(A7.1) Remove both ZX-01 switch sensors from the robot chasis but the cable are still connect.
The ZX-01 switch sensors are similar looking to that of a wired remote control for POP-BOT
XT

(A7.2) Open the Arduino IDE. Type the Listing A7-1. Compile and upload to the robot.

(A7.3) Run the program. Try to press both ZX-01 switch sensors to control the robot movement.
158POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 8 : The bumper


From Activity 7, you have learnt how to use switch sensors to control the movement
of the robot. This activity requires the switches to be installed at the front of robot again.
The codes for this activity is also changed. For normal movement, robot moves forward
continuously until any of the switches is pressed. It means a collision has happened. The
robot moves backward and changes its direction to get through obstacles.

This activity is to program the robot to detect the collision of both switches at the
front of the POP-BOT XT robot. After a collision is encountered on the left side, the robot will
move backward and spin right to change the direction.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 159

On the other hand, if the collision is occurs at the right side. The robot moves
backwards again and spins left to change the direction.

(A8.1) Create the new sketch with Listing A8-1.

(A8.21) Turn-on the robot. Connect USB cable between a robot and a computer.

(A8.3) Compile and upload the code or sketch to POP-BOT XT controller board by clicking

on button or select menu File > Upload

(A8.4) Prepare the demonstration area by placing and securing boxes or objects on the
surface.

(A8.5) Place the robot on the demonstration area.

(A8.6) Run the sketch. At the robots display, it shows message :

Press OK

to Start
(A8.7) Press the OK switch and observe the robot.

The POP-BOT XT will read both switch status from port 22/A4 and 23/A5. If any
switch is pressed or it collides with some object, the result is logic 0.

In a normal operation, the robot will move forward continually.

If the Left Switch module touches any object, the robot will move backward and
change its moving direction to its right to avoid the object.

If the Right Switch module touches any object, the robot will move backward and
change its moving direction to its left to avoid the object.
160POP-BOT XT : The Arduino Compatible Mobile Robot kit

#include <popxt.h> // Include the main library


void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
glcd(2,1,"to Start");
sw_ok_press(); // Wait for OK switch pressed
glcdClear();
glcd(1,1,"Let's go!"); // Show operation message
}
void loop()
{
fd(70);
if(in(22)==0) // Left switch is attacked
{
bk(80); // Move backward
sleep(300);
sr(80); // Spin right
sleep(200);
}
if(in(23)==0) // Right swtich is attacked
{
bk(80); // Move backward
sleep(400);
sl(80); // Spin left
sleep(400);
}
}

Programming hint
This code determines the delay time in sleep() function which is used in the backward,
spin left and right sub-functions. These are not equal. It assist the robot to move out of the
trapped situation easier.

Listing A8-1: ObjectAvoider.ino; sketch file for object avoiding with


collision of the POP-BOT XT
POP-BOT XT : The Arduino Compatible Mobile Robot kit 161

Chapter 10
POP-BOT XT line tracking
Line following or Line tracking is a popular and common activity in robotics learning.
The purpose of this activity is to learn about how to interface analog sensors. In the POP-
BOT XT robot kit, it has a pair of Infrared reflector sensor for this activity. Two IR Reflector
sensors will be installed at the bottom of the POP-BOT XT so that it can detect both white
and black lines.

10.1 ZX-03 : Infrared reflector sensor


The heart of this sensor is TCRT5000 reflective object sensor. It is designed for close
proximity infrared (IR) detection. Theres an infrared diode behind its transparent blue
window and an infrared transistor behind its black window. When the infrared emitted by
the diode reflects off a surface and returns to the black window, it strikes the infrared
transistors base, causing it to conduct current. The more infrared incident on the transistors
base, the more current it conducts. The figure 10-1 shows the operation of ZX-03 sensor.

When used as an analog sensor, the ZX-03 can detect shades of gray on paper
and distances over a short range if the light in the room remains constant.

The suitable distance from sensor to line or floor is during 3 to 8 mm. The output
voltage is during 0.1 to 4.8V and digital value from10-bit A/D converter is 20 to 1,000.

+V +V
current flow

current flow

TCRT5000 OUT TCRT5000 OUT


510 High output voltage 510 Low output voltage
10k 10k
GND GND

Infrared LED Infrared LED

Photo-transistor Photo-transistor

White surface Black surface

Figure 10-1 : The operation of ZX-03 Infrared reflector sensor board


with white and black surface
162POP-BOT XT : The Arduino Compatible Mobile Robot kit

10.2 Line tracking activity preparation


10.2.1 Demonstration field component preparation
All activities are described in this chapter use the make your own demonstration
field . They includes white surface with black line and black surface with white line field.
You must make your own field using the items below (not provided in this kit) :

1. Polypropylene board or PP board white and Black sheet. Size is 90 x 60 cm.


However the sizing can change depending on your applications and resoucres.

2. Black and white electrical tape 1 inches width 2 rolls per color. 3M brand is
recommended.

3. Scissors or a Cutter

10.2.2 Set the reference value for line tracking activity with
analogRead() function
POP-BOT XT can detect the difference between lines and surface by reading the
infrared reflector sensors value via the analog input ports. POP-BOT XT programming uses
the analogRead() function of Arduino for reading any analog sensor port.

POP-BOT XT reads the black line and surface data with low value (less than 400
and minimum is 0) and reads the white line and surface data with high value (higher than
500 and maximum is 1023). The reference value for making the decision about line or
surface is average value from summing of black and white surface as follows :

Reference value = (White surface value + black surface value) / 2

The activity 9 shows the detail of the reference value for this line tracking activity.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 163

Activity 9 : Testing black and white area


The POP-BOT XT robot is attached with 2 of Infrared reflector modules at bottom of
the robot base. This activity will only dwell on the programming section.

Before developing the robot to track the line, developers must program the robot
to detect the difference between black and white surface.

(A9.1) Open the Arduino IDE and create the sketch code from Listing A9-1.

(A9.2) Upload the sketch to the robot. Disconnect the download cable.

(A9.3) Make the black & white testing sheet similar to the illustration as shown below. The
white surface area is 30 x 30 cm. and black surface is 30 x 30cm. (recommended).

(A9.4) Check the connection of both sensors again. The left ZX-03 sensor connect with port
18/A0 and right sensor connect with port 19/A1.

#include <popxt.h> // Include the main library


void setup()
{
setTextSize(3);
glcdMode(3);
glcd(1,1,"Press OK"); // Start message
sw_ok_press(); // Wait for the OK switch pressing
}
void loop()
{
glcd(1,1,"L=%d ",analog(0)); // Left ZX-03 value
glcd(3,1,"R=%d ",analog(1)); // Right ZX-03 value
sleep(100);
}

Listing A9-1 : SurfaceRead.ino ; sketch file for reading the surface


color and shows the value on the color display of the POP-BOT XT
164POP-BOT XT : The Arduino Compatible Mobile Robot kit

(A9.5) Place the robot on the black surface. See the detection data from the color display.

Black surface values will range from 80 to 250.

R=100
L=100
100

TB6612

100
TB6612

(A9.6) Place the robot on the white surface. See the detection data from the color display.
White surface values will range from 700 to1000.
L=900

R=900
100

TB6612

100
TB6612

The result is :

The black surface value is between 80 and 250

The white surface value is between 700 and 1000

The example reference value for detecting the line would be an average,
(100+900) /2 = 500.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 165

Activity 10 : AlarmBOT
This is a sample application to make the simple alarm system. When the robot is
lifted from the floor (the power is still on), the ZX-03 sensor that is installed bottom of the
robot chasis can not detect the reflected light. The reading is very low (less than black
value).

(A10.1) Open Arduino1.0 IDE and type the Listing A10-1.

(A10.2) Compile and upload to the POP-BOT XT. Disconnect the USB cable.

(A10.3) Place the robot on the floor. Then turn on power.

The robot will not do any work. The only indicator light is the on and the color
display screen will be black.

(A10.4) Try to lift the robot off the floor.

The POP-BOT XT will drive a warning sound alarm and the color display of the POP-
BOT XT is changed to red to alert you that the robot was lifted up off the floor.

#include <popxt.h> // Iclude the main library


void setup()
{}
void loop()
{
if(analog(0)<20) // Read and check the left sensor value ch.0
// lower 20
{
sound(2500,500); // If correct, drive alarm sound
glcdFillScreen(GLCD_RED); // Change background to red
}
else
{
glcdClear(); // Clear screen
}
}

Listing A10-1 : AlarmBOT.ino ; sketch file for AlarmBOT application


of the POP-BOT XT
166POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 11 : POP-BOT XT Edge detection


This activity is extended from the Activity 10. The POP-BOT XT can detect no light
reflected status. This activity will show about using infrared reflector sensors for surface
detection to control the robot move on the table and not fall off the edge of the table !

With a simple change of the position of the sensors and a simple program, you can
adapt the POP-BOT XT to edge detection. Start assembling the mechanical parts place
the sensors in the right position and create the Arduino sketch for the table surface testing.
This capability can be used to detect the area with a desk top or on the board at the
floor. Then write a program to make POP-BOT XT robot can move in the area.

(A11.1) Change the ZX-03 sensor position from bottom of the robot chasis to front by using
5-hole strip joiners, 3 x 15mm. screws and 3mm. nuts. The Edging detection robot will be
ready for programming following the picture below.

(A11.2) Use the same connection of both ZX-03 sensor same the previous activity.

(A11.3) Turn-on the robot. Connect USB cable between the robot and the computer.
(A11.4) Create the code following the Listing A11-1. Compile and upload the code or
sketch to POP-BOT XT controller board by clicking on button or select menu File >
Upload

(A11.5) Turn off power and remove the USB cable.


POP-BOT XT : The Arduino Compatible Mobile Robot kit 167

#include <popxt.h> // Include the main library


int L,R;
void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
glcd(2,1,"to Start");
sw_ok_press(); // Wait for the OK switch pressing
glcdClear();
glcd(1,1,"Moving..."); // Show the operation message
}
void loop()
{
fd(60); // Move forward
L=analog(0); // Define A0 sensor as Left sensor
R=analog(1); // Define A1 sensor as Right sensor
if (L<500&&R<500) // Both sensors out of the area
{
bk(80); // Move backward
sound(1000,100); // Warn the out of area by sounding
sleep(500);
sr(60); // Spin right to change direction
sleep(300);
}
else if(L<500) // The left sensor out of the area
{
bk(80); // Movce backward
sound(1500,100); // Warn the out of area with the different sound
// frequency
sleep(400);
sr(60); // Spin right to change direction
sleep(300);
}
else if(R<500) // The right sensor out of the area
{
bk(80); // Movce backward
sound(1500,100); // Warn the out of area with the sound
sleep(300);
sl(60); // Spin left to change direction
sleep(500);
}
}
Programming hint
There is 2 important variables; L and R for storing the value from ZX-03 sensors on both the
left and right. Thus, use the variable values to compare with the reference value with IF statement
to check the robot move out the table. Before the robot moves, the controller will move the
robot backward and drive a warning sound. After that, it will spin to change its direction.
From the code, execute the sound() function after bk() function. This is because the sound()
function takes time to work. If executed before moving backward, the robot may fall off the
table while the robot is generating the alarm sound.

Liusting A11-1 : EdgeDetect.ino ; sketch file for edge detection


application of the POP-BOT XT
168POP-BOT XT : The Arduino Compatible Mobile Robot kit

(A11.6) Place the robot on the table. Turn on and press the OK switch to start.

POP-BOT XT moves forward until the sensor is out from the tables edge. It will
change the movement direction following these scenarios :

1. Both sensors are out from tables edge : the robot moves backward and spins
right then moves forward again.

2 3
1 00

TB 66 12

100

1 00
TB 66 12

1
TB 66
12

4 5 6
100

TB 66
12
0
10

100
TB 661
2

TB6
61 2

2. The left sensor is out from talbes edge : the robot moves backward and
spins right then moves forward again.
100

TB6
61
2
0
10

100
TB 661
2

TB6
61
2

3. The right sensor is out from talbes edge : the robot moves backward and
spins left then moves forward again.

0
10
12
66
TB

TB6 612

100

0
10
2
61
T B6
POP-BOT XT : The Arduino Compatible Mobile Robot kit 169

Activity 12 : POP-BOT XT line detection


From the activity 9, we get the decision value for detection black and white area.
It is 500. Therefore, the reading sensor value which is lower 500 will be decided to black
color.

This activity demonstrates about black line detection of the POP-BOT XT that using
the result from the activity 9. The robot will move forward continuous until it detects the
black line. It will then stop immediately.

(A12.1) Use the robot platform from the previous activity.

(A12.2) Open the Arduino1.0 IDE to create the sketch following the Lisitng A12-1.

(A12.3) Compile and upload to the POP-BOT XT. Turn off power and remove the USB cable.

(A12.4) Stick the black tape 30cm. length on the white floor.

(A12.5) Place the robot on the floor far from the black line about 6cm. Turn on and press
the OK switch to start.

POP-BOT XT moves forward and stop when any ZX-03 sensor detects the black line.

(A12.6) From testing with the sketch file A12-1, usage of only the ao(); statement is not
enough to stop the movement immediately. We can impove this operation by moving
backward with very short time before stop. The example sketch is shown in Listing A12 -2

(A12.7) Upload the Listing A12-2 to POP-BOT XT and test again. See the different operation.

POP-BOT XT moves and stop when detect the black line similar the previous
operation. The different is stopping better than the previous operation than Listing A12-1.
170POP-BOT XT : The Arduino Compatible Mobile Robot kit

#include <popxt.h> // Include the main library


int L,R;
void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
sw_ok_press(); // Wait for the OK switch pressing
glcdClear();
glcd(1,1,"Moving..."); // Show the operation message
fd(60); // Moce forward
while(analog(0)>500); // Detect black line at A0 sensor
ao(); // Stop moving
}
void loop()
{}

Listing A12-1 : BlackLineDetect.ino ; sketch for the black line


d e t e c t i o n a c t i v i t y o f t h e P O P -B O T XT

#include <popxt.h> // Include the main library


int L,R;
void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
sw_ok_press(); // Wait for the OK switch pressing
glcdClear();
glcd(1,1,"Moving..."); // Show the operation message
fd(60); // Moce forward
while(analog(0)>500); // Detect black line at A0 sensor
bk(100); // Backward short time
sleep(100);
ao(); // Stop moving
}
void loop()
{}

Listing A12-2 : BlackLineDetect02.ino ; sketch file for the black line


detection activity of the POP-BOT XT. This code is improved the
robot stopping after detect the line.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 171

Activity 13 : POP-BOT XT moves along the black


line with 2 sensors
Heart of line tracking robot is control the robot to move over the line by sensors
position bestride the line. The robot moving along the line can be in 4 different scenarios.

(1) Both sensors read values that are white : The robot will move forward. Thus,
this program is written so that the robot moves forward normally.

(2) The left sensor detects the black line : This occurs when the robot is slightly
turned to the right. Thus, the program is written for the robot to move back left to resume
its normal path.
100

TB66
12
172POP-BOT XT : The Arduino Compatible Mobile Robot kit

(3) The right sensor detects the black line : This occurs when the robot is
slightly turned to the left. Thus, the program is written for the robot to move back to the
right to resume its normal path.

0
10
12
TB 66

(4) Both sensor detect the black line : the program is written for the robot to
make decision to move forward, tunr left, turn right , backward or stop.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 173

(A13.1) Change the ZX-03 sensor positon back to bottom of the robot chasis.

(A13.2) Open the Arduino1.0 IDE to create the sketch following the Lisitng A13-1.

(A13.3) Compile and upload to the POP-BOT XT. Turn off power and remove the USB cable.

(A13.4) Make the simple black line field following the illustration below. The white surface
area is 90 x 60 cm. and black line width is 1 inches (2.5 cm.)

(A13.5) Place the POP-BOT XT on the black line field. Turn on the robot. Observe the
robot movement.

POP-BOT XT will move along the black line. It is possible that the robot moves out of
the line. You can improve the precision by editing the program with adjusting the sensor
reference value and adjust to the position of both infrared reflector sensors.
When the robot moves over the crossing line, it drives a beep sound at once.
(A13.6) Try to increase the movement speed to find the maximum speed that the robot
still move along the line completely and not move out from the line.

Troubleshooting about line traking robot


There are some suggestion about checking and find out why the robot does not
move along the line or move not complete.

1. Check the connection of ZX-03 sensors. Follow this activity, the left ZX-03 sensor
connect with port A0/18 and right sensor is connected with port A1/19.

2. Check the motor connection. possible to swop connection or connection is not


complete ? Refer this activity, the left motor is Motor A or Motor 1 and the right motor is
Motor B or Motor 2.

3. Installation the sensor too far from the floor or not ? The suitable distance is 5 to
10mm.

4. Test the reference value from the activity 9 still working or not ?
174POP-BOT XT : The Arduino Compatible Mobile Robot kit

#include <popxt.h> // Include the main library


int L,R;
void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
sw_ok_press(); // Wait for the OK switch pressing
glcd(1,1,"Moving..."); // Show the operation message
}
void loop()
{
L=analog(0); // Get the Left line sensor data
R=analog(1); // Get the Rightt line sensor data
if (L<500&&R<500) // Both sensors detect the black line.
// It means the crossing line
{
fd(60); // Move forward over the corssing line
sound(2000,200); // Beep a sound
}
else if(L>500&&R>500) // Both sensors detect the white area.
// It means robot move bestride the line
{
fd(60); // Move forward with 60% power
}
else if(L<500) // The left line sensor detects the black line
// The robot will move out the line in right
{
sl(60); // Spin left a little bit to adjust the robot
// over the line
sleep(20);
}
else if(R<500) // The right line sensor detects the black line
// The robot will move out the line in left
{
sr(60); // Spin right a little bit to adjust the robot
// over the line
sleep(20);
}
}

Listing A13-1 : SimpleLineTracking.ino ; sketch file for the Simple


line tracking activity of the POP-BOT XT by using 2 line tracking
sensors
POP-BOT XT : The Arduino Compatible Mobile Robot kit 175

Activity 14 : Simple Maze Solving


This activity is example of the Maze Solving competition. The robot will move along
the line and turn to change its ditrection when detect the crossing line. The robotmust
move in this manner until it detects all the crossing lines of the competition

Make the field


Stick the black tape 2.5cm. width on the white surface 90 x 60cm. size. or bigger
following the illustration below.

R90() function - the important function for this activity


To solve this activity, the important factor is the precision turning 90 degrees. The
R90() function is created. It turns right 90 degrees function when detect the crossing line

For a precision turn right when detecting the crossing line, robot must move forward
for a short time and then turn right until the sensors detects the cross line. After that move
forward to along the line continuous. The figure A14-1 shows this function operation.
176POP-BOT XT : The Arduino Compatible Mobile Robot kit

Figure A14-1 : Shows the robot operation with R90() function to


improve the movement in Maze Solving activity.

Procedure
(A14.1) Open the Arduino1.0 IDE to create the sketch following the Lisitng A14-1.

(A14.2) Compile and upload to the POP-BOT XT. Turn off power and remove the USB cable.

(A14.3) Place the POP-BOT XT over the line. Tunr on power and press OK switch to start.

POP-BOT XT moves along the line and turn right after detects the crossing line.
Every cross line detection, the robot drives a beep.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 177

#include <popxt.h> // Include the main library


int L,R;
/* 90-Degree Turn right routine */
void R90()
{
fd(60); // Move forward pass the crossing line
sound(1500,100); // Drive the sound signal
while(analog(1)>500) // Check the Right line sensor to detect the white
area
{
sr(60); // Spin right
}
while(analog(1)<500) // Spin right until detect the black line
{
sr(60); // Spin right again to pass the black line
}
}
void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
sw_ok_press(); // Wait for the OK switch pressing
glcd(1,1,"Moving..."); // Show the operation message
}
void loop()
{
L=analog(0); // Get the Left line sensor data
R=analog(1); // Get the Rightt line sensor data
if (L<500&&R<500) // Both sensors detect the black line.
// It means the crossing line
{
R90(); // Call 90-Degree Turn right routine
}
else if(L>500&&R>500) // Both sensors detect the white area.
// It means robot move bestride the line
{
fd(60); // Move forward with 60% power
}
else if(L<500) // The left line sensor detects the black line
// The robot will move out the line in right
{
sl(60); // Spin left a little bit to adjust the robot over
// the line
sleep(20);
}
else if(R<500) // The right line sensor detects the black line
// The robot will move out the line in left
{
sr(60); // Spin right a little bit to adjust the robot over
// the line
sleep(20);
}
}

Listing A14-1 : SimpleMaze.ino; sketch file for simple maze solving


activity of the POP-BOT XT
178POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 15 : POP-BOT XT with complex line


tracking
The robot needs to detect multiple cross lines with with increasing complexity, such
as turn left at the first intersection, turn right at the second intersection, move forwards at
the third intersection and turn right at the forth intersection etc. Users must create some
variable to count the number of intersections that robot detected.

Procedure
(A15.1) Make the demonstration field by using the 2.5mm. width black tape. Stick the
tape on the white surface 90 x 120cm size (or bigger) following the illustration below.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 179

(A15.2) Open the Arduino1.0 IDE to create the sketch following the Lisitng A15-1.

(A15.3) Compile and upload to the POP-BOT XT. Turn off power and remove the USB cable.

(A15.4) Place the POP-BOT XT over the line. Turn on power and press OK switch to start.

POP-BOT XT moves following the line, turn left when detects the 1st, 2nd, 4th, 5th,
6th, 7th and 8th intersection and turn right at the 3rd intersection. Then, robot drive a
beep at every intersection detected.
180POP-BOT XT : The Arduino Compatible Mobile Robot kit

#include <popxt.h> // Include the main library


int L,R,x=0;

/* 90-Degree Turn right routine */


void R90()
{
fd(60); // Move forward pass the crossing line
sound(1500,100); // Drive the sound signal
while(analog(1)>500) // Check the Right line sensor to detect the white
area
{
sr(60); // Spin right
}
while(analog(1)<500) // Spin right until detect the black line
{
sr(60); // Spin right again to pass the black line
}
}
/* 90-Degree Turn left routine */
void L90()
{
fd(60); // Move forward pass the crossing line
sound(1500,100); // Drive the sound signal
while(analog(1)>500) // Check the Right line sensor to detect the white
area
{
sl(60); // Spin right
}
while(analog(1)<500) // Spin right until detect the black line
{
sl(60); // Spin right again to pass the black line
}
}
void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
sw_ok_press(); // Wait for the OK switch pressing
glcd(1,1,"Moving..."); // Show the operation message
}
void loop()
{
L=analog(0); // Get the Left line sensor data
R=analog(1); // Get the Right line sensor data
if (L<500&&R<500) // Both sensors detect the black line. It means the
// crossing line
{
if(x==6) // The crossing line counting was complete
{
x=0; // Restart counting
POP-BOT XT : The Arduino Compatible Mobile Robot kit 181

}
x++; // Increase the crossing line counting
if (x==3) // Check the 3rd crossing line
{
R90(); // Turn right with 90-degree after detect the 3rd
// crossing line
}
else
{
L90(); // If not, turn left with 90-degree
}
}
else if(L>500&&R>500) // Both sensors detect the white area. It means
// robot move bestride the line
{
fd(60); // Move forward with 60% power
}
else if(L<500) // The left line sensor detects the black line
// The robot will move out the line in right
{
sl(60); // Spin left a little bit to adjust the robot over
// the line
sleep(20);
}
else if(R<500) // The right line sensor detects the black line
// The robot will move out the line in left
{
sr(60); // Spin right a little bit to adjust the robot over
// the line
sleep(20);
}
}

Liusting A15-1 : MultipleCrossingTrack.ino ; sketch file for muitiple


crossing line tracking activity of the POP-BOT XT
182POP-BOT XT : The Arduino Compatible Mobile Robot kit
POP-BOT XT : The Arduino Compatible Mobile Robot kit 183

Chapter 11
Touchless object avoiding
From chapter 10, we have many examples about interfacing the Infrared reflector
sensors. They are one kind of analog sensor. In this chapter, we will concentrate in interfac-
ing with another analog sensors. It is Infrared distance sensor or Infrared ranger; GP2D120.
We will explore on some of example about using this sensor and applications.

One of the special sensors in robotics is the Infrared Distance sensor. Some people
call it the IR Ranger. With the GP2D120 module, it gives POP-BOT XT the ability for distance
measurement and obstacle detection using an infrared light. Your POP-BOT XT can avoid
obstacles without having to make any physical contact.

11.1 GP2D120 features


Uses Infrared light reflection to measure range
Can measure a range from 4 to 30 cm.
4. 5 to 5 V power supply and 33mA electric current
The output voltage range is 0.4 to 2.4V when supplied by +5V

Output voltage (V)

2.8
Infrared LED transmitter Infrared Receiver
2.4

2.0

1.6
GP2D120 1.2

0.8
Vout GND Vcc
0.4

0
Supply 0 4 8 12 16 20 24 28 32
Distance (cm)
38.39.6 ms
* Use Kodak R-27 gray-white
Measurement 1st measure 2nd measure n measure
paper. The white side has a
90% reflection rate, made
Vout Not stable 1st output 2nd output n output
from a material that reflects
5 ms
light for range measurement.

Figure 11-1 : GP2D120 pin assignment, operation and characteristic


curve
184POP-BOT XT : The Arduino Compatible Mobile Robot kit

GP2D120 Infrared Ranger module has 3 terminals : Supply input (Vcc), Ground
(GND) and Voltage output (Vout). To read the voltage values from the GP2D120, you
must wait until after the acknowledgement period which is around 32 to 52.9 ms.
The output voltage of GP2D120 at a range of 30 cm. and +5V power supply is
between 0.25 to 0.55V, with the mean being 0.4V. At the range of 4 cm., the output
voltage will change at 2.25V 0.3V.

11.2 Reading GP2D120 with A/D converter


The GP2D120s output voltage will change according to the detection distance.
For example, Vout 0.5V is equal 26cm. distance and Vout 2V is equal 6cm. distance. The
table 11-1 shows the summary of GP2D120s Vout and Distance relation.
For interfacing with A/D converter module within microcontroller, the result is raw data
from the A/D conversion. The user will need to use the software to convert the raw data to the
exact distance. You can calculate the approximate distance from the formula below.

2914
R 1
V 5
Thus, R as Distance in Centimetre unit
V as Digital data from A/D conversion
For example, see the Table 11-1. The raw data from conversion is 307. It is equal
8cm. distance.

11.3 GP2D120 Infrared ranger library


For supporting the GP2D120 sensor, the main library popxt.h also provides the special
library. It is the gp2d120_lib.h.
To using this library, must include at the beginning of the program with this statement :
#include <gp2d120_lib.h>
There is only one function in this library. It is getdist(). This is summary of this
function :
Syntax
unsigned int getdist(char adc_ch)
Parameter
adc_ch - Analog port that connect with GP2D120 (A0 to A7)

Return value
Distance in centimetre unit
Example 11-1
dist = getdist(3); // Read distance from GP1D120 at A3 port

For hardware interfacing, connect this sensor to any analog port of the POP-BOT
XT. which is A0 to A7.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 185

GP2D120 10-bit Distance


output voltage (V) A/D converter result (cm.)

0.4 82 32
0.5 102 26
0.6 123 22
0.7 143 19
0.8 164 16
0.9 184 14
1.0 205 13
1.1 225 12
1.2 246 11
1.3 266 10
1.4 287 9
1.5 307 8
1.6 328 8
1.7 348 7
1.8 369 7
1.9 389 6
2.0 410 6
2.1 430 6
2.2 451 5
2.3 471 5
2.4 492 5
2.5 512 5
2.6 532 4

Table 11-1 : The relation of GP2D120 output voltage, A/D converter


result and Measured distance.

11.4 Warning for the signal cable of the GP2D120


The GP2D120 module has a different pin arrangement then that of the POP-BOT XT
controller board, even though it looks similar. Therefore, a special signal cable has already
been made and connected to the GP2D120 module. All the user need to is to connect
the other end of the cable to any of the analog ports of the POP-BOT XT controller board.
DO NOT remove the cable from the module, and do not replace it with signal cables from
other sensor modules.
186POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 16 : POP-BOT XT with GP2D120

Activity 16-1 GP2D120 installation with POP-BOT XT


(A16.1.1) Fix the 2 x 3 holes right-angle metal shaft with GP2D120 module at both installation
holes by using 3 x 10mm. screws and 3mm. nuts following the picture below.

2 x 3 hole right-angle
GP2D120 module metal shaft

3mm. nut
3 x 10mm. screw

hole of metal shaft

(A16.1.2) Attach the GP2D120 in front of the robot chasis by using 3 x 10mm. screws and
3mm. nuts following the pictures below.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 187

(A16.1.3) Connect GP2D120 cable to port 20/A2 of the POP-BOT XT controller board.

20/A2

Now the POP-BOT XT is ready for touchless object avoidance.

Activity 16-2 Measure distance with GP2D120


GP2D120 module gives the output voltage relate the distannce. The microcontroller
use the analog reading function to get the distance raw data from GP2D120. The POP-
BOT XT also have the special library to read the value. If reading value is high, means the
object is near the GP2D120. In the other hands, low value result means that the object is
far from GP1D120.

#include <popxt.h> // Include the main library


#include <gp2d120_lib.h> // Include GP2D120 sensor library
int raw,dist;
void setup()
{
setTextSize(2); // Set text size 2x
glcdMode(1); // Set display mode 1
glcd(1,1,"Press OK"); // Show the start message
sw_ok_press(); // Wait for the OK switch pressing
glcdClear(); // Clear screen
}
void loop()
{
raw=analog(2); // Read the raw sensor data from Analog input 2
dist=getdist(2); // Get the real distance value
glcd(2,1,"RAW = %d ",raw); // Show the raw data on screen
glcd(3,1,"Dist = %d cm",dist); // Show the distance value on screen
sleep(100);
}

Listing A16-1 : GP2D120_Reading.ino ; sketch file of GP2D120


distance measurement of the POP-BOT XT
188POP-BOT XT : The Arduino Compatible Mobile Robot kit

(A16.2.1) Open the Arduino1.0 IDE to create the sketch following the Lisitng A15-1.

(A16.2.2) Compile and upload to the POP-BOT XT. Turn off power and remove the USB
cable.

(A16.2.3) Place the POP-BOT XT on the table. Put an object in front of the GP2D120. Turn
on the POP-BOT XT. Try to move an object in and out from GP2D120 sensor. Observe the
result at the color display of the robot.

100 F

A
TM
e
g
a
3
2
U
4

220 F

TB
100
6
6
1
2

Adjust the distance


in range 4 to 32cm.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 189

Activity 17 : Touchless object avoiding robot


With the GP2D120 module, it adds the distance measuring and obstacle detection
using infrared light feature to your robot. Your POP-BOT XT can avoid obstacles without
having to make any physical contact. The detected distance of this activity is 10cm.

(A17.1) Open the Arduino IDE and create the sketch code from Listing A17-1.

(A17.2) Upload the sketch to the robot and disconnect the USB cable.

(A17.3) Place the POP-BOT XT on thefloor. Try to place any object at the front of the robot
and see its operation.

The robot will check the distance of the object in 10cm. range. If not any obstacle,
robot will move forward continue. If found the object, it will move backward, spin left and
move forward again.

The display of the robot will change the color background everytime an object
detecion is detected. The color changing is random from 8 colors including red, green,
blue, yellow, black, white, skyblue and magenta.
190POP-BOT XT : The Arduino Compatible Mobile Robot kit

#include <popxt.h> // Include the main library


#include <gp2d120_lib.h> // Include GP2D120 sensor library
void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
glcd(2,1,"to Start");
sw_ok_press(); // Wait for OK switch pressed
glcdClear();
glcd(1,1,"Let's go!"); // Show operation message
}
void loop()
{
fd(70);
if(analog(20)>250) // Detect object in 10cm. or shorter
{
bk(80); // Move backward with 80% power
glcdFillScreen(color[random(8)]); // Change background colr with random
sleep(300);
sl(70); // Spin left to change direction
sleep(600);
}
}

Listing A17-1 : TouchlessObjectAvoider.ino ; sketch file for Touchless


object avoider activity of the POP-BOT XT
POP-BOT XT : The Arduino Compatible Mobile Robot kit 191

Chapter 12
POP-BOT XT with servo motor
POP-BOT XT features more of the RC servo motor output. POP-BOT XT can drive 3 of
small RC servo motors simultaneously. POP-BOT XT controller board supplies the servo motor
supply voltage to Servo output headers already. There is no need for additional batteries
for the servo motor.

12.1 Servo motor introduction


Figure 12-1 shows a drawing of a Standard Servo. The plug is used to connect the
servo motor to a power source (Vdd and Vss) and a signal source (a microcontroller I/O
pin). The cable conducts Vdd, Vss and the signal line from the plug into the servo motor.
The horn is the part of the servo that looks like a four-pointed star. When the servo is running,
the horn is the moving part that the microcontroller controls. The case contains the servos
control circuits, a DC motor, and gears. These parts work together to take high/low signals
from the microcontroller and convert them into positions held by the servo horn.

Figure 12-2 shows the servo motor cable assignment. It has 3 wires with difference
color; Black for GND or Vss or Negative pole, Red for Vdd or Servo motor supply voltage
and White (sometime is yellow or brown) wire for signal.

The servo motor plug standard has 2 types; S-type and J-type are shown in the
figure 12-3.

Horn

Plug Cable

STANDARD
SERVO MOTOR

Case

Figure 12-1 : Standard servo motor physical


192POP-BOT XT : The Arduino Compatible Mobile Robot kit

(a) S-type plug (b) J-type plug

Figure 12-2 : Standard Servo motor Figure 12-3 : Standard Servo motor
cable assignment plug type

Controlling of the servo motors is used to pulse controlling. The control pulse is positive
going pulse with length of 1 to 2 ms which is repeated about 50 to 60 times a second. You
can check the details in the figure 12-4. Start by generating a pulse a period 20 millisecond
and adjust the positive pulse width 1 millsecond. The servo motor will move the horn to last
left position. The pulse width 1.5 millisecond move the servo horn to center and pulse
width 2 millsecond causes the servo horn to last right position.

The important specification of servo motor are 2 points, Speed or Servo turn rate or
transit time and Torque. The servo turn rate, or transit time, is used for determining servo
rotational velocity. This is the amount of time it takes for the servo to move a set amount,
usually 60 degrees. For example, suppose you have a servo with a transit time of 0.17sec/
60 degrees at no load. This means it would take nearly half a second to rotate an entire
180 degrees. More if the servo were under a load. This information is very important if high
servo response speed is a requirement of your robot application. It is also useful for
determining the maximum forward velocity of your robot if your servo is modified for full
rotation. Remember, the worst case turning time is when the servo is at the minimum
rotation angle and is then commanded to go to maximum rotation angle, all while under
load. This can take several seconds on a very high torque servo.

Torque is the tendency of a force to rotate an object about an axis. The torque
unit is ounce-inches (oz-in) or kilogram-centimetre (kg-cm). It tell you know about this servo
motor can drive a load weight in 1 oz. to move 1 inche or 1kg. weight to moved 1
centimeter (1oz. = 0.028kg. or 1kg. = 25.274oz.). Normally the RC servo motor has 3.40 kg-
cm/47oz-in torque.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 193

1 to 2 millsecond pulse

(a) Servo motor control pulse


20ms period

1 millisecond pulse

STANDARD
(b) 1 millisecond pulse causes SERVO MOTOR

servo horn moves anti-clockwise


direction to last right position (0o)

1.5 millisecond pulse

(c) 1.5 millisecond pulse causes STANDARD


SERVO MOTOR

servo horn moves to center position

2 millisecond pulse

(d) 2 millisecond pulse causes STANDARD


SERVO MOTOR

servo horn moves clockwise


direction to last left position (180o)

Figure 12-4 : Timing diagram of pulse control servo motor


194POP-BOT XT : The Arduino Compatible Mobile Robot kit

12.2 servo() function


The heart of controlling the servo motor of POP-BOT XT controller board is servo()
function in popxt.h library. We will use a general purpose port to servo output; 30 (SV1), 12
(SV2) and 13 (SV3).

This is sum m a ry o f servo()function.


Syntax
void servo(unsigned char _ch, int _pos)

Parameter
_ch - Servo motor output (1 to 3)

_pos - Set the sevo motor shaft poistion (0 to 180 and -1)

If set to -1, disable selected servo motor output


POP-BOT XT : The Arduino Compatible Mobile Robot kit 195

Activity 18 : Simple servo motor control


This activity demonstrates the simple example about control the standard RC servo
motor with a KNOB button on the POP-BOT XT controller board.

(A18.1) Open the Arduino IDE and create the sketch code from Listing A18-1.

(A18.2) Upload the sketch to the robot. Turn off power.

(A18.3) Connect the standard RC servo motor to SERVO PORT 1 (SV1). Make sure the
connection is correct. The black wire is ground (GND), red wire is +Vm and white or yellow
wire is signal (S).

(A18.4)Turn on power, Press the OK switch to start. Adjust the KNOB button on the POP-BOT
XT controller board. Observe the servo motor operation when adjust the KNOB.

Adjusting the KNOB causes the color display to show the KNOB value and servo
motor is driven following the KNOB adjustment.
196POP-BOT XT : The Arduino Compatible Mobile Robot kit

#include <popxt.h> // Include the main library


int x;
void setup()
{
glcdMode(1); // Set display mode 1
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
sw_ok_press(); // Wait for OK switch pressed
glcdClear();
}
void loop()
{
x=map(knob(),80,1023,0,180); // Read KNOB data and adjust to 0 to 180
// range for storing in variable
glcd(2,1,"Servo = %d ",x); // Display servo motor position
servo(1,x); // Drive a servo motor1 to target position
}

Listing A18-1 : ServoKnob.ino ; sketch file of simple servo motor control


of the POP-BOT XT
POP-BOT XT : The Arduino Compatible Mobile Robot kit 197

Activity 19 : ObjectHitter-BOT

Activity 19-1 Installation servo motor with POP-BOT XT


(A19.1.1) Attach 2 of the 2 x 3 hole right-angle metal shaft together by using 3 x 6mm.
screws and 3mm. nuts following the picture below.

2 x 3 hole right-angle metal shaft


#2
3 x 6mm. screw

3mm. nut

hole of metal shaft

2 x 3 hole right-angle metal shaft #1

(A19.1.2) Unscrew the screw at servo motor shaft and remove the horn. Attach a right-
angle metal shaft with servo motor body by using 3 x 10mm. screws and 3mm. nuts following
the picture below.

installation hole of servo motor


3 x 10mm. servo motor
screw

3mm. nut

3 x 10mm.
screw
The 2 x 3 hole right-angle
metal shaft from step
metal shaft's hole (A19.1.1)
198POP-BOT XT : The Arduino Compatible Mobile Robot kit

(A19.1.3) Attach the servo motor from step (A19.1.2) at the front of the robot chasis (see
the circle) by using 2 sets of 3 x 10mm. screw and 3mm. nut

(A19.1.4) Make an arm from 12-hole strip joiner. Attach it with servo motor shaft. Tighten
with a servo motor screw that release from stpe (A19.1.2). Connect the servo motor to SV1
output. The ObjectHitter-BOT is ready for doing the mission.
POP-BOT XT : The Arduino Compatible Mobile Robot kit 199

Activity 19-2 ObjectHitter-BOT basic operation


The mission of this activity is move to find the line and hit an abject at the end of
each line.

(A19.2.1) Open the Arduino IDE and create the sketch code from Listing A19-1.

(A19.2.2) Upload the sketch to the robot. Turn off power.

(A19.2.3) Stick the black line on the white surface. Place the robot far from the black line
30cm.

(A19.2.4) Turn on power. Press the OK switch to start.

POP-BOT XT will move forward to the black line. After detect lhe blakc line, robot
will stop and drive a servo motor to move from 0 degree to 180 degrees and back to 0
degree position again. The arm that connect with servo shaft will move from right to left
and back to left again. The arm will hit an object at the black line.

#include <popxt.h> // Include the main library


void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
glcd(2,1,"to Start");
sw_ok_press(); // Wait for OK switch
// pressed
glcdClear();
glcd(1,1,"Let's go!"); // Show operation message
servo(1,0); // Set servo motor shaft
// to zero postion
sleep(1000);
fd(60); // Robot moves forward
}

void loop()
{
if(analog(0)<500) // Detect the black line
{
ao(); // Stop moving
servo(1,180); // Drive servo to hit an object
sleep(1000); // Delay 1 second
servo(1,0); // Set servo motor shaft to origin
while(1); // Stop operation
}
}

Listing A19-1 : ServoHitting.ino ; sketch file for controlling the servo


motor to hit an object
200POP-BOT XT : The Arduino Compatible Mobile Robot kit

Activity 19-3 ObjectHitter-BOT mission


The mission field for this activity is shown below.

START
STOP

From start point, the robot must move following the line and do something when
the robot detects the intersection as follows :

1. Turn left

2. Turn right

3. Move forward

4. Hit the object and move back to the same path

Mission is move to the end of each line to hit the object. Moving path of this mission
is as follows :

1. Detect 1st intersection, robot turn left

2. Detect 2nd intersection, robot hit an object, turn back and move forward.

3. Detect 3rd intersection, robot move forward to cross the intersection.

4. Detect 4th intersection, robot hit an object, turn back and move forward.

5. Detect 5th intersection, robot turn right


POP-BOT XT : The Arduino Compatible Mobile Robot kit 201

(A19.3.1) Open the Arduino IDE and create the sketch code from Listing A19-2.

(A19.3.2) Upload the sketch to the robot. Turn off power.

(A19.3.3) Make the mission field by using the 2.5cm. width black tape and the white board.

(A19.3.4) Place the robot on the start point

(A19.3.5) Turn on power. Press the OK switch to start.

The POP-BOT XT moves and do mission following the illustration below :


202POP-BOT XT : The Arduino Compatible Mobile Robot kit

#include <popxt.h> // Include the main library


int L,R,x=0,y=0;
/* Move forward funtion */
void FF()
{
fd(60);
sleep(300);
}
/* 90-Degree Turn right function */
void R90()
{
fd(60); // Move forward pass the crossing line
sound(1500,100); // Drive the sound signal
while(analog(1)>500) // Check the Right line sensor to detect the white
area
{
sr(60); // Spin right
}
while(analog(1)<500) // Spin right until detect the black line
{
sr(60); // Spin right again to pass the black line
}
}
/* 90-Degree Turn left function */
void L90()
{
fd(60); // Move forward pass the crossing line
sound(1500,100); // Drive the sound signal
while(analog(1)>500) // Check the Right line sensor to detect the white
area
{
sl(60); // Spin right
}
while(analog(1)<500) // Spin right until detect the black line
{
sl(60); // Spin right again to pass the black line
}
}
/* Hit object function */
void hit()
{
bk(100); // Move backward short time
sleep(50);
ao(); // Stop motor
servo(1,180); // Drive servo motor to 180-degree position
sleep(1000);
servo(1,0); // Drive servo motor back to 0-degree position

bk(60); // Move backward


sleep(200);
R90(); // 90-degree turn right
}
void setup()
{
setTextSize(2); // Set text size 2x
glcd(1,1,"Press OK"); // Show the start message
glcd(2,1,"to Start");
sw_ok_press(); // Wait for OK switch pressed
glcdClear();
glcd(1,1,"Let's go!"); // Show operation message
}
POP-BOT XT : The Arduino Compatible Mobile Robot kit 203

void loop()
{
L=analog(0); // Read the Left line sensor value
R=analog(1); // Read the Right line sensor value
if (L<500&&R<500) // Detect the crossing line
{
if(x==5) // The crossing line counting was complete
{
x=0; // Restart counting
y++; // Increase branch counter
if (y==4) // The branch counting was complete
{
ao(); // Stop the robot
servo (1,-1); // Stop servo motor
while(1);
}
}
x++; // Increase the line crossing counter
if (x==1) // 1st crossing
{
L90(); // Turn left
}
else if(x==2||x==4) // 2nd and 4th crossing
{
hit(); // Hit the object
}
else if (x==3) // 3rd crossing
{
FF(); // Move forward
}
else if (x==5) // 5th crossing
{
R90(); // 90-degree turn right
}
}
else if(L>500&&R>500) // Both sensors detect the white area. It means
// robot move bestride the line
{
fd(60); // Move forward with 60% power
}
else if(L<500) // The left line sensor detects the black line
// The robot will move out the line in right
{
sl(60); // Spin left a little bit to adjust the robot
// over the line
sleep(20);
}
else if(R<500) // The right line sensor detects the black line
// The robot will move out the line in left
{
sr(60); // Spin right a little bit to adjust the robot
// over the line
sleep(20);
}
}

Listing A19-2 : ObjectHitterBOT.ino ; sketch file for ObjectHitter-BOT


mission of the POP-BOT XT
204POP-BOT XT : The Arduino Compatible Mobile Robot kit

About this mission operation is described as


follows :

Firstly, POP-BOT XT moves along the line. After


meet the 1st intersection, it turns left and moves forward
until it meets the 2nd intersection. It drives a servo motor
to hit an object at the end of line. After that, it turns
back and moves forward to the main path.

Robot will meets the 3rd intersection at the main


path. It moves forward over this intersection and moves
to meets the 4th intersection. After that it drives a servo
motor again to hit the object at the end of line. Then it
turns back and moves forward back to the main path
again.

It meets the 5th at the main path then turns right.


The movement will loop to detect the 1st intersection.
POP-BOT XT will move, detect the intersection and drive
the servo motor to hit object at the end of each line.

After it hits all object already, it moves to the Stop


point. The mission is completed.

You might also like