Escolar Documentos
Profissional Documentos
Cultura Documentos
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.
68 POP-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);
}
70 POP-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 2
3
// The result is y = 125
72 POP-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*/.
74 POP-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;
76 POP-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 calcul ation with the float variabl e wil l be sl ower 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.
78 POP-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.
80 POP-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.
}
82 POP-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
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* 10
2
) + (0 * 10
1
) + (1 * 10
0
) = 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 * 2
2
) + (0 * 2
1
) + (1 * 2
0
) = 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 * 8
2
) + (0 * 8
1
) + (1 * 8
0
) = 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 * 16
2
) + (0 * 16
1
) + (1 * 16
0
) = 256 +
0 + 1 = 257
POP-Note
84 POP-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
HIGH
LOW
INPUT
OUTPUT
SERIAL
DISPLAY
PI
HALF_PI
TWO_PI
LSBFIRST
MSBFIRST
CHANGE
FALLING
RISING
false
true
null
# Literal Constants
GLCD_RED
GLCD_GREEN
GLCD_BLUE
GLCD_YELLOW
GLCD_BLACK
GLCD_WHITE
GLCD_SKY
GLCD_MAGENTA
# Port Constants
DDRB
PINB
PORTB
DDRC
PINC
PORTC
DDRD
PIND
PORTD
# Names
popxt
# Datatypes
boolean
byte
char
class
default
do
double
int
long
private
protected
public
return
short
signed
static
switch
throw
try
unsigned
void
# Methods/Fucntions
sw_ok
sw_ok_press
analog
knob
glcd
glcdChar
glcdString
glcdMode
glcdGetMode
glcdFlip
glcdGetFlip
colorRGB
setTextColor
setTextBackgroundColor
setTextSize
getTextColor
getTextBackgroundColor
getTextSize
glcdFillScreen
glcdClear
glcdPixel
glcdRect
glcdFillRect
glcdLine
glcdCircle
86 POP-BOT XT : The Arduino Compatible Mobile Robot kit
glcdFillCircle
glcdArc
getdist
in
out
motor
motor_stop
fd
bk
fd2
bk2
tl
tr
sl
sr
servo
sound
beep
uart_set_baud
uart_get_baud
uart_putc
uart_puts
uart
uart_available
uart_getkey
uart1_set_baud
uart1_get_baud
uart1_putc
uart1_puts
uart1
uart1_available
uart1_getkey
uart1_flush
# Other
abs
acos
+=
+
[]
asin
=
atan
atan2
&
&=
|
|=
boolean
byte
case
ceil
char
char
class
,
//
?:
constrain
cos
{}
default
delay
delayMicroseconds
/
/**
.
else
==
exp
false
float
float
floor
for
<
<=
HALF_PI
if
++
!=
int
<<
<
<=
log
&&
!
||
^
^=
loop
max
millis
min
-
%
/*
*
new
null
()
PII
return
>>
;
Serial
Setup
sin
sq
sqrt
-=
switch
tan
this
true
TWO_PI
void
while
Serial
begin
read
print
write
println
available
digitalWrite
digitalRead
pinMode
analogRead
analogWrite
attachInterrupts
detachInterrupts
beginSerial
serialWrite
serialRead
serialAvailable
printString
printInteger
printByte
printHex
printOctal
printBinary
printNewline
pulseIn
shiftOut
POP-BOT XT : The Arduino Compatible Mobile Robot kit 87
The POP-BOT XT robots program development can be summarize in the diagram
shown in figure 5-1.
Chapter 5
POP-BOT XT program
development by Arduino1.0
Figure 5-1 Programming development diagram of POP-BOT XT robot kit by
using Arduino IDE
Create the sketch file
Make the C/C++ code on Arduino IDE
Compile
Upload the code
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.
Installtion software tools
- Arduino 1.0 IDE :
C/C++ programming development tools.
Includes Text editor, Compiler and Upload the
code to microcontroller
- USB driver of the POP-XT controller board
USB port
88 POP-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
Upl oading 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
90 POP-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.
USB-miniB cable
Connect with
computer's USB port
Computer
POP-BOT XT
2
2
0
F
1
0
0
F
TB6612
ATMega32U4
1
0
0
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.
92 POP-BOT XT : The Arduino Compatible Mobile Robot kit
POP-BOT XT : The Arduino Compatible Mobile Robot kit 93
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.
Chapter 6
POP-BOT XT controller board
hardware experiment
94 POP-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.
USB-miniB cable
Connect with
computer's USB port
Computer
POP-BOT XT
2
2
0
F
1
0
0
F
TB6612
ATMega32U4
1
0
0
(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
(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.
220 F
100 F
T
B
6
6
1
2
A
T
M
e
g
a
3
2
U
4
100
Hello World
#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
96 POP-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.
220 F
100 F
T
B
6
6
1
2
A
T
M
e
g
a
3
2
U
4
100
Row00
Row01
RRRow02
RRRRow03
RRRRRow04
RRRRRRow05
RRRRRRRow06
RRRRRRRRow07
RRRRRRRRRow08
RRRRRRRRRRow09
RRRRRRRRRRRow010
RRRRRRRRRRRRow011
RRRRRRRRRRRRRow012
RRRRRRRRRRRRRRow013
RRRRRRRRRRRRRRRow014
RRRRRRRRRRRRRRRRow015
98 POP-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) Compile and upload the code or sketch to POP-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
100 POP-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
102 POP-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.
104 POP-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.
106 POP-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
108 POP-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
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
-_-..-
-
.-.--
.-
.-.-,-
-,
.-.
.-.
.-..
.-.-
.
.
.
,.
..
,.,
.
.
.
,.
..
,.,
.-.-a-
..
-
--.--
--
-
---.
.
..
...
.--,-
.
,
,
,-a-
,
.--
.-.,---
,
,-
,-
.
,.--
,.-.,---
,.
,-
,.
,
,-
,
,
,-
,
Chapter 7
POP-BOT XT library file
110 POP-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
100 F
Row00
RRValueR=R20
RRRow02
RRRRow03
RRRRRow04
RRRRRRow05
RRRRRRRow06
RRRRRRRRow07
112 POP-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()
{}
220 F
100 F
T
B
6
6
1
2
A
T
M
e
g
a
3
2
U
4
100
Row00
RRValueR=R20
RRRow02
RRRRow03
RRRRRow04
RRRRRRow05
RRRRRRRow06
RRRRRRRRow07
RRRRRRRRRow08
RRRRRRRRRRow09
RRRRRRRRRRRow010
RRRRRRRRRRRRow011
RRRRRRRRRRRRRow012
RRRRRRRRRRRRRRow013
RRRRRRRRRRRRRRRow014
RRRRRRRRRRRRRRRRow015
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
114 POP-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
220 F
100 F
A
T
M
e
g
a
3
2
U
4
RRValueR=R20
RRRow02
RRRRow03
RRRRRow04
RRRRRRow05
RRRRRRRow06
RRRRRRRRow07
RRRRRRRRRow08
RRRRRRRRRRow09
RRRRRRRRRRRow010
RRRRRRRRRRRRow011
RRRRRRRRRRRRRow012
RRRRRRRRRRRRRRow013
RRRRRRRRRRRRRRRow014
Hello World
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]
116 POP-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()
{}
118 POP-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()
{}
120 POP-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()
{}
122 POP-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()
{}
124 POP-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()
{}
126 POP-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.
128 POP-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
......
130 POP-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. Pl ease 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
132 POP-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
134 POP-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
}
}
}
136 POP-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
138 POP-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
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 :
% duty cycle =
Toff Ton
Ton
100
................................................................(8.1)
PWM frequency =
T
1
Toff Ton
1
....................................................................(8.2)
Average DC motor voltage drop = Supply voltage x duty cycle (%) ............(8.3)
Chapter 8
POP-BOT XT movement control
M
Vs
Vm
Rs
Vm
t
Ton
Toff
T
Figure 8-1 : The PWM signal for driving DC motor
140 POP-BOT XT : The Arduino Compatible Mobile Robot kit
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.
4 8 12 16 20 24 28 32
t (ms)
Vm (V)
4.5
4 8 12 16 20 24 28 32
t (ms)
Vm (V)
4.5
4 8 12 16 20 24 28 32
t (ms)
Vm (V)
4.5
10ms
4 8 12 16 20 24 28 32
t (ms)
Vm (V)
4.5
18ms
20ms
Average voltage = 4.5 x 100% = 4.5V
(A)
(B)
(C
(D)
Average voltage = 4.5 x 90% = 4.05V
Duty cycle =
20
18
x100%
=
90%
Duty cycle =
20
20
x100%
=
100%
Duty cycle =
20
10
x100%
=
50%
Average voltage = 4.5 x 50% = 2.25V
Duty cycle =
20
4
x100%
=
20%
Average voltage = 4.5 x 20% = 0.9V
Figure 8-2 : Shows the relation between the different duty cycle
and voltage accross the DC motor.
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.
Figure 8-3 : Shows the PWM signal at any duty cycle.
20%
50%
75%
0%
100%
142 POP-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. Pl ease 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
144 POP-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
}
146 POP-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
148 POP-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
150 POP-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.
152 POP-BOT XT : The Arduino Compatible Mobile Robot kit
POP-BOT XT : The Arduino Compatible Mobile Robot kit 153
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.
Operation :
If the switch is pressed; the logic
0I is sent to output and the red
LED is on.
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.
DATA
R3
220
R2
10k
R1
510
LED1
S1
Switch
Indicator
Signal output
GND
+V
Chapter 9
Object avoidance by contact
154 POP-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.
T
B
6
6
1
2
A
T
M
e
g
a
3
2
U
4
100
Press OK
to Start
(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
#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
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.
156 POP-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.
158 POP-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 wil l 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.
160 POP-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
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.
Chapter 10
POP-BOT XT line tracking
Figure 10-1 : The operation of ZX-03 Infrared reflector sensor board
with white and black surface
Infrared LED
Photo-transistor
White surface
10k
TCRT5000
510
+V
GND
OUT
High output voltage
Infrared LED
Photo-transistor
Black surface
10k
TCRT5000
510
+V
GND
OUT
Low output voltage
c
u
r
r
e
n
t
f
l
o
w
c
u
r
r
e
n
t
f
l
o
w
162 POP-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
164 POP-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.
TB6612
1
0
0
T
B
6
6
1
2
100
L
=
1
0
0
R
=
1
0
0
(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.
TB6612
1
0
0
T
B
6
6
1
2
100
L
=
9
0
0
R
=
9
0
0
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
166 POP-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
168 POP-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.
TB6612
100
TB6612
100
TB 6612
100
TB 6612
100
TB661 2
1 00
T B 6 6 1 2
100
1
4 5 6
2 3
2. The left sensor is out from talbes edge : the robot moves backward and
spins right then moves forward again.
TB6612
100
TB6612
10 0
T B 66 1 2
100
3. The right sensor is out from talbes edge : the robot moves backward and
spins left then moves forward again.
T B6612
1 0 0
TB6612
1 0 0
T B 6 6 1 2
1 0 0
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.
170 POP-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 POP-B OT 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.
TB6612
1
00
172 POP-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.
TB6612
1
0
0
(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 ?
174 POP-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.
176 POP-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
178 POP-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.
180 POP-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
Liusting A15-1 : MultipleCrossingTrack.ino ; sketch file for muitiple
crossing line tracking activity of the POP-BOT XT
}
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);
}
}
182 POP-BOT XT : The Arduino Compatible Mobile Robot kit
POP-BOT XT : The Arduino Compatible Mobile Robot kit 183
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
Chapter 11
Touchless object avoiding
Infrared LED transmitter Infrared Receiver
GND Vout Vcc
GP2D120
4 8 12 16 20 24 28 32 0
0
0.4
0.8
1.2
1.6
2.0
2.4
2.8
Output voltage (V)
Distance (cm)
Figure 11-1 : GP2D120 pin assignment, operation and characteristic
curve
1st measure 2nd measure
Not stable 1st output 2nd output n output
n measure
38.39.6 ms
5 ms
Measurement
Vout
Supply
* Use Kodak R-27 gray-white
paper. The white side has a
90% reflection rate, made
from a material that reflects
light for range measurement.
184 POP-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.
1
5 V
2914
R