You are on page 1of 110

V2.

0 User Manual
A uniquely designed, complete robot kit to get you started in
building and programming!
Table of Contents
Introduction: Before You Begin ............................................................................................................................ 4
Chapter 1: Introduction to Electronics ................................................................................................................. 5
Electricity .......................................................................................................................................................... 5
Resistors............................................................................................................................................................ 6
Understanding Voltage, Current, and Resistance............................................................................................. 7
Circuit Symbols ................................................................................................................................................. 7
Breadboards ..................................................................................................................................................... 8
Building a Basic Circuit ...................................................................................................................................... 9
Chapter 2: Basic Hardware Programming........................................................................................................... 10
The Arduino Board.......................................................................................................................................... 10
Digital Input/Output ....................................................................................................................................... 11
The Light Emitting Diode (LED) ....................................................................................................................... 13
Breadboarding to Prototype ........................................................................................................................... 14
Chapter 3: Introduction to C Programming ........................................................................................................ 15
The Basic Arduino Program ............................................................................................................................ 15
Constants and Variables ................................................................................................................................. 16
Control Statements......................................................................................................................................... 19
Chapter 4: Assembling Your Gearbox ................................................................................................................. 25
Identification of the Gearbox Parts ................................................................................................................ 25
Assembly of the Gearbox................................................................................................................................ 30
Chapter 5: Building Your Basic Pi-Bot ................................................................................................................. 43
Mounting the Gearbox ................................................................................................................................... 44
Installing Your Switch ..................................................................................................................................... 45
Setting Up Your Caster Wheel ........................................................................................................................ 47
Assembling Your Tires..................................................................................................................................... 49
Mounting the STEM Board Microcontroller ................................................................................................... 51
Setting Up Your Battery Pack Slide ................................................................................................................. 54
Chapter 6: Wiring and Programming Your Basic Pi-Bot ...................................................................................... 58
Basic Motor Wiring Schematic........................................................................................................................ 60
Wiring the H-Bridge ........................................................................................................................................ 61
Making Your Pi-Bot Move ............................................................................................................................... 66
Chapter 7: Distance Sensor ................................................................................................................................. 70

2
Assembly ......................................................................................................................................................... 70
Wiring the Distance Sensor ............................................................................................................................ 73
Wiring the LEDs............................................................................................................................................... 74
Programming the Distance Sensor ................................................................................................................. 76
Chapter 8: Line Tracking ..................................................................................................................................... 85
Line Tracking Sensor Assembly ....................................................................................................................... 85
Complete Pi-Bot Wiring Schematic................................................................................................................. 87
Basic Line Following Program ......................................................................................................................... 89
Line Following Advanced Programming ...................................................................................................... 93
Appendix A: Installing and Testing the IDE ......................................................................................................... 98
Preparing the Computer ................................................................................................................................. 98
Connecting the Arduino to the Computer .................................................................................................... 101
Testing the IDE .............................................................................................................................................. 105
Appendix B: Complete Pi-Bot Wiring Schematic .............................................................................................. 110

Notes by the Team


We are excited to have you join us the Pi-Bot Adventure! STEM Center USA created the Pi-Bot to offer
users a holistic robotics experience where they could taste multiple fields of engineering. The Pi-Bot first
launched on Kickstarter in 2014 and is now used by individual users as well as high schools and colleges
worldwide.
What is the Pi-Bot?
The Pi-Bot kit is a multidisciplinary robotics experience intended for high school and college aged
students and above. It includes an introduction to mechanical, electrical, and computer science
engineering.
What makes Version 2.0 special?
We have upgraded our Pi-Bot! Some of our main updates includes:
Extra wires
Streamlined choice of fasteners (with a couple extras included!)
Longer motor wires for easier motor wiring
Zip-ties to clean up your Pi-Bot
How do these instructions vary from Version 1.5?
Version 1.5 uses different types of fasteners at various locations. It also places the breadboard on the
opposite side of the chassis for cleaner wire routing. The video tutorials for the gearbox assembly and all
wiring are the same for Version 1.5 and Version 2.0 just watch out for the breadboard and fasteners
please! Version 2.0 Video Tutorials will be released by mid-October 2015.

3
Introduction: Before You Begin
Congratulations on purchasing your Pi-Bot Robot Kit! The Pi-Bot manual is meant to assist you in
building and programing. All of the instructions in this manual are designed to provide an easy step-by-
step method for every aspect of building your Pi-Bot, from start to finish. Make sure to take your time
and read through each lesson carefully. Pictures are included with every step for clarity.
This manual is for the Version 2.0 Pi-Bot which has minor changes from the Version 1.5.
Accompanying video tutorials can be found at:
http://www.stemcenterusa.com/pi-bot/tutorials-/
Before starting the assembly of your Pi-Bot, please check to make sure all necessary parts for your Pi-Bot
are included. Your kit should include the following items:

4
Chapter 1: Introduction to Electronics
Digital devices are widely used. Earlier, most electronic devices contained analog circuits which dealt
with continuously changing signals. Today, digital circuits are widely used. Personal computers and
smart phones are examples of digital devices that contain digital circuits. Digital devices use discrete
values which are zero (0) or one (1). The notation based on these two numbers is known as the Binary
system.

Electricity
The movement of electrons can be described by the analogy below:
The flow of water from one tank to another is a good analogy for an electrical circuit and the
mathematical relationship between voltage, resistance, and current. See Figure 1.1.
o Force: The difference in water levels (voltage)
o Flow: The flow of the water between the tanks (current)
o Resistance: The valve that limits the amount of water (resistance)

Figure 1.1

5
Resistors
A resistor is an electronic component that resists the flow of electrical current. A resistor is typically
used to control the amount of current that is flowing in a circuit. Resistor converts electrical energy into
heat. Resistance is measured in units of ohms () and named after George Ohm, whose law (Ohms
Law) defines the fundamental relationship between:
Voltage - measured in Volts [V]
Current - measured in amperes [A]
Resistance - measured in ohms []

A resistors rating can be identified by its color bands. Refer to Figure 1.2 below.

Figure 1.2: Courtesy of DigiKey

6
Understanding Voltage, Current, and Resistance
Ohms Law: V = IR
Units:
Current (I) Ampere
Voltage (V) Volt
Resistance (R) Ohm

Figure 1.3
Circuit Symbols
Below are basic circuit symbols that you should familiarize yourself with, as shown in Figure 1.4.

Figure 1.4
Be able to draw a circuit diagram for each circuit you create using the above symbols.

7
Breadboards
A breadboard is a reusable platform to quickly build and test electronic circuits. Breadboards are a
rectangular array of electrical contacts. Each contact in a row is electronically the same. See Figure 1.5,
below, for various breadboard sizes.

Figure 1.5
Each row is electrically the same. Figure 1.6 shows the back, disassembled view of the breadboard
where you can clearly see the rows. This means the voltage at any point along each row is the same.

Figure 1.6

Lighting up an LED

8
LED stands for light emitting diode. LEDs work like a one way street. They allow current to flow in one
direction only. The longer end of the LED is positive (anode) and the shorter end is negative (cathode).
An LED requires an appropriate resistor, based on the power supply, to drop the voltage. A simple LED
circuit is shown in Figure 1.7.

Figure 1.7

Building a Basic Circuit


The same circuit diagram is shown in Figure 1.8 but with the actual components. Compare this to the
symbols in Figure 1.7.

Figure 1.8
Understanding circuits is extremely important when wiring your Pi-Bot. Wire your own LED circuit like
the one in Figure 1.7 and Figure 1.8. You will have more practice and repetition in the following chapter.

9
Chapter 2: Basic Hardware Programming
The Basic Arduino Program
In this lesson, you will learn how to program the input/output ports of your STEM Board
microprocessor. The focus will be on functions needed for programming your robot. It is assumed that
you have a basic understanding of the C programming language, as described in Lesson 3: Introduction
to C Programming. After completing this lesson, you should be familiar with the digital I/O ports, the
analog-digital converter (ADC), and the pulse width modulator (PWM).

The Arduino Board


1. The STEM Board microprocessor and its features are shown in Figure 2.1. The functionality of
your STEM Board microprocessor is the same as an Arduino UNO Board.

Figure 2.1

10
2. The specifications for the STEM Board microprocessor are:
Microcontroller ATmega328
Operating Voltage 5V
Input Voltage (recommended) 7 12V
Input Voltage (limits) 6 20V
Analog Input Pins 6
Digital I/O Pins 14 (of which 6 provide PWM output)
DC Current for 3.3V Pin 50 mA
Flash Memory 32 KB of which 0.5 KB used by bootloader
SRAM 2 KB
EEPROM 1 KB
Clock Speed 16 MHz

Digital Input/Output
1. After plugging the STEM Board microprocessor into your PC using the USB connector, you
should notice that the green LED power light is turned on. You do not need to plug in the 9-volt
battery at this point as the board is now powered from the USB port.
2. If everything looks good, enter and run the program: led_01.ino, as shown in Figure 2.2. The LED
on your STEM Board microprocessor for channel 13 (as shown in Figure 2.2) should be flashing.

Figure 2.2: Program led_01.ino


3. As before, the program consists of two separate functions, setup () and loop ()
a. Note:
In the setup function, digital pin 13 is defined to an output pin.
Again, the loop function is the main program. The statement digitalWrite (13,HIGH);
is a function call to the digitalWrite. The first parameter is the pin number, as shown
at the top row of the STEM board microprocessor in Figure 2.1. The second
parameter, HIGH, is a predefined constant for 1. Likewise, LOW is a predefined
constant for 0.
Note that C is case-sensitive. Typing in High instead of HIGH will cause an error. That
is why HIGH is blue and High is black, reminding you that you are using predefined

11
constants. The use of predefined constants, such a HIGH and LOW, make the
program much more readable end easier to debug.
The delay is used to pause the program for 0.1 seconds.

Exercise 1
1. After you get the program: led_01.ino to run, modify it to:
a. Turn on the Board LED (digital I/O pin 13) and stay lit for 1 second.
b. After the 1 second, turn off for 0.1 seconds.
c. Repeat indefinitely.
2. We can use the predefined constants to make our programs easier to read. For example, pin 13
represents the board LED for our robot. We can make a global definition that Board_LED is 13,
as shown in Figure 2.3.
3. Beginner programmers are hesitant to use long descriptive variables. Typing Board_LED is more
time-consuming than typing 13, but program led_02.ino is much easier to understand than
led_01.ino. They do the exact same thing. So, make your programs as easy to read as possible.

Figure 2.3: Program led_02.ino


4. Now that you understand the use of digital I/O, lets connect our own LEDs to your STEM Board
microprocessor.

12
The Light Emitting Diode (LED)
1. LED is short for Light Emitting Diode and is shown in simple circuit in Figure 2.4.

Figure 2.4
2. The LED conducts electricity only in one direction. If the polarity of the diode is reversed, it will
not damage the LED, it will simply not emit light. What will damage the LED is too much current.
The LEDs included in the robot kit are .020 amps, commonly referred to as 20 ma (milliamps).
Therefore, a limiting resistor is needed in series with the LED, as shown in Figure 2.4.
3. Ohms Law is used to determine the current flow through the circuits:


I = or V = IR or R = =

V the voltage across the component


I the current flowing through the component
R the resistance of the circuit

4. In circuitry, ohms is a unit of electrical resistance and is represented by the symbol .


5. In our case, the LED will be connected on a digital I/O pin which has a HIGH output of 5 V. By
placing a 220 resistor in series, you are limiting the circuit through the resistor and LED to
about 20 ma. Let's connect the circuit shown in Figure 2.4 to your STEM Board microprocessor.
For this, we will need to use the breadboard.

13
Breadboarding to Prototype
1. The protoboard, commonly referred to as a breadboard, is used for prototyping electrical
circuits without needing to solder everything together. The term protoboard differentiates from
breadboards as protoboards typically require soldering while breadboard do not.
2. A diagram of the breadboard layout is shown in Figure 2.5.

Figure 2.5
3. Your mini breadboard has 170 connections arranged in groups of give, as shown in Figure 2.5
Any five connections within each group are electrically joined.
4. To connect the circuit shown in Figure 2.4 to the STEM Board, see Figure 2.6.

Figure 2.6

14
Chapter 3: Introduction to C Programming
This lesson assumes that the Arduino IDE is correctly installed on your computer and tested. If not, refer
to Appendix A to follow the installation process.

The Basic Arduino Program


1. Lets start with a simple program, as shown in Figure 3.1. This is the same program referenced in
Appendix A.

void setup()
{
// Your setup code here, to run once:
Serial.begin(9600);
}
void loop()
{
// Your main code here, to run repeatedly:
Serial.println("Hello World");
delay(1000);
}

Figure 3.1: Program - First.ino


2. The program consists of two separate functions, namely setup and loop. You will be adding
additional functions to your code, but you must have a setup function and a loop function in
every program that you write. Referring to the program, you should note:

The setup function is used to define certain parameters on the Arduino microprocessor.
In this example, the setup function includes the statement Serial.begin(9600); which
sets the communication speed of the serial port on the Arduino to 9600 baud. This will
allow the Arduino to communicate with the serial monitor on the PC. The () after the
name setup is the parameter list passed to the function. Since there are no parameters
being passed to the function, the list is empty. However, the () after the name is still
required. Following the function name is a { at the opening, and a matching } at the end
of the function. Everything between the first { and its matching } belong to the
function.

The // indicates that whatever follows is a Comment. Comments may begin in any
column. For example, one could write:

Serial.println("Hello World"); // used to print to a serial port

Use comments to help document the program.

The word void in front of the function names indicate that the functions are not
returning a value. We will discuss this more later.

15
In the case of the function Serial.begin(9600), the name of the function is
Serial.begin and when called, the program passes the value of 9600, which in this case
is the baud rate (transfer rate) for the serial communication. For another example,
when the function Serial.println("Hello World"); is called, the string Hello World is
a parameter being passed to the communication port.

The semicolon ; terminates the command. It is required. Note that the function name
void loop() is not terminated by a ;. That is because the function name contains the
lines between the { and } and therefore cannot be terminated.

The function delay(1000); calls a delay function where the parameter list contains the
number of millisecond to wait. In this case, there is a one (1) second delay. Note that
when the program executes this command, it is literally waiting the specified time. If
something is happening, such as a sensor value has changed, the Arduino
microprocessor will not see it during the wait time.

The void loop() is the main function and it must be in every Arduino code that you
write. It is the entry point for your code. The loop function is executed continuously,
that is, when the program reaches the end of the loop function, denoted by the last },
the Arduino goes back to the top the of the loop function and begins execution again.

Exercise 1
After you get the Hello Word program to run, modify it to:
1. Print your first name
2. Wait second
3. Print surname on the next line
4. Print a blank line
5. Wait 2 seconds
6. Repeat
If you have any difficulty with this exercise, ask your instructor for help.

Constants and Variables


1. Constants can be thought of as predefined variables that cannot change during the execution of
a program. There are two types of constants, which you will see in Figure 3.2:
a. User defined constant
b. Predefined constant
2. Dont be overwhelmed by the lengthy of the program. It is mostly print statements. We will see
shortly how we can reduce the number of lines to do the same thing.
3. Review the program in Figure 3.2. Then we will analyze it in the next steps.

16
#define var1 1
int const var3=1;
void setup()
{
Serial.begin(9600);
}

void loop()
{
const int var2 = 1;
int var4;
int var5=1;
boolean var6=false;

var4=1; // The value of c4 is now defined


Serial.print("var1 = ");
Serial.print(var1,DEC);
Serial.print(" var2 = ");
Serial.print(var2,DEC);
Serial.print(" var3 = ");
Serial.print(var3,DEC);
Serial.print(" var4 = ");
Serial.print(var4,DEC);
Serial.print(" var5 = ");
Serial.print(var5,DEC);
Serial.print(" var6 = ");
Serial.println(var6, DEC);

//var3++;
var4++;
var5++;
var6=true;

Serial.print("var1 = ");
Serial.print(var1,DEC);
Serial.print(" var2 = ");
Serial.print(var2,DEC);
Serial.print(" var3 = ");
Serial.print(var3,DEC);
Serial.print(" var4 = ");
Serial.print(var4,DEC);
Serial.print(" var5 = ");
Serial.print(var5,DEC);
Serial.print(" var6 = ");
Serial.println(var6, DEC);
Serial.println(" ");
delay(1000);
}

Figure 3.2: Program - Second.ino

17
4. You have two required functions: setup () and loop ()
5. We have added #define var1 1 to the first line of the program. This var1 is now a user defined
constant that cannot be changed .This also has a global definition, that is, var1 is equal to 1 for
all the functions. If you try to redefine var1, you will get a compile error. Another method to
define the var1 as a constant global variable will be to place the statement int const var1
before the first function call.
6. var2 is also a constant defined to be 1. However, it is local to the function loop (). Therefore, it
is not available in any functions.
a. Note: If the variable name var2 is used in another function, it will be a unique variable
that is local to that function.
7. var3 is a global integer variable because it is typed before the first function call.
8. var4 and var5 are integer variables and can be changed anywhere within the function. They
are local variables and their scope is limited to the function that they are defined (typed) in. Run
the programs and watch how the variables change as the programs are executed. The purpose
of the program is simply to print the values of each variable, then increment the variables using
the ++ command and print the values again.
9. Repeat the loop every 1 second. Make sure that you open the serial monitor after the program
is completely downloaded. As you can see, the constants var1 and var2 do not change.
10. For fun, try to change their values in the code and see what happens.
11. The value of var3 increments continuously, as it is a global variable and is not reset upon
successive loops. The values of var4 and var5 are local variables and get re-initialized at the
beginning of each loop. The only difference between var4 and var5 is that var5 is initialized
when it is typed. var4 is not, so it needs to be assigned a value prior to using it.
a. Note: Non-constant variables are referred to as variables, and constant variables are
referred to as constants.
12. var6 is a Boolean variable, which is often used with the predefined constants:
a. True defined as 1
b. False defined as 0
13. Be sure to look at the code and its output to help understand the use of the Boolean variables.
14. We will discuss integers, Booleans, and other variables in more detail later. For now, lets take a
look at some control statements in the next section.

18
Control Statements
1. The control statement is used to control the flow of the program. In this section we will be
addressing three of the commonly used control statements:
a. if statement
b. for statement
c. do while statement
2. The form of the if statement is as follows:

if(logical test)
{
statements are executed if logical true.

}
else if(logical)
{
statements are executed if the first logical is false and the
second logical is true.

else
{

statements are executed if none of the above logical are


true. This is the default condition.
}

3. Note that both the else if and else statements are optional.

19
4. Lets do the example as shown in Figure 3.3.

void setup()
{
Serial.begin(9600);
}

void loop()
{
int var1, var2;
var1 = 1;
var2 = 1;

if( var1 == 1)
{
var2 = 2;
}

Serial.print("var1 = ");
Serial.print(var1, DEC);
Serial.print(" var2 = ");
Serial.println(var2, DEC);
Serial.println(" ");
delay(1000);
}

Figure 3.3

5. Things to note about the if statement in the example:


a. The logical test is == not just =. A single = is an assignment statement.
b. In the statement var1 = 1, the value of 1 is assigned to the variable var1. In the
statement var1 == 1, the value of var1 is compared to the value of 1 and returns a
true if the values are equal and false if the values are not equal.
6. Take a few minutes to change the value of var1 in the example to see what happens to the
value of var2. Does the output make sense?
7. The logical operators are:
a. == test if equal
b. != test if not equal
c. < test if less than
d. > test if greater than
e. <= test if less than or equal to
f. >= test if greater than or equal to

20
8. Time for another example! Copy the program Fourth.pde shown in Figure 3.4.

void setup()
{
Serial.begin(9600);
}

void loop()
{
int var1;
var1 = 3;

Serial.print("var1 = ");
Serial.print(var1, DEC);
if( var1 == 1)
{
Serial.println(" is equal to 1");
}
else if( var1 < 1)
{
Serial.println(" is less than 1");
}
else if( var1 <= 4)
{
Serial.println(" is less than or equal to 4");
}
else
{
Serial.println(" unknown");
}
delay(1000);
}

Figure 3.4: Program Fourth.ino


9. Look at the use of the if, else if, and else statements. Does it make sense?

21
Exercise 2
Using the Fourth.ino program, edit the following:
Change the value of var1 = 0. What part of the if statement prints the results?
Change the value of var1 = 1. Why does the program say it is less than 1, but does not say it is
less than 4?
Change the value of var1 = 3. Does the program correctly state the value of var1 is less than 4?
Change the value of var1 = 7. This is the default value.
Try several numbers to make sure that you understand the program flow.
Try the != and >= logical operators.

1. Next we will look for the for statement, which is used for repetitive operations.
2. The form of the for statement is given by:

for(initialize the variable, exit condition, increment the variable)


{
statements to be executed in the loop
}

3. Lets jump into the example shown in Figure 3.5

void setup()
{
Serial.begin(9600);
}

void loop()
{
int var1;
for(int count=0; count<10; count++)
{
var1 = var1 + count;
}
delay(1000);
}

Figure 3.5: Program Fifth.ino


4. In the program Fifth.pde, the for statement is used to loop a set of statements ten times. You should
notice several items:
a. The variable var1 is typed and initialized in the int var1 = 0 statement.
b. The variable count is typed and initialized to 0 in the for statement, hence its scope is
limited to the for loop.
c. At the start of each of the for loops, count is tested to see if it is less than 10.
d. At the completion of each loop, the variable count is incremented by 1.

22
e. Experiment by changing the initial value of count and the logical test.
i. Note: Make sure that you SAVE on a regular basis when you are testing your code. It
is easy to get the program into an infinite loop, and sometime you may need to kill
(stop) the program.
5. For our last example, before we start controlling the hardware, lets combine the use of the if
statement and the for statement. The program shown in Figure 3.6 counts from 1 to 10 and
determines if the number is less than 5, equal to 5, or greater than 5.

void setup()
{
Serial.begin(9600);
}
void loop()
{
int var1=0;
for(int count=1; count<=10; count++)
{
if(count < 5)
{
Serial.print(count, DEC);
Serial.println(" is less than 5 ");
}
else if(count > 5)
{
Serial.print(count, DEC);
Serial.println(" is greater than 5 ");
}
else
{
Serial.print(count, DEC);
Serial.println(" is equal to 5 ");
}
}
while(1==1);
}

Figure 3.6: Program Sixth.ino

Exercise 3
1. Write a program based on the Sixth.pde to compute and print the number from 0 to 10 together
with the factorial of the number. The output of the program should look like this:
The factorial of 0 is 1
The factorial of 1 is 1
The factorial of 2 is 2
The factorial of 3 is 6

etc

23
Advanced Exercise
1. Modify the program to count from -5 to 5. For the negative numbers, the program should state
the factorial could be computed.
Congratulations on completing your Introduction to C programming!

24
Chapter 4: Assembling Your Gearbox
These are the first steps to enjoying your new Pi-Bot kit. Follow the directions and you'll be ready to
program it in no time! This first lesson covers how to build your gearbox, which will power your Pi-Bot.
The Tamiya Double Gearbox comes with various gearbox options. We have identified option C as the
most efficient gearbox for the Pi-Bot.

Identification of the Gearbox Parts


1. Your Pi-Bot comes in a specially-designed package. Locate and open the box for the Double
Gearbox kit. You should have three bags of parts and a gearbox housing, as shown in Figure 4.1.

Figure 4.1

25
2. Open the bag of hardware, as shown in Figure 4.2, and verify its contents.

Figure 4.2
Two (2) electric motors with wires
Two (2) hex shafts approximately 15mm in length
Two (2) smooth shafts approximately 28mm in length
Two (2) brass gear hubs 7mm in length
Two (2) 4mm spacers
One (1) hex wrench
One (1) tube of grease
One (1) package containing:
o Six (6) self-tapping screws approximately 17mm in length
o Two (2) tapping screws approximately 8mm in length
o Two (2) screws and nuts
o Nine (9) brass eyelets
o Three (3) grub screws (set screws)
o Two (2) motor purple pinion gears

26
3. Open one of the bags of gears, as shown in Figure 4.3, and verify its contents.

Figure 4.3
One (1) yellow crown gear
Three (3) blue 2-step gears
One (1) yellow final gear
Two (1) yellow long spacers and two short spacers (spaces are attached, as seen in the top
yellow part of Figure 1.3)

4. Use Figure 4.4 to help you recognize the different types of gears.

Figure 4.4
5. Open the second bag of gears and verify its contents. The bags should be identical.

27
6. Identify the gearbox housing, as shown in Figure 4.5.

Figure 4.5
7. Twist the gearbox housing parts apart, so they match Figure 4.6. Notice which housing parts are
considered left and right.

Left Right
Side Side

Figure 4.6

28
8. Organize the parts for ease of assembly. It is recommend to have a large open table space to
avoid losing any small parts. Identify that all parts are present, as shown in Figure 4.7.

Figure 4.7

29
Assembly of the Gearbox

1. Twist the large yellow bushing off of the yellow part, as shown in Figure 4.8. You will not need
the small yellow bushing.

Figure 4.8
2. Press a yellow bushing onto each of the smooth shafts, as shown in Figures 4.9 and 4.10. There
should be 3mm of exposed shaft from the flanged side of each bushing. Once you have made
both pieces, set them aside temporarily.

Figure 4.9 Figure 4.10


3. Locate the right side of the housing.
4. Place a gear hub on each of the hex shafts approximately 18mm from the end and secure with a
grub screw. Do no over-tighten the grub screw, this will be adjusted later on. See Figures 4.11
and 4.12.

Figure 4.11 Figure 4.12

30
5. Twist off the top of the tube of grease. Save the top as it can be used to seal the tube later on.
6. Place two eyelets into the inside center holes of the right side of the housing, as shown in Figure
4.13.

Figure 4.13
7. Carefully apply a small amount of grease to the hex shaft next to both sides of the gear hub, as
shown in Figure 4.14.

Figure 4.14

31
8. Insert the 26mm (longer) end of the hex shaft into the rear eyelet, as shown in Figure 4.15.

Figure 4.15
9. Locate the smooth shaft assembly, which was built in step 1, and apply a small amount of grease
to the 3mm end, as shown in Figure 4.16.

Figure 4.16

32
10. Insert the 3mm (shorter) end into the remaining eyelet on the gearbox housing, as shown in
Figure 4.17.

Figure 4.17
11. Insert a yellow final gear onto the hex shaft, such that the hub of the gear enclosed the gear
hub. Look carefully at Figure 4.18, and identify how the gear hub is enclosed.

Figure 4.18

33
12. Apply a small amount of grease to both of the exposed shafts on the inner part of the gearbox
housing, as shown in Figure 4.19.
a. Note: Do not apply grease to the outside portion of the hex shaft. This is where the
wheel will be attached.
b. You may need to squeeze the tube to get the grease out from the bottom.

Figure 4.19
13. Place a blue 2-step gear onto the smooth shaft such that the small diameter gear mates with the
yellow final gear, as shown in Figure 4.20.

Figure 4.20

34
14. Place a second blue 2-step gear on the hex shaft such that the smaller diameter mates with the
larger diameter gear from the first blue 2-step gear, as shown in Figure 4.21.

Figure 4.21
15. Place the yellow crown gear on the smooth shaft, such that the small diameter gear mates with
the larger diameter gear of the second blue 2-step gear, as shown in Figure 4.22.

Figure 4.22

35
16. Place one 4mm spacer (silver) onto the hex shaft, as shown in Figure 4.23.

Figure 4.23
17. Take (2) eyelets, and place one on the smooth shaft and one on the hex shaft, as shown in
Figure 4.24.

Figure 4.24
18. Holding the gear assembly carefully so that the shafts are vertical, attach the center section of
the gearbox housing to the gear assembly, as shown in Figures 4.25 and 4.26.

36
a. Note: In Figure 4.26, there is an open area where you can see all the gears. If you see a
grey horizontal shaft going through this area, you have mated the center housing
backwards.

Figure 4.25 Figure 4.26


19. After ensuring that the gearbox housing parts are mated correctly, locate and insert three
17mm self-tapping screws to hold the assembly together, as shown in Figure 4.27. The screws
should be tightened and snug.
a. Note: There are 4 holes, but only 3 screws inserted. The front lower hole is for
alignment only. Inserting a screw into this location will damage the housing.
b. Caution: Do no over-tighten the screws!

Figure 4.27
20. Congrats, the right side of your gear housing is now finished!
21. Repeat steps 2 18 for the left side of the housing. The completed left side of the gear assembly
is shown in Figure 4.28.

37
Figure 4.28

22. Verify that both sides of the housing are mated to the center correctly. If so, then locate and
insert three 17mm self-tapping screws to hold the assembly together, as shown in Figure 4.29.
The screws should be tightened and snug.
a. Caution: If the housing sides are not meshing together, do not force them. Follow step
23 to fix the housing.

Figure 4.29

38
23. The left side of the housing may not close correctly, as shown in Figure 4.30. Do not force them
together, as this will damage the housing. Instead, while holding the two parts together, use the
hex wrench to loosen the left side Grub screw. See Figures 4.31 and 4.32. This will allow the two
parts to mate properly. Continue to hold the two housing parts together, then tighten the Grub
screws.

Figure 4.30

Figure 4.31 Figure 4.32

39
24. The complete gearbox housing is shown in Figure 4.33.

Figure 4.33
25. Attach a purple pinion gear on to each of the two motor shafts, as shown in Figure 4.34. Do not
push on the motor body. Support the opposite end of the shaft, as shown in Figure 4.35. Your
motors should look like Figure 4.36.

Figure 4.34 Figure 4.35

40
Figure 4.36
26. Install the motors into the front of the gear assembly making sure that the electrical contacts
face outward. See Figures 4.37 and 4.38.
a. Note: Wires have already been soldered to your motors. Place the motors so that the
blues and whites are aligned, as shown in Figure 4.38. Notice how the blue wires are on
the top.

Figure 4.37

Figure 4.38

41
27. Slip on the motor retaining band (T5) in between the motors, as shown in Figures 4.37, 4.39,
4.40.

Figure 4.39 Figure 4.40


28. Lastly, apply grease to all of the gears, as shown in Figure 4.41.

Figure 4.41
Note: You will have some leftover parts after your assembly. This is okay! Keep these spare parts in a
bag for future projects.
Congratulations, your gearbox assembly is complete! You may test your completed gearbox with a 3-
volt power source.

42
Chapter 5: Building Your Basic Pi-Bot
Now that you've successfully completed assembling your gearbox, it's time to build your Pi-Bot!

1. Identify your Pi-Bot chassis. Remove the brown tape overlaid on the chassis, as shown in Figure
5.1. The top side can be identified by the countersink holes. You can also identify the top side by
the additional switch hole on the right side of the chassis. Orient your chassis as show below,
with countersunk holes facing up.

Countersunk
holes

Switch
hole

Figure 5.1
2. Mount the breadboard to the lower left section of the body, as shown in Figure 5.2. The
breadboard should be approximated 3mm from the edge.
a. Note: The breadboard in the figure is white. Your breadboard may come in any color!

Figure 5.2

43
Mounting the Gearbox
3. Locate two (2) flat head 4-40 x 3/8 screws and two (2) 4-40 nuts.
4. Locate your assembled gearbox from the previous chapter. Flip your chassis over, so that the
gearbox will be mounted to the underside of the chassis, as shown in Figure 5.3. Notice how the
motors point to the rear of the body.

Figure 5.3
5. Now mount the gearbox by using the two lower, center countersink holes, as shown in Figure
5.4.
a. Note: Use your pliers to hold the nut as you tighten your screw. The head of your screw
should fit snugly into the countersink hole.

Figure 5.4

44
Installing Your Switch
6. Locate the bag with the following items, as shown in Figure 5.5:
a. Switch with soldered wires
b. Flat and locking washers
c. Two (2) matching nuts
d. Note: Pay careful attention to how the nuts and washers are arranged in the proper
order for installation in Figure 5.6.
e. Arrange your switch so that it is in the OFF position. This is when the lever is pointing
away from the side with empty terminal, as shown below.

Figure 5.5
7. Install the switch such that the toggle is on the top of the body and the wires are on the
underside of the chassis, as shown in Figure 5.6. One nut and the flat washer should be installed
on the top of the switch. One nut and the locking washer should be on the underside of the
chassis.
a. Arrange the switch so that the OFF position points towards the backend of the chassis
(towards the breadboard side).

Figure 5.6

45
8. Insert two (2) 4-40 x 3/8 screws in the two holes next to the switch at act as terminal blocks.
When mounting the screws, the eyelets of the switch wires should be captive, as shown in
Figure 5.7.

Figure 5.7
9. Figure 5.8 depicts the screws pointing up through the top side of your Pi-Bots body. This will
later be used to power the gearbox during testing.

Figure 5.8

46
Setting Up Your Caster Wheel

10. Locate the front caster parts as shown in Figure. 5.9.


a. Note: You will need to remove the brown cover from the clear component, as shown in
Figure 5.10.

Figure 5.9 Figure 5.10


11. Assemble the front caster using the provided screws and nuts, as shown in Figure 5.11. Notice,
we use the large spacer to make the Pi-Bot level.

Figure 5.11
12. Locate two (2) 3/4 inch nylon spacers and four (4) 4-40 x 3/8 screws, and assemble them as
shown in Figure 5.12.

47
Figure 5.12
13. Mount the assembled caster to the rear bottom of the body, as shown in Figure 5.13. Route the
motor wires through the hole above the caster.

Figure 5.13
14. Now we will install the 1 standoffs for the front line sensor. Locate the two remaining
countersunk holes on your Pi-Bot chassis.
15. Mount two (1) inch standoff spacers using two (2) flat head 4-40 x 3/8 screws, as shown in
Figure 5.14. Do not mount the line sensor at this time.

48
Figure 5.14

Assembling Your Tires


16. Locate the Sports Tire set, as displayed in Figure 5.15.

Figure 5.15
17. Assemble the wheels as shown in Figure 5.16.
a. The wheel hubs should be attached to maximize the wheel base. In other words, insert
the screws into the deeper side of each wheel and the nuts into the more shallow side.

49
b. You can find detailed instructions at:
https://www.youtube.com/watch?v=mWdVtPwpJ8M

Figure 5.16
18. The Pi-Bot with correctly installed wheels are depicted in Figures 5.17.
a. Note: Do no force the wheels all the way in! Keep a reasonable clearance between the
tires and the body.

Figure 5.17

50
Mounting the STEM Board Microcontroller

19. Now you will begin mounting your Arduino-compatible STEM Board microcontroller. Locate the
following items, as shown in Figure 5.18:
a. Four (4) 1 nylon
b. Clear plastic microprocessor mounting board
c. Four (4) 4-40 x 1/2 screws
d. Four (4) 4-40 x 3/8 screws

Figure 5.18
20. Attach four (4) 1/2 nylon standoffs to the bottom of the microprocessor mounting board using
four (4) 4-40 x 3/8 screws, as shown in Figure 5.19.
a. Note: You will need to peel off the brown layer from the microprocessor mounting
board.

Figure 5.19

51
21. Attach the STEM Board microprocessor to the top of the clear plastic mounting plate using four
(4) 4-40 x 3/8 screws and four (4) 4-40 nuts. See Figures 5.20 and 5.21.
a. Note: There is only one configuration that allows the STEM Board to fit onto the
mounting plate.

Figure 5.20

Figure 5.21
22. Locate the clear battery pack rails, there should be two wider ones and two thinner ones. Next,
get four (4) 4-40 x 1/2" screws. See Figure 5.22.
a. Note: You will have to peel off the brown layer from the rails.

52
Figure 5.22

23. Stack the rails so that the thinner one is adjacent to the chassis, and the thicker rail is on top.
This creates a notch for the battery pack slider. Pay careful attention to Figure 5.23 to see how
the rails are oriented. Use the 1/2" screws to mount the entire STEM Board and rails together.
a. Note: You will need to insert the screws from the underside of the chassis.

Figure 5.23

53
Setting Up Your Battery Pack Slide

24. The battery pack slide will be inserted into the battery rails you created in Step 22. Locate the
following items, as shown in Figure 5.24.
a. The three AA battery pack carrier
b. Clear plastic battery slide
c. One Velcro set

Figure 5.24
25. Peel off the brown layer from the plastic battery slide. Then place a piece of Velcro on the
battery pack and battery slide, as shown in Figure 5.25.

Figure 5.25

54
26. Insert the completed battery pack slide into the slots underneath the STEM board mount. You
may need to loosen or tighten the underside screws to lock the battery slide in place. See Figure
5.26 for the inserted battery pack slide.

Figure 5.26
27. Locate your 9V battery case and one Velcro set, as shown in Figure 5.27.

Figure 5.27

55
28. Place one Velcro on the underside of the 9V battery case and one of the Pi-Bot chassis. Refer to
Figure 5.28 for the placement of the Velcro.
a. Note: The battery case should have the switch facing upwards.

Figure 5.28

Congratulations! You have completed the assembly of the Basic Pi-Bot! Your Pi-Bot should look similar
to Figure 5.29.

56
Figure 5.29
Now that your Basic Pi-Bot is complete, we are now ready for the most exciting part making your Pi-
Bot move! The next lesson will go over the motor wiring.

57
Chapter 6: Wiring and Programming Your Basic Pi-Bot
Now that youve successfully completed building your basic Pi-Bot, you are now ready to wire your
motors!

1. Locate two nuts and the positive (red) jumper wire with a tab from your bag of wires, as shown
in Figure 6.1.

Figure 6.1

2. Attach the jumper wire tab to the right switch terminal, secure it with a nut. Then attach the
positive (red) wire from the battery pack to the left switch terminal, secure it with a nut. See
Figure 6.2.

Figure 6.2
3. Figure 6.3 depicts the motor (H-bridge) controller. Get familiar with the pin configurations.

58
a. Note: The motor controller has multiple solder pads on the right side of the board.
These solder pads will be used to orient the controller on the breadboard. When
installing the controller in the breadboard, make sure the solder pads are on the right
side of the body as shown in Figure 6.4.

Figure 6.3

4. Place the motor controller in the breadboard, as shown in Figure 6.4.

Figure 6.4

59
5. Route your motor wires through the center hole, if you have not done so already. We have
labeled our motor wires with L and R to make the wiring more clear. See Figure 6.5.

Figure 6.5

Basic Motor Wiring Schematic


6. Review the Figure 6.6 schematic to get familiar with the wiring and motor controller pins.

Figure 6.6

60
Wiring the H-Bridge

7. Connect positive (red) wire from the right power switch terminal to motor controller pin 15. See
the schematic in Figure 6.6 and Figure 6.7

Figure 6.7

8. Locate four (4) white male-male wires and one (1) black male-male wire, as shown in Figure 6.8.

Figure 6.8

61
9. Connect the following wires, as shown in Figures 6.9 and 6.10:
a. Ground (black) male-male wire from the STEM Board to motor controller pin 1.
b. Battery pack negative (black) wire to motor controller pin 16.

Figure 6.9 Figure 6.10

10. Wire the left and right motors to the motor controller, as shown in Figure 6.11.

62
Figure 6.11

11. Connect the motor controller to the STEM Board as shown in Figure 6.12. The connections
between the STEM Board and H-Bridge should be as follows:
a. STEM Board Pin 3 will go to H-Bridge Pin 3
b. STEM Board Pin 5 will go to H-Bridge Pin 4
c. STEM Board Pin 6 will go to H-Bridge Pin 5
d. STEM Board Pin 11 will go to H-Bridge Pin 6

63
Figure 6.12

12. Notice that H-Bridge Pin 2 is not used.


13. A close up view of the completed breadboard is shown in Figure 6.13.

Figure 6.13
14. Make sure the power switch is turned OFF. Remember, the power switch is arranged in the OFF
position when it is pointing to the rear of your Pi-Bot, or away from the empty terminal. See
Figure 6.14.

64
Figure 6.14
15. Insert a 9V battery into your 9V battery case. You will need to unscrew the bottom lid.
16. Plug the 9V battery into the 9V socket on the STEM Board to test it out. Look for the green LED
on the STEM Board to turn on.
a. Note: Do not turn on the power switch to the motor controller yet!
Congratulations! You have finished wiring your motors, and your Pi-Bot is now ready for programming!

65
Making Your Pi-Bot Move

1. Go to http://www.stemcenterusa.com/pi-bot/downloads-/ and download the sample codes.


2. Open Arduino IDE and open the MotorTest program
a. You may need to navigate to the appropriate folder on your computer.
3. You can enter and run the program in Figure 6.15, shown on the next page.

MotorTest Comments
Download this program and run it. If everything is hooked up as shown in the wiring diagram, the wheels
will turn forward for 2 seconds, stop for 1 second, reverse for 1 second, and then stop for 1 second. If
your robot is spinning or not moving forward, check your wiring again.

Common Mistakes:
Motor connection leads on the H-Bridge are swapped
Wires are not connected to the right pins on the STEM Board

Once you have determined the robot is running the program correctly, you can modify the program to
do different tasks. Review the following statements to familiarize yourself with the program in Figure
6.15.

STEM Board Pins 3 (IN1) and 5 (In2) control the left motor
IN1 and IN2 both cannot be a positive value simultaneously
A positive value for IN1 & zero for IN2 moves the left motor forward
A zero for IN1 & a positive value for IN2 moves the left motor backward
STEM Board Pins 6 (IN3) and 11 (IN4) control the right motor
IN3 and IN4 both cannot be a positive value simultaneously
A positive value for IN3 & zero for IN4 moves the right motor forward
A zero for IN3 & a positive value for IN4 moves the right motor backward

We are going to use the analogWrite function to control the motors. This will allow the motors to
change speed.

66
Figure 6.15

67
The program provided in Figure 6.15 is not an efficient method for programming motor controls. The
next program, shown below in Figure 6.16 is similar to the previous program except now it uses function
calls. Using function calls makes the program compact. You can make function calls as many time as you
need without rewriting the same code. Test out the new program and try using function calls in future
codes.

Figure 6.16

68
Exercise 1
Using the program provided in figure 2.40, make modifications to control the motors to move the
wheels forward for 5 seconds, stop for 2 seconds, reverse for 3 seconds, and stop indefinitely.

Exercise 2
Add another function called TURN. Have it turn the wheels in opposite directions. This will cause your Pi-
Bot to spin in circles.

Congratulations! You have successfully tested the motion control capabilities of your Pi-Bot!

69
Chapter 7: Distance Sensor
The HC-SR04 ultrasonic sensor uses sonar to determine the distance to an object just like bats and
dolphins. Since they are used to determine distance, ultrasonic sensors are popularly known as distance
sensors. Ultrasonic sensors offer excellent non-contact range detection from 2cm to 400 cm or 1 to 13
feet.

Assembly
1. Locate the ultrasonic sensor, LED adapters, and ultrasonic mount, as shown in Figure 7.1.

Figure 7.1
2. LEDs can be attached to the ultrasonic sensor mount using the adapters. You should be able to
gently push the green and red LEDs through the adapters. See Figure 7.2.

Figure 7.2

70
3. Connect four (4) 20 cm female-male wires to the ultrasonic sensor as follows, as shown in Figure
7.3:
a. VCC Red
b. Trig Yellow
c. Echo Green
d. GND Black

Figure 7.3
4. Attach the ultrasonic sensor using four (4) 0-80 x 1/2" screws and nuts (they come in a separate
bag). See Figure 7.4.
a. Caution: Do not force the ultrasonic sensor into the mounting bracket. Do not
overtighten the screws. These components are fragile and damage may easily occur.

Figure 7.4

71
5. Use one (1) 4-40 x 3/8 screw and nut to mount the ultrasonic assembly on the left side of the
body, as shown in Figure 7.5.

Figure 7.5
6. Route all of the wires underneath the STEM Board, as shown in Figure 7.6.

Figure 7.6

72
Wiring the Distance Sensor
1. Locate two (2) male-male 20 cm wires, 1 black and 1 red. See Figure 7.7.

Figure 7.7
2. Jumper wires are used to create more pins for power and ground. They also help clear the
clutter of wires. See Figure 7.8 and a close-up of 7.9.
a. Use the red wire as a jumper wire from your STEM Board 5V Pin to the breadboard.
b. Use the black wire as a jumper wire from your STEM Board GND to the breadboard.

Figure 7.8

73
Figure 7.9 Black GND Jumper Red 5V Jumper

3. Connect the four (4) 20cm ultrasonic wires to the following:


a. VCC Red to breadboard positive 5V (use the jumper wires you have already set up so
that the VCC lead connects to the breadboard)
b. Trig Yellow to Pin 2
c. Echo Green to Pin 4
d. GND Black to breadboard GND (use the jumper wires you have already set up so that
the GND lead connects to the breadboard)

Wiring the LEDs


4. Now you will need to wires your LEDs. As discussed in the Introduction to Electronics and Basic
Hardware Programming chapters, an LED requires a resistor to drop the voltage. Figure 7.10
shows the two (2) 330 resistors that you will need.

Figure 7.10

74
5. Connect the lead of the Red LED through the dropping resistor to STEM Board digital pin 13.
Connect the lead of the Green LED through the dropping resistor to STEM board digital pin 12,
as shown in Figure 7.11.
a. Note: White jumper wires are used from Pin 12 and Pin 13 to the dropping resistors.

Figure 7.11

6. For both LEDs, the black leads must connect to GND (again use the jumper wires to connect the
GND lead to the GND on the breadboard).

75
Programming the Distance Sensor
The HC-SR04 ultrasonic distance sensor board is a practical component for your Pi-Bot. Once
programmed, your Pi-Bot will be able to detect an object in front of it and determine its distance.

Note: VCC is the board +5V power supply and the wire is always colored red. The Ground wire is
always colored black. Consistency between these colors will help prevent accidental electrical
damage to the components.

The SR04 ultrasonic detector is used to determine the distance of an object in front of your Pi-Bot. This
is accomplished with the use of an ultrasonic transmitter and an ultrasonic receiver. The sensor emits a
chirp using the transmitter and listens for an echo on the receiver. The time it takes for the return echo
to be detected is proportional to the distance to the object.
The following program, UltraSonicSensorTest is simple and easy to understand. Download this program
from http://www.stemcenterusa.com/pi-bot/downloads-/ and run it. Open the serial monitor to view
the sensor output as you move an object (wave your hand) in front of the distance sensor. Notice the
screen output is both in cm and inches.

The program will give you erroneous (large numbers) results when the object is out of range, too close.
Modify the program to see the results in cm or inch only.

76
UltraSonicSensorTest Program

Now, let's use the ultrasonic sensor to control an LED. Download the program
UltraSonicSensorTestwithLED and run it. The RED LED will light whenever the distance to an object is
less than 10cm.

77
UltraSonicSensorTestwithLED Program

78
Using Interrupts (advanced programming)
It is important that the program does not spend all of its time polling the sensor to determine the
distance to an object. To allow the STEM Board processor to perform more than one task such as
sensing the distance using the ultrasonic and controlling the motors for line following, interrupts will be
used. Interrupt control is a technique which allows the STEM Board to temporarily suspends what is
doing (such are controlling the motors) to service a change on an input pin (such as a timed ultrasonic
echo response). This effectively allows the STEM Board to perform two tasks at the same time.

A program demonstrating the use of interrupt control for the ultrasonic sensor will be available soon.

Obstacle Avoidance Using the Ultrasonic Sensor


In this lesson, you will program your Pi-Bot to prevent accidents. Combining with what we have learned
about the ultrasonic sensor and motion control, we shall now investigate obstacle avoidance. Using the
program shown below, your Pi-Bot will continue forward at a medium speed until an obstacle is
detected within 10cm of the sensor. Upon detecting the object in front of the sensor, your Pi-Bot will
reverse and make a left turn, and then will proceed go forward.

The program has numerous print statements. Open the serial monitor window to see what is going on.
Once you understand, you can turn off all the print statements and serial monitor.

79
ObstacleAvoidance Program

80
ObstacleAvoidance Program CONTINUED

Obstacle Avoidance with LED


Now, let's use the ultrasonic sensor to control two LEDs as the robot moves forward and detect an
obstacle. Download the program ObstacleAvoidancewithLED and run it. GREEN LED will be on as the
robot moves forward and the RED LED will light up when the robot encounters an obstacle.

81
ObstacleAvoidancewithLED Program

82
ObstacleAvoidancewithLED Program CONTINUED

83
ObstacleAvoidancewithLED Program CONTINUED

Exercise 1
Modify the forward speed and the backward speed of your Pi-Bot. Try different speeds on the two
wheels when traveling in reverse.

Exercise 2
Upon detecting an obstacle, have your Pi-Bot reverse in different directions. For example, upon
detecting the first obstacle, have your Pi-Bot reverse while turning to the right. The next time it detects
an obstacle, have your Pi-Bot turn to the right.

84
Chapter 8: Line Tracking
Line following is a very important and fun activity. Many real world systems including robots performing
warehouse operations use line following activities. Speaking of warehouse operations, it may be
interesting to know that not too long ago, Amazon paid almost 1 billion dollars for Kiva System, a
company that makes robots for warehouse operations. These Kiva robots are strong and silent. They
replace the use of humans with forklifts. These robots use pretty much all techniques our students learn
and more: going in a straight line, turning, machine vision, line following, obstacle avoidance, dead
reckoning and bar code reading. For a day in the life of Kiva Robot, take a look at the following video:
http://www.youtube.com/watch?v=6KRjuuEVEZs

There are several competitions focusing on line following. You can use one, two, three or even more
sensors for line following. In this lesson, we will be using three light sensors.

Before we attempt to do line follow, the line sensors should be assembled and tested.

Line Tracking Sensor Assembly


1. Connect five (5) 30cm female-male wires to the line sensor as follows, as shown in Figure 8.1:
a. VCC Red
b. L Yellow (sensor on the left)
c. C Green (sensor at the center)
d. R Blue (sensor on the right)
e. GND Black

Figure 8.1

85
2. Locate two (2) 4-40 3/8 screws to attach the line sensor to the nylon spacers. See Figure 8.2.
a. Note: Notice the red LEDs are pointed upwards.

Figure 8.2
3. Figure 8.3 shows the view of the robot from the underside showing the line sensor wiring.

Figure 8.3
4. Route the wires through the hole on top of the caster wheel.

86
5. Connect the wires as follows:
a. Power (Red) to STEM Board 5V or 5V on breadboard
b. L (Yellow) to STEM Board Pin 7
c. C (Green) to STEM Board Pin 8
d. R (Blue) to STEM Board Pin 10
e. GND (Black) to STEM Board GND or GND on Breadboard

Complete Pi-Bot Wiring Schematic

6. Figure 8.4 shows the wiring diagram of the line sensor array.
a. The diagram also shows connections for the ultrasonic sensor, motors, and LEDs.

Figure 8.4
7. Once you have completed the wiring, download the program LineFollowingSensorTest from
http://www.stemcenterusa.com/pi-bot/downloads-/
8. Open the serial monitor and run the program. Each of the line sensor outputs will be displayed.
You will see three columns, one for each line sensor.
0 indicates White
1 indicates Black

87
By moving the sensors over a black line, you should see the outputs toggle between 0
and 1. If this test is successful, you are ready to begin line following!

LineFollowingSensorTest

88
Basic Line Following Program
We will now discover how the line sensors will allow your Pi-Bot to detect and track a line.
Line following consists of two parts:
1. Determining the position of your Pi-Bot to a black line

First, your Pi-Bot determines its position relative to a black line with the use of line sensors,
located in the front. When the line sensor detects black, sensor outputs 1 indicating that most
of the light is absorbed. When the line sensor detects white, the sensor output is 0.

By using three line sensors, your Pi-Bot will know whether it is on a black line (left and right
sensors output 0 and the center sensor outputs 1), to the left of a black line, or to the right
of a black line.
2. Motor control

With this information, your Pi-Bot will control the speed of each motor individually to try and
get back over the line.
The diagram below visualizes parts 1 and 2.

89
Download and run the following program:
LineFollowing Program

90
LineFollowing Program CONTINUED

91
LineFollowing Program CONTINUED

Exercise 1
Write a program to follow a line with just one light sensor (use any, L, C, or R)?

Exercise 2
Write a program to follow a line with two light sensors, L and R.

Exercise 3
Compare the performance of all three programs
.

92
Line Following Advanced Programming
More advanced programming can be created to allow your Pi-Bot to operate more precisely. Run the
program, AdvancedLineFollowing below. This is an example of a more sophisticated line following
algorithm.
While your Pi-Bot will not run any faster using this program, it is more reliable and can easily track
around sharp corners. The program continuously samples each of the three line sensors and stores the
latest N samples for each detector where N can be any integer value between 2 and 50. The samples are
stored in three arrays, one for each detector. After each set of samples are read, the program places the
samples on the top of the arrays and shifts the current samples down for each array. The samples at the
bottom of the arrays are discarded. After the arrays are shifted down and the latest samples are placed
on the top of the arrays, a weighted sum is generated from the arrays for each of the detectors.
Basically, instead of having an on/off value for each detector, there are values related to how long your
Pi-Bot is has been off the line. The longer it has been off the line, the larger the differential speed is
between the wheels to get your Pi-Bot back on track.

In the program, N is set to 8. The speed value for each motor is controlled by the ratio of the weighted
sum of the side detectors to the center detector. This algorithm is very sensitive to the motor voltage
supplied by the 3 AA batteries. As the battery voltages lower with use, or if you are using rechargeable
NiCads batteries, the performance changes. To minimize this effect, the program reads the motor
battery voltage using the analog input and adjusts the PWM voltage accordingly. THEREFORE, YOU
MUST RUN A JUMPER FROM THE BREADBOARD, H-BRIDGE PIN 15 (MOTOR BATTERY POWER) TO A0
OF THE ANALOG INPUT ON THE STEM BOARD. WITHOUT THE JUMPER, THE PROGRAM WILL NOT
WORK CORRECTLY. Also, this will not fix dead batteries. If your batteries cannot supply enough current
to run the motors, no programming will help! As you familiarize yourself with the program, change the
values to experiment. You can use this program as a starting point or just as a learning tool to develop
your own (and better) control program.
AdvancedLineFollowing Program

93
AdvancedLineFollowing Program CONTINUED

94
AdvancedLineFollowing Program CONTINUED

95
AdvancedLineFollowing Program CONTINUED

96
AdvancedLineFollowing Program CONTINUED

Exercise 4 (Advanced)

Combine the line following with the collision detection. Your Pi-Bot should follow a black line, until an
obstacle is placed in front of it, at which time it stops.

97
Appendix A: Installing and Testing the IDE
Preparing the Computer
1. Go to www.arduino.cc and download latest version of the Arduino IDE which is the Arduino
1.5.6-r2-windows.exe file. The download may take several minutes, as the file size is 66 MB. See
figure A.1. Your instructor may provide a copy of the file on a CD or USB drive. Save the file in
the location c:\Arduino. You may need to create this folder before downloading the file. Your
computer may request that you allow the program to make changes as shown in Figure A.1. If
so, answer Yes.

Figure A.1
2. Go to the c:\Arduino installation directory and run the 1.5.6-r2-windows.exe file as shown in
Figure A.2. You will be prompted to agree to the license agreement. Click I Agree.

Figure A.2
3. It is recommended that you use the default installation options, as shown in Figure A.3. Click
Next.

98
Figure A.3

4. Select your destination folder and click Install, as shown in Figure A.4.

Figure A.4

5. After installation is complete, you should see the Arduino Setup: Completed dialog box, as
shown in Figure A.5.

99
Figure A.5
6. Use the Arduino command in the Start menu, or click on the icon on the desktop to open the
program, as shown in Figure A.6.

Figure A.6

100
Connecting the Arduino to the Computer
1. Close the IDE.
2. Plug the STEM Board microprocessor into an available USB port using the supplied USB cable.
3. The first time you plug the STEM Board into your computer, Windows should automatically
detect the newly attached device and attempt to find a driver for it. If Windows finds and
updates the driver, skip to the next section: Testing the IDE. In the likely event that Windows
cannot find the appropriate driver, follow the following steps.
4. Go to the Start Menu and select Devices and Printers, as shown in Figure A.7.

Figure A.7

101
5. Scroll down and double click on the Arduino UNO icon, as shown in Figure A.8.

Figure A.8
6. In the Arduino UNO dialog box, select the Properties tab, as shown in Figure A.9.

Figure A.9

102
7. Next, select the Change Settings button, as shown in Figure A.10.

Figure A.10
8. Select the Update Driver button to update the driver software, as shown in Figure A.11.

Figure A.11

103
9. Windows will prompt you, whether you would like Windows to automatically search for driver
software or browse your computer. Choose the second option: Browse my computer for driver
software, as shown in Figure A.12.

Figure A.12
10. Use the Browse button and select the location the C:\Arduino\arduino-0022\drivers, as shown
in Figure A.13. Click Next and Windows should install the correct driver.

Figure A.13

104
11. A Windows message should popup indicating that the device is ready for use.
12. We are now ready to test the system.

You are now ready to begin Chapter 3: Introduction to C Programming.

Testing the IDE


1. Open up the IDE. It should look similar to the IDE shown in Figure A.14.
a. Note: The boxed comments in Figure A.14 have been added to help understand the IDE.

Figure A.14
2. Most (but not all) of your interfacing with the IDE can be accomplished using the seven action
buttons directly below the menus. A brief description of each button is useful;

Button 1, (right pointing triangle), is used to VERIFY your code, which in Arduino
language is known as a sketch. Use this button to compile (convert) your code (the
sketch) to Arduino language, but not upload your code to the Arduino microprocessor.
This is very useful when you want to determine if the code you wrote is valid, but you
are not ready to execute it and do not want to waste time uploading.

105
Button 2, the STOP button, is used to stop the execution of the program. This is useful
for when you need to stop a runaway program. Note, however, there will be times that
the STOP button will not stop your code, and you will need to unplug the Arduino
microprocessor from the USB and/or shut down the IDE. Make sure that you save often
as not to lose any of your hard work.

Button 3, the NEW button, is use to create a new sketch. The new sketch is created in
the same IDE by default. However, if you hold the SHIFT key down while selecting the
NEW button, the new sketch is created in a new IDE.

Button 4, the OPEN button, is used to open an existing sketch. The existing sketch opens
in the same IDE by default. However, if you hold the SHIFT key down while selecting the
OPEN button, the existing sketch is opened in a new IDE.

Button 5, the SAVE button, is used to save the current sketch. Use it often! Dont lose
your work!

Button 6, the UPLOAD button, is used to compile (generate the Arduino machine code)
the current sketch and, if no errors result, upload it to the Arduino microprocessor. If
any compiling errors do occur, they will be shown in the output window at the bottom
of the IDE.

Button 7, the MONITOR button, is used to monitor your program by sending data from
the Arduino microprocessor back to your PC and display it in a monitor window.

Note: While the monitor tool is very valuable for debugging, it is extremely time-
consuming for the Arduino microprocessor. When it is not needed for debugging,
remove or comment out any of the monitor output. This is especially necessary when
performing the control algorithms.

3. Now that we have an understanding of action buttons, lets begin!

106
4. Make sure that the IDE is set up for Arduino UNO. Using Tools Board, select the Arduino
UNO, as shown in Figure A.15.

Figure A.15

107
5. Next, check that the STEM Board microprocessor is connected to a USB port. Do this by clicking
Tools Serial Port, as shown in figure A.16. A serial port must be selected. It will probably not
be port 12, as shown in Figure A.16. If you have multiple ports and the IDE cannot communicate
with the STEM Board, try changing the ports.

Figure A.16
6. We are now ready to write our first program.

108
7. Cut and paste (or type, if you like) the following code into the IDE. See Figure A.17.
void setup()
{
// Your setup code here, to run once:
Serial.begin(9600);
}
void loop()
{
// Your main code here, to run repeatedly:
Serial.println("Hello World");
delay(1000);
}

Figure A.17
8. SAVE it. You may wish to create a working directory to save your programs. DO NOT save your
programs into the c:\Arduino directory.
9. Click the VERIFY button. Did it compile without errors?
a. Note: This step is not really needed in this case, but it helps to understand the
functionality of the IDE buttons.
10. If so, click the UPLOAD button.
11. Open a monitor window by clicking the MONITOR button.
12. Does it continuously print Hello World? If so...

Congratulations! You have successfully run your first Arduino program.

109
Appendix B: Complete Pi-Bot Wiring Schematic

You might also like