When you have successfully completed each activity, turn on your call light and your instructor will check your work.
Activity 1:
Here is a screen capture of the Arduino Development Environment edit pane on the left, containing a simple sketch that sends a “Hello!” message to the Serial Monitor window on the right.
Open your Arduino software in the Start menu, CTE, Teched directory, and carefully type in the code in the text box:
void setup() { Serial.begin(9600); Serial.print("Hello!"); } void loop() { //Add code that repeats automatically here. }
Be sure you have capitalized “Serial” both times, or the sketch won’t work.
Also, notice in the figure that the sketch uses parentheses() and curly braces {}. Be sure to use the right ones in the right places!
Click the Verify button to make sure your code doesn’t have any typing errors.
Look for the “Binary sketch size” text in the message pane.
If it’s there, your code compiled and is ready to upload to the Arduino.
If there’s a list of errors instead, it’s trying to tell you it can’t compile your code. So, find the typing mistake and fix it!
Click the Upload button. The status line under your code will display “Compiling sketch…,” “Uploading…,” and then “Done uploading.”
After the sketch is done uploading, click the Serial Monitor button.
If the Hello message doesn’t display as soon as the Serial Monitor window opens, check for the “9600 baud” setting in the lower right corner of the monitor.
Use File → Save to save your sketch. Give it the name HelloMessage.
When you have successfully programmed your First and Last Name on the screen, turn your call light on and your instructor will check your work.
Activity 2:
How about having each "Hello!" message on a new line? That would make the messages scroll down the Serial Monitor, instead of across it. All you have to do is change print to println, which is short for ‘print line.’
Change Serial.print("Hello!") to Serial.println("Hello!").
void setup()
{
Serial.begin(9600);
Serial.println("Hello!");
Serial.println("Hello!");
Serial.println("Hello!");
Serial.println("Hello!");
}
void loop()
{
//Add code that repeats automatically here.
}
Upload the modified sketch and watch it print each "Hello!" message on a new line.
When you have successfully programmed your robot to print our your name multiply times on the screen, turn on your call light and your instructor will check your work.
Activity 3
Example Sketch – StoreRetrieveLocal
Use File → New to create a new sketch, and save it as StoreRetrieveLocal.
Enter or copy the code below into the Arduino editor.
Save the file, then upload it to the Arduino.
Open the Serial Monitor and verify that the values display correctly.
// Robotics with the BOE Shield - StoreRetrieveLocal void setup() { Serial.begin(9600); int a = 42; char c = 'm'; float root2 = sqrt(2.0); Serial.println(a); Serial.println(c); Serial.println(root2); } void loop() { // Empty, no repeating code. }
When you can successfully input different variables into your program, turn on your call light and your instructor will check your work.
Activity 4
Arithmetic operators are useful for doing calculations in your sketch. In this activity, we’ll focus on the basics: assignment (=), addition (+), subtraction (-), multiplication (*), division(/), and modulus (%, the remainder of a division calculation).
Open up the Arduino Language Reference, and take a look at the list of Arithmetic Operators.
The next example sketch, SimpleMath, adds the variables a and b together and stores the result in c. It also displays the result in the Serial Monitor.
Notice that c is now declared as an int, not a char variable type. Another point, int c = a + b uses the assignment operator (=) to copy the result of the addition operation that adds a to b. The figure below shows the expected result of 89 + 42 = 131 in the Serial Monitor.
Enter, save, and upload SimpleMath to your Arduino.
Check the result in the Serial Monitor. Is it correct?
// Robotics with the BOE Shield - SimpleMath void setup() { Serial.begin(9600); int a = 89; int b = 42; int c = a + b; Serial.print("a + b = "); Serial.println(c); } void loop() { // Empty, no repeating code. }
When you have successfully programmed your robot to solve a division, multiplication, addition and subtraction problem, turn on your call light and your instructor will check your work.
Activity 5
Your BOE Shield-Bot will need to make a lot of navigation decisions based on sensor inputs. Here is a simple sketch that demonstrates decision-making. It compares the value of a to b, and sends a message to tell you whether or not a is greater than b, with an if…else statement.
If the condition (a > b) is true, it executes the if statement’s code block: Serial.print("a is greater than b"). If a is not greater than b, it executes elsecode block instead: Serial.print("a is not greater than b").
Enter the code into the Arduino editor, save it, and upload it to the Arduino.
Open the Serial Monitor and test to make sure you got the right message.
Try swapping the values for a and b.
Re-upload the sketch and verify that it printed the other message.
// Robotics with the BOE Shield - SimpleDecisions void setup() { Serial.begin(9600); int a = 89; int b = 42; if(a > b) { Serial.print("a is greater than b"); } else { Serial.print("a is not greater than b"); } } void loop() { // Empty, no repeating code. }
Maybe your sketch needs to monitor for three conditions: greater than, less than, or equal. Then, you could use an if…else if…else statement.
// Robotics with the BOE Shield - SimpleDecisions void setup() { Serial.begin(9600); int a = 42; int b = 42; if(a > b) { Serial.print("a is greater than b"); } else if(a < b) { Serial.print("b is greater than a"); } else { Serial.print("a is equal to b"); } } void loop() { // Empty, no repeating code. }
A sketch can also have multiple conditions with the Arduino's boolean operators, such as && and ||. The && operator means AND; the || operator means OR. For example, this statement’s block will execute only if a is greater than 50 AND b is less than 50.
// Robotics with the BOE Shield - SimpleDecisions
void setup()
{
Serial.begin(9600);
int a = 52;
int b = 42;
if((a > 50) && (b < 50))
{
Serial.print("Values in normal range");
}
}
void loop()
{
// Empty, no repeating code.
}
Another example: this one prints the warning message if a is greater than 100 OR b is less than zero.
// Robotics with the BOE Shield - SimpleDecisions
void setup()
{
Serial.begin(9600);
int a = 52;
int b = -42;
if((a > 100) || (b < 0))
{
Serial.print("Danger Will Robinson!");
}
}
void loop()
{
// Empty, no repeating code.
}
When you have successfully programmed your robot to identify and print out equal to, greater than, less than values, turn on your call light and your instructor will check your work.
Activity 6
Many robotic tasks involve repeating an action over and over again. Next, we’ll look at two options for repeating code: the for loop and while loop. The for loop is commonly used for repeating a block of code a certain number of times. The while loop is used to keep repeating a block of code as long as a condition is true.
A for Loop is for Counting
A for loop is typically used to make the statements in a code block repeat a certain number of times. For example, your BOE Shield-Bot will use five different values to make a sensor detect distance, so it needs to repeat a certain code block five times. For this task, we use a for loop. Here is an example that uses a for loop to count from 1 to 10 and display the values in the Serial Monitor.
Enter, save, and upload CountToTen.
Open the Serial Monitor and verify that it counted from one to ten.
// Robotics with the BOE Shield - CountToTen void setup() { Serial.begin(9600); for(int i = 1; i <= 10; i++) { Serial.println(i); delay(500); } Serial.println("All done!"); } void loop() { // Empty, no repeating code. }
The figure below shows the for loop from the last example sketch, CountTenTimes. It labels the three elements in the for loop’s parentheses that control how it counts.
Initialization: the starting value for counting. It’s common to declare a local variable for the job as we did here with int i = 1; naming it i for ‘index.’
Condition: what the for loop checks between each repetition to make sure the condition is still true. If it’s true, the loop repeats again. If not, it allows the code to move on to the next statement that follows the for loop’s code block. In this case, the condition is “if i is less than or equal to 10.”
Increment: how to change the value of i for the next time through the loop. The expression i++ is equivalent to i = i + 1. It makes a nice shorthand approach for adding 1 to a variable. Notice that ++ comes after i, meaning “use i as-is this time through the function, and then increment it afterward.” This is the post incrementuse of the operator.
The first time though the loop, the value of i starts at 1. So, Serial.println(i) displays the value 1 in the Serial Monitor. The next time through the loop, i++ has made the value of i increase by 1. After a delay (so you can watch the individual values appear in the Serial Monitor), the for statement checks to make sure the condition i <= 10 is still true. Since i now stores 2, it is true since 2 is less than 10, so it allows the code block to repeat again. This keeps repeating, but when i gets to 11, it does not execute the code block because it’s not true according to the i <= 10 condition.
When you have successfully programmed your robot to count from 2 to 20 by 2's, turn on your call light and your instructor will check your work.
Your output should look like this:
Activity 7
A resistor is a component that resists the flow of electricity. This flow of electricity is called current. Each resistor has a value that tells how strongly it resists current flow. This resistance value is called the ohm, and the sign for the ohm is the Greek letter omega: Ω. (Later on you will see the symbol kΩ, meaning kilo-ohm, which is one thousand ohms.)
This resistor has two wires (called leads and pronounced “leeds”), one coming out of each end. The ceramic case between the two leads is the part that resists current flow. Most circuit diagrams use the jagged line symbol with a number label to indicate a resistor of a certain value, a 470 Ω resistor in this case. This is called a schematic symbol. The part drawing on the right is used in some beginner-level texts to help you identify the resistors in your kit, and where to place them when you build circuits.
The resistors in your parts kit have colored stripes that indicate what their resistance values are. There is a different color combination for each resistance value. For example, the color code for the 470 Ω resistor is yellow-violet-brown.
There may be a fourth stripe that indicates the resistor’s tolerance. Tolerance is measured in percent, and it tells how far off the part’s true resistance might be from the labeled resistance. The fourth stripe could be gold (5%), silver (10%) or no stripe (20%). For the activities in this book, a resistor’s tolerance does not matter, but its value does.
Each color bar on the resistor's case corresponds to a digit, as listed in the table below.
Here’s how to find the resistor’s value, in this case proving that yellow-violet-brown is really 470 Ω:
The first stripe is yellow, which means the leftmost digit is a 4.
The second stripe is violet, which means the next digit is a 7.
The third stripe is brown. Since brown is 1, it means add one zero to the right of the first two digits.
Yellow-Violet-Brown = 4-7-0 = 470 Ω.
Your Turn
When you can successfully read the resistor color code, turn on your call light and your instructor will check your skill level.
Activity 8
A diode is a one-way electric current valve, and a light-emitting diode (LED) emits light when current passes through it. Since an LED is a one-way current valve, you have to make sure to connect it the right way for it to work as intended.
An LED has two terminals: the anode and the cathode. The anode lead is labeled with the plus-sign (+) in the part drawing, and it is the wide part of the triangle in the schematic symbol. The cathode lead is the pin labeled with a minus-sign (-), and it is the line across the point of the triangle in the schematic symbol.
When you build an LED circuit, you will have to make sure the anode and cathode leads are connected to the circuit properly. You can tell them apart by the shape of the LED’s plastic case. Look closely at the case—it’s mostly round, but there is a small flat spot right near one of the leads, and that tells you it’s the cathode. Also note that the LED’s leads are different lengths. Usually, the shorter lead is connected to the cathode.
Always check the LED’s plastic case.
Usually, the longer lead is connected to the LED’s anode, and the shorter lead is connected to its cathode. But sometimes the leads have been clipped to the same length, or a manufacturer does not follow this convention. So, it’s best to always look for the flat spot on the case. If you plug an LED in backwards, it will not hurt it, but it won’t emit light until you plug it in the right way.
When you can successfully determine the (-) negative lead on the LED, turn on your call light and your instructor will check your comprehension.
Activity 9
The white board with lots of square sockets in it is called a solderless breadboard. This breadboard has 17 rows of sockets. In each row, there are two five-socket groups separated by a trench in the middle. All the sockets in a 5-socket group are connected together underneath with a conductive metal clip. So, two wires plugged into the same 5‑socket group make electrical contact. This is how you will connect components, such as an LED and resistor, to build circuits. Two wires in the same row on opposite sides of the center trench will not be connected.
The prototyping area also has black sockets along the top, bottom, and left.
Top: these sockets have three supply voltages for the breadboard: 3.3 V, Vin (input voltage from either battery pack or programming cable), and 5 V.
Bottom-left: The first six sockets along the bottom-left are ground terminals, labeled GND; think of them as a supply voltage that’s 0 V. Collectively, the 3.3V, Vin, 5V and GND are called the power terminals, and they will be used to supply your circuits with electricity.
Bottom-right: The ANALOG IN sockets along the bottom-right are for measuring variable voltages; these connect to the Arduino module’s ANALOG IN sockets.
Left: The DIGITAL sockets on the left have labels from 0 to 13. You will use these to connect your circuit to the Arduino module’s digital input/output pins.
When you can successfully connect two jumper cables to the same electrical connection, turn on your call light and your instructor will check your comprehension.
Activity 10
(2) LEDs – Red
(2) Resistors, 220 Ω (red-red-brown)
(3) Jumper wires
Always disconnect power to your board before building or modifying circuits!
1. Set the BOE Shield’s Power switch to 0.
2. Disconnect the programming cable and battery pack.
The image below shows the indicator LED circuit schematic on the left, and a wiring diagram example of the circuit built on your BOE Shield’s prototyping area on the right.
Build the circuit shown below. If you are new to building circuits, try to follow the wiring diagram exactly.
Make sure your LED cathode leads are connected to GND. Remember, the cathode leads are the shorter pins that are closer to the flat spot on the LED’s plastic case. Each cathode lead should be plugged into the same 5-socket row as the wires that run to the GND sockets.
Make sure that each longer anode lead is connected to the same 5-socket row as a resistor lead.
The next picture will give you an idea of what is going on when you program the Arduino to control the LED circuit. Imagine that you have a 5 volt (5 V) battery. The Board of Education Shield has a device called a voltage regulator that supplies 5 volts to the sockets labeled 5V. When you connect the anode end of the LED circuit to 5 V, it’s like connecting it to the positive terminal of a 5 V battery. When you connect the circuit to GND, it’s like connecting to the negative terminal of the 5 V battery.
On the left side of the picture, one LED lead is connectd to 5 V and the other to GND. So, 5 V of electrical pressure causes electrons to flow through the circuit (electric current), and that current causes the LED to emit light. The circuit on the right side has both ends of the LED circuit connected to GND. This makes the voltage the same (0 V) at both ends of the circuit. No electrical pressure = no current = no light.
You can connect the LED to a digital I/O pin and program the Arduino to alternate the pin’s output voltage between 5 V and GND. This will turn the LED light on/off, and that’s what we’ll do next.
Volts is abbreviated V.
When you apply voltage to a circuit, it’s like applying electrical pressure. By convention, 5 V means “5 V higher than ground.” Ground, often abbreviated GND, is considered 0 V.
Ground is abbreviated GND.
The term ground originated with electrical systems where this connection is actually a metal rod that has been driven into the ground. In portable electronic devices, ground is commonly used to refer to connections that go to the battery supply’s negative terminal.
Current refers to the rate at which electrons pass through a circuit.
You will often see measurements of current expressed in amps, which is abbreviated A. The currents you will use here are measured in thousandths of an amp, or milliamps. For example, 10.3 mA passes through the circuit shown above.
When you have successfully wired the circuit shown above, turn on your call light and your instructor will check your accuracy.
Activity 11
Example Sketch: HighLowLed
Reconnect the programming cable to your board.
Enter, save, and upload HighLowLed to your Arduino.
Verify that the pin 13 LED turns on and off, once every second. (You may see the LED flicker a few times before it settles down into a steady blinking pattern. This happens when reprogramming the Arduino.)
/* Robotics with the BOE Shield - HighLowLed Turn LED connected to digital pin 13 on/off once every second. */ void setup() // Built-in initialization block { pinMode(13, OUTPUT); // Set digital pin 13 -> output } void loop() // Main loop auto-repeats { digitalWrite(13, HIGH); // Pin 13 = 5 V, LED emits light delay(500); // ..for 0.5 seconds digitalWrite(13, LOW); // Pin 13 = 0 V, LED no light delay(500); // ..for 0.5 seconds }
When you have successfully programmed the LED at pin 13 to turn on/off, turn on your call light and your instructor will check your work.
Activity 12
Energize two LED's
Write the following program to get both lights to turn on.
/*
Robotics with the BOE Shield - HighLowLed
Turn LED connected to digital pin 13 on/off once every second.
*/
void setup() // Built-in initialization block
{
pinMode(13, OUTPUT); // Set digital pin 13 -> output
pinMode(12, OUTPUT); // Set digital pin 12 -> output
}
void loop() // Main loop auto-repeats
{
digitalWrite(13, HIGH); // Pin 13 = 5 V, LED emits light
digitalWrite(12, HIGH); // Pin 12 = 5 V, LED emits light
delay(500); // ..for 0.5 seconds
digitalWrite(13, LOW); // Pin 13 = 0 V, LED no light
digitalWrite(12, LOW); // Pin 12 = 0 V, LED no light
delay(500); // ..for 0.5 seconds
}
When you have successfully programmed both lights to turn on/off, turn on your call light and your instructor will check your work.
Activity 13
The high and low signals that control servo motors must last for very precise periods of time. That’s because a servo motor measures how long the signal stays high, and uses that as an instruction for how fast, and in which direction, to turn its motor.
This timing diagram shows a servo signal that would make your Shield-Bot’s wheel turn full speed counterclockwise. There’s one big difference though: all the signals in this timing diagram last 100 times longer than they would if they were controlling a servo. This slows it down enough so that we can see what’s going on.
Example Sketch: ServoSlowMoCcw
Enter, save, and upload ServoSlowMoCcw to the Arduino.
Verify that the pin 13 LED circuit pulses briefly every two seconds.
/* Robotics with the BOE Shield - ServoSlowMoCcw Send 1/100th speed servo signals for viewing with an LED. */ void setup() // Built in initialization block { pinMode(13, OUTPUT); // Set digital pin 13 -> output } void loop() // Main loop auto-repeats { digitalWrite(13, HIGH); // Pin 13 = 5 V, LED emits light delay(170); // ..for 0.17 seconds digitalWrite(13, LOW); // Pin 13 = 0 V, LED no light delay(1830); // ..for 1.83 seconds }
Your Turn – Two Steps to Servo Signal
Alright, how about 1/10th speed instead of 1/100th speed?
Reduce delay(170) to delay(17), and delay(1830) to delay(183), and re-upload the sketch.
Is the LED blinking 10 times faster now? Divide by 10 again for a full speed servo signal—we’ll have to round the numbers a bit:
Change delay(17) to delay(2), and delay(183) to delay(18), then upload the modified sketch.
Now you can see what the servo signal looks like with the indicator LED. The LED is flickering so fast, it’s just a glow. Since the high signal is 2 ms instead of 1.7 ms, it’ll be a little brighter than the actual servo control signal—the light is spending more time on. We could use this signal and programming technique to control a servo, but there’s an easier, more precise way. Let’s try it with LEDs first.
When you have successfully adjusted the timing to make it appear as thought the LED light is on continuously, turn on your call light and your instructor will check your work.
Activity 14
In this activity, you will run a sketch that sends the “stay-still” signal to the servos. You will then use a screwdriver to adjust the servos so that they actually stay still. This is called centering the servos. After the adjustment, you will run test sketches that will turn the servos clockwise and counterclockwise at various speeds.
Tool Required
You’ll need a Phillips #1 point screwdriver with a 1/8″ (3.18 mm) or smaller shaft.
If a servo has not yet been centered, it may turn, vibrate, or make a humming noise when it receives the “stay-still” signal.
Reconnect your programming cable, and re-run LeftServoStayStill.
Set the BOE Shield’s Power switch to 2, to provide power to the servos.
Use a screwdriver to gently adjust the potentiometer in the servo as shown in Figure 2‑26. Don’t push too hard! Adjust the potentiometer slightly until you find the setting that makes the servo stop turning, humming or vibrating.
Verify that the pin 13 LED signal monitor circuit is showing activity. It should glow like it did when you ran LeftServoStayStill the first time.
What’s a Potentiometer?
A potentiometer is kind of like an adjustable resistor with a moving part, such as a knob or a sliding bar, for setting the resistance. The Parallax continuous rotation servo’s potentiometer is a recessed knob that can be adjusted with a small Phillips screwdriver tip. Learn more about potentiometers in What’s a Microcontroller? and Basic Analog and Digital at www.parallax.com.
Your Turn – Center the Servo Connected to Pin 12
Repeat the process for the pin 12 servo using the sketch RightServoStayStill.
/* Robotics with the BOE Shield – RightServoStayStill Transmit the center or stay still signal on pin 12 for center adjustment. */ #include <Servo.h> // Include servo library Servo servoRight; // Declare right servo void setup() // Built-in initialization block { servoRight.attach(12); // Attach right signal to pin 12 servoRight.writeMicroseconds(1500); // 1.5 ms stay still signal } void loop() // Main loop auto-repeats { // Empty, nothing needs repeating }
When you have successfully centered BOTH of your servo motors and stopped them from drifting, turn on your call light and your instructor will check your work.
Activity 15
There’s one last thing to do before assembling your BOE Shield-Bot, and that’s testing the servos. In this activity, you will run sketches that make the servos turn at different speeds and directions. This is an example of subsystem testing—a good habit to develop.
Subsystem testing is the practice of testing the individual components before they go into the larger device. It’s a valuable strategy that can help you win robotics contests. It’s also an essential skill used by engineers to develop everything from toys, cars, and video games to space shuttles and Mars roving robots. Especially in more complex devices, it can become nearly impossible to figure out a problem if the individual components haven’t been tested beforehand. In aerospace projects, for example, disassembling a prototype to fix a problem can cost hundreds of thousands, or even millions, of dollars. In those kinds of projects, subsystem testing is rigorous and thorough.
Pulse Width Controls Speed and Direction
This timing diagram shows how a Parallax continuous rotation servo turns full speed clockwise when you send it 1.3 ms pulses. Full speed typically falls in the 50 to 60 RPM range.
What’s RPM? Revolutions Per Minute—the number of full rotations turned in one minute.
What’s a pulse train? Just as a railroad train is a series of cars, a pulse train is a series of pulses (brief high signals).
Example Sketch: LeftServoClockwise
Enter, save, and upload LeftServoClockwise.
Verify that the servo’s horn is rotating between 50 and 60 RPM clockwise.
/* Robotics with the BOE Shield – LeftServoClockwise Generate a servo full speed clockwise signal on digital pin 13. */ #include <Servo.h> // Include servo library Servo servoLeft; // Declare left servo void setup() // Built in initialization block { servoLeft.attach(13); // Attach left signal to pin 13 servoLeft.writeMicroseconds(1300); // 1.3 ms full speed clockwise } void loop() // Main loop auto-repeats { // Empty, nothing needs repeating }
Your Turn: Left Servo Counterclockwise
Save LeftServoClockwise as LeftServoCounterclockwise.
In servoLeft.writeMicroseconds, change (1300) to (1700).
Save the modified sketch and upload it to the Arduino.
Verify that the servo connected to pin 13 now rotates the other direction, which should be counterclockwise, at about 50 to 60 RPM.
Example Sketch: RightServoClockwise
Save LeftServoClockwise as RightServoClockwise.
Replace all instances of servoLeft with servoRight.
Replace all instance of 13 with 12.
Run the sketch and verify that the pin 12 servo is rotating between 50 and 60 RPM clockwise.
/* Robotics with the BOE Shield – RightServoClockwise Generate a servo full speed clockwise signal on digital pin 12. */ #include <Servo.h> // Include servo library Servo servoRight; // Declare left servo void setup() // Built in initialization block { servoRight.attach(12); // Attach left signal to pin 12 servoRight.writeMicroseconds(1300); // 1.3 ms full speed clockwise } void loop() // Main loop auto-repeats { // Empty, nothing needs repeating }
Your Turn – Right Servo Counterclockwise
In servoRight.writeMicroseconds change (1300) to (1700).
Save the sketch and upload it to your Arduino.
Verify that the pin 12 servo turns full-speed counterclockwise, about 50 to 60 RPM.
When you know what happens when the servoRight.writeMicroseconds changed to (1500), turn your call light on and show your instructor.