Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
You will use an Arduino code editor (also called an IDE – Integrated Development Environment) to create and save your Arduino apps for your robot. You'll also use the code editor to upload apps to your robot, in order to actually run them.
Follow these instructions to set up an Arduino code editor on your computer. There are two options: you could use the Arduino Create web editor or the Arduino IDE desktop editor. Check with your teacher to see which editor you should set up.
Once your Arduino code editor is ready to use, go on to the next step in this tutorial.
Next you'll add a command in your app code to designate the LED pin as an output.
A variety of inputs and outputs can be connected to the I/O pins on your RedBot circuit board. Your app code needs to identify which I/O pins you are using and whether each of these pins will be used for an input or output. This is referred to as setting the pin modes.
Setting the pin modes for your inputs and outputs only needs to occur one time when your app first starts to run, so the code statements to do this should be added within the setup()
function.
So you'll need to set the pin mode for the built-in LED that you'll be using. Add this code statement within the setup()
function (between the curly braces):
The pinMode()
method requires two parameters inside its parentheses (in this order):
The I/O pin number, which can be the actual pin number (such as: 13
, etc.) or a variable that stores a pin number. In this case, the variable LED
is listed (which has a value equal to 13
).
The mode value, which can be INPUT
, INPUT_PULLUP
, or OUTPUT
. Your RedBot uses this value to change the electrical behavior of the pin, so the pin can either receive signals from an input or send signals to an output. In this case, the mode was set to OUTPUT
because your app will be sending "on" and "off" signals to the LED light.
At this point, your app code should look similar to this:
Notice that the pinMode()
statement shown in the app code above is indented (using the tab key). This is a useful practice when adding code statements within curly braces because it helps make the code easier to read and understand – especially if your app contains many code statements nested within each other.
The Arduino code editor does NOT check your code syntax as you type, so be sure to periodically verify your code to check for errors. You can verify your code even if you're not done creating your entire app.
Verify your app code by clicking the Verify icon (looks like a checkmark) at the top of the code editor panel. (The Arduino code editor will first save your code before verifying it.)
After the verification is done, a message will appear in a status bar at the bottom of the code editor panel:
If your code compiled without any errors, the status bar will display a success message. (In the web editor, the message will say "Success." In the desktop editor, the message will say "Done compiling.")
If your code contains an error, the status bar will display an error message with a description of the error, and the code editor will highlight the specific line number in your code where the error was detected (although the actual cause of the error usually occurs on a previous line). You'll want to fix the error and then try verifying your code again.
MULTIPLE ERRORS: Sometimes your app code might contain multiple errors. However, the Arduino code editor will stop verifying the code at the first error that is detected. Once you fix that error and verify the code again, you might see a new error message for another error that occurs later in the code.
In this second tutorial, you'll program a "Hello World" app for your robot by using its LED light, speaker, and push button.
ALTERNATIVE TUTORIALS: Instead of completing these tutorials, your teacher might instruct your team to complete the SparkFun Experiment Guide for RedBot. If so, you should complete all the experiments except Experiment 9 (Remote Control).
Afterwards, if your robot has an ultrasonic sensor, be sure to also complete these tutorials for that sensor: D-3 Test Ultrasonic Sensor and D-4 Avoid Collisions
The goals of this tutorial are to help you:
Understand how to use the Arduino programming language to code apps for your robot
Program a Hello World app that controls your robot's LED light, speaker, and push button
The RedBot robot runs apps written in a programming language called Arduino. The Arduino language is designed to make it easier to write programs for microcontrollers. Many electronic kits and robotics kits use Arduino for programming.
Arduino is actually a code library written in another computer language called C++ (similar to how jQuery is a code library written in JavaScript). If and when necessary, your Arduino program can also incorporate code written directly in C++.
An Arduino program (or app) is also referred to as a sketch because the Arduino language is designed to allow you to quickly create a program — just like a sketch is a quick drawing.
These tutorials will introduce you to some of the basics of programming with Arduino. For additional help, the Arduino Programming Language Reference is useful for learning more about the structure and syntax of Arduino code.
When learning a new programming language, the first step that many people take is to create what is called a "Hello World" program. Traditionally, this program simply displays the text "Hello World" on the screen and only requires a few lines of code. The purpose is to demonstrate that you can create a simple yet functional program in the new coding language. It's a first step before creating more complex programs.
However, your robot does not have a built-in screen. The good news is your RedBot circuit board does have a built-in green LED light (D13) that can be controlled by your robot's app. So you'll first program a simple app that makes the built-in LED blink on and off repeatedly, as a way of saying "Hello World."
After that you'll modify the app to use the robot's speaker to produce a "beep" sound when the LED light blinks. Then you'll modify the app to detect when the built-in button (D12) on the circuit board is pressed, in order to make the LED blink and the speaker beep. Once all that is done, you'll start programming apps to make your robot drive around.
Next you'll add commands in your app code to turn the LED on and off in a repeating pattern.
Your app can receive signals from inputs using the digitalRead()
or analogRead()
methods, depending on whether the values being received will be digital or analog.
Your app can send signals to outputs using the digitalWrite()
or analogWrite()
methods, depending on whether the values being sent will be digital or analog.
DIGITAL VS. ANALOG: Digital inputs and outputs use binary values (such as: HIGH vs. LOW, etc.). Analog inputs and outputs use a range of values (such as: 0-255, etc.)
The LED can be controlled as a digital output that is either "on" or "off".
You'll need to send an "on" signal to the LED pin, in order to turn on the LED light. Add this code statement within the loop()
function (between the curly braces):
The digitalWrite()
method requires two parameters inside its parentheses (in this order):
The I/O pin number, which can be the actual pin number (such as: 13
, etc.) or a variable that stores a pin number. In this case, the variable LED
is listed (which has a value equal to 13
).
The signal value, which can be HIGH
or LOW
. Your RedBot uses this value to send an electrical signal through the pin: HIGH
is a signal of 5 volts which represents "on," while LOW
is a signal of 0 volts which represents "off." In this case, the signal was set to HIGH
because you want to turn on the LED light.
You'll want to leave the LED turned on for a certain amount of time before you send the "off" signal.
Because the RedBot's app code runs very fast, there will be certain situations where you'll want to insert delays into the code, in order to allow time for certain events to occur.
Your app can use the delay()
method to insert a time delay. It acts like a timer that makes the app wait before performing the next line of code.
You'll need to add a delay after the LED has been turned on. Add this code statement (as a separate line of code) within the loop()
function (after the digitalWrite()
statement):
The delay()
method requires one parameter inside its parentheses:
The time value, which can be an integer number (whole number) or a variable that stores an integer. The value represents the number of milliseconds for the time delay (1000 ms = 1 second). In this case, the delay was set to 500
ms (0.5 second).
Next, you'll send an "off" signal to the LED pin. Add this code statement (as a separate line of code) within the loop()
function (after the delay()
statement):
You can see that the second parameter in this digitalWrite()
statement was set to LOW
, which represents "off" for a digital output.
When all the code within the loop()
function has been performed, the loop()
will automatically repeat itself. Since the first line of code in your loop()
turns on the LED, you'll want to add another delay to leave the LED turned off for a brief amount of time before the loop()
repeats itself (which will start by turning the LED back on again).
Add this code statement (as a separate line of code) within the loop()
function (after the second digitalWrite()
statement):
At this point, the code within your loop()
function should perform these actions (in order):
Turn On LED light
Wait 0.5 second
Turn Off LED light
Wait 0.5 second
Repeat
REPEATING LOOP: You don't need to add a command to make the loop()
function repeat – it automatically repeats itself after its last code statement has been performed.
This represents all the code needed for your first version of the "Hello World" app. In the next step, you'll upload the app to your robot to test it out.
Let's upload your "Hello World" app to your robot to see if it works.
Your RedBot kit should have a USB to Mini-USB cable that allows you to connect the robot to a computer, in order to update the robot's app (or to send serial data to the computer).
Carefully plug the small end of this cable into the Mini-USB port on your RedBot circuit board. Plug the other end of the cable into a USB port on your computer.
IMPORTANT: Stand the RedBot upright on its back end (so its wheels are in the air). This is a precaution to make sure your robot doesn't drive away while connected to your computer.
Your RedBot is powered by a battery pack containing 4 AA batteries. Be sure the battery pack cable is plugged into the barrel jack on your RedBot circuit board.
Slide the RedBot's Power switch to ON. The RedBot's green Power LED light should turn on.
STOP MOTORS: If your robot's wheels start spinning when powered on (because the robot is running an existing app), you can temporarily slide the Motor switch to STOP if desired.
NO POWER: If the robot's Power LED doesn't turn on, verify the battery pack cable is plugged in and the Power switch is set to ON. Next, try replacing the AA batteries in the battery pack.
In order to upload your app to your robot, the code editor must know which type of Arduino board your robot has and which USB port on your computer that the robot is connected to.
If you previously selected your Arduino board type (which should be "Arduino/Genuino Uno"), the code editor should remember this selection.
Click "Select Other Board & Port" in the drop down menu at the top of the code editor panel.
In the pop-up, verify that "Arduino/Genuino Uno" is selected, and then select the correct USB port that your robot is connected to. Finally, click the OK button.
On Mac, the correct port should include "usbserial" as part of its name.
On Windows, there should be one or more numbered COM ports listed. You may have to select one, try uploading your app — and then if the app won't upload, switch to another COM port instead until you identify the correct port.
Under the Tools menu, verify that "Arduino/Genuino" is selected in the Board sub-menu, and then select the correct USB port in the Port sub-menu:
On Mac, the correct port should include "usbserial" as part of its name.
On Windows, there should be one or more numbered COM ports listed. You may have to select one, try uploading your app — and then if the app won't upload, switch to another COM port instead until you identify the correct port.
Once you've selected the correct port, the code editor should remember this selection while you keep the code editor open. However, if you close the code editor, you'll have to select the correct port again the next time you open and use the code editor.
Click the Upload icon (looks like a right arrow) at the top of the code editor panel. The code editor will automatically save and verify the app before uploading it to your robot.
During the upload process, you may notice two other green LED lights (labeled TX and RX, located next to the Mini USB port) blinking rapidly as the app code is transferred to the robot.
Once the upload is complete, the new app will immediately start running on your robot.
UPLOAD ERROR: If the Arduino code editor indicates there was a problem uploading to the board, it most likely means that the correct port was not selected. Be sure the correct USB port is selected in the code editor.
Confirm that the built-in green D13 LED light blinks on and off in a repeating pattern (changing every 0.5 second).
Arduino devices, such as the RedBot, can only store and run one app at a time. If you want to change the app running on your robot, you have to upload a different app from your code editor to the robot.
Next, try modifying the code within the loop()
function to make the LED blink faster (Hint: use shorter delays).
Upload your modified app to your robot to see if your changes worked as you expected.
Then modify the code to make the LED blink slower. Then upload your modified app to your robot to see if it works.
As your last step of this tutorial, you'll modify the "Hello World" app so your robot's LED and speaker will "blink" and "beep" whenever the D12 button on the robot's circuit board is pressed.
You'll need to create a global variable to store the pin number of the RedBot's built-in button, which is connected to pin D12 (via internal circuitry)
Add this code statement before the setup()
function:
Your code should now have three separate code statements before the setup()
function to declare a global variable for the LED, a global variable for the speaker, and a global variable for the button.
The button is an example of an input because your app will use it to receive data (i.e., to detect when someone presses the button). So you'll need to set the pin mode for the button to be an input.
Add this code statement within the setup()
function:
INPUT_PULLUP
indicates the button pin will be used for input and will use a pull-up resistor (which is something that buttons and switches typically use, but other inputs do not).
Your code should now have three separate code statements within the setup()
function to set the pin mode for the LED, set the pin mode for the speaker, and set the pin mode for the button.
Your app can receive signals from inputs using the digitalRead()
or analogRead()
methods, depending on whether the values being received will be digital or analog.
DIGITAL VS. ANALOG: Digital inputs and outputs use binary values (such as: HIGH vs. LOW, etc.). Analog inputs and outputs use a range of values (such as: 0-255, etc.)
The button can be read as a digital input that is either "pressed" or "not pressed."
Your app will need to use an if
statement and the digitalRead()
method to check if the button is being pressed. Add this code within the loop()
function (before the first digitalWrite()
statement that turns on the LED):
The digitalRead()
method requires one parameter insides its parentheses:
The I/O pin number, which can be the actual pin number (such as: 12
, etc.) or a variable that stores a pin number. In this case, the variable named button
is listed (which has a value equal to 12
).
The digitalRead()
method will check the button and return a value of either HIGH
or LOW
:
HIGH
indicates the button is NOT currently pressed.
LOW
indicates the button is currently pressed.
An if
statement checks whether a specific condition (listed insides its parentheses) is true or false.
In this case, the condition being checked is whether the value returned from digitalRead(button)
is equal to LOW
:
If this condition is true, the app will perform whatever code statements are listed within the curly braces of the if
statement.
If this condition is false, the app will not perform the code statements within the curly braces of the if
statement.
Here's what we want to happen: if the button is pressed, the LED will blink and the speaker will beep at the same time.
To do that, you're going to move the existing code statements in the loop()
that make the LED blink and speaker beep, so those code statements are now listed within the curly braces of the if
statement.
Select the code statements to be moved, cut them (choose "Cut" from Edit menu – or press Control-X on keyboard), and then paste them in their new location (choose "Paste" from Edit menu – or press Control-V on keyboard).
You may want to use the tab key to indent the code statements that you moved (so it is more visually clear that they are contained within the curly braces of the if
statement).
Modify the second delay()
method, so the delay is 200
milliseconds. This will act as a 0.2 second pause between each check of the button (to allow sufficient time for a person to release the button, so the code doesn't read a single button press as if it were multiple presses).
Just for reference, here's what your loop()
function should now look like:
Upload the modified app to your robot, confirm that it works correctly.
The robot's LED and speaker should briefly blink and beep (in sync) only when you press the D12 button on the RedBot circuit board.
If your teacher requires you to submit a file containing your completed "Hello World" app code, follow these instruction to download a copy of your app.
In the next tutorial, you'll program apps to make your robot drive around and make turns.
Let's add a variable in your app code to represent the built-in LED light.
Your "Hello World" app will make the RedBot circuit board's built-in green LED light turn on and off in a blinking pattern. This will be accomplished by sending separate "on" and "off" signals to the LED's pin.
Each I/O pin on the RedBot circuit board is identified by a pin number (such as: A0, A1, A2, 3, 9, 10, etc.). In this case, the RedBot's built-in green LED light is connected to pin D13 (via internal circuitry).
When coding an Arduino app, you will typically create global variables to store the pin numbers for the inputs and outputs connected to your circuit board that you want to control. This will help make your code easier to understand because the variable names help identify each input or output.
You'll need to "declare" (create) a global variable to store the pin number of the built-in LED. Add this code statement to your app by inserting it (as a separate line of code) before the setup()
function:
HOW TO COPY CODE: When using this IoT code guidebook, you can copy a code block simply by clicking the copy icon displayed in the upper right of the code block.
This code statement does 3 things (in order):
It declares a data type for the variable's value. In this case, int
stands for integer (whole number). Arduino pin numbers are always treated as int
values (even if they contain letters).
It declares the variable's name. In this case, the variable will be called LED
. You get to decide what to name your variables. Choose names that will make sense to anyone reviewing your code.
It assigns a value to the variable. In this case, the variable's value will be equal to 13
, which is the pin number for the RedBot's built-in LED light.
Notice that this code statement ends with a semi-colon. Typically, each code statement in your app will end with a semi-colon. The semi-colon separates code statements, similar to how periods separate sentences in written English.
The exceptions to ending with a semi-colon are certain statements (such as functions, conditionals, loops, etc.) that use curly braces to enclose other code statements. However, within the curly braces, each code statement will end with a semi-colon.
Although you can actually list multiple code statements on the same line (because their semi-colons will separate them), each code statement is traditionally listed on its own separate line to make it easier to read the code.
The Arduino code editor does NOT autosave as you type, so be sure to periodically save your code.
At the top of the code editor panel, hover your mouse cursor over the button with 3 dots, and then select "Save" from the pop-up menu.
Under the File menu, select "Save" – alternatively, you can click the Save icon (looks like a downward arrow) at the top of the code editor window.
TURN ON AUTOSAVE: You can turn on autosave in the Arduino Create web editor (but not the desktop editor). Click the Preferences menu in the left navigation to display its menu options. Be sure "Enable Autosave" and "Save when verifying and uploading" are both checked.
You get to decide what to name each variable in your app's code. However, here are a few rules and recommendations to help you name your variables:
Each global variable must have a unique name.
A variable's name cannot be one of the keywords in the Arduino programming language.
Variable names must be one word (no spaces allowed).
Variable names can contain lowercase letters, uppercase letters, numbers, and certain special characters (such as underscores, etc.) – but the name cannot start with a number.
Make each variable's name concise yet descriptive, so it will be easy to read and understand.
Example of variable name that's concise yet descriptive: LED
Example of variable name that's too concise: L
Example of variable name that's too descriptive: greenD13LEDlight
If your variable name combines multiple words, you can make the name easier to read by either using an underscore between words – or using "camelCase" (lowercase letters, but new words start with an uppercase letter).
Examples of variable name using underscore: push_button
Examples of variable name using camelCase: pushButton
If you have multiple inputs or outputs of the same type (mechanical bumpers, IR line sensors, etc.), add an adjective (or number) to their variable names to help identify them in your app code.
Examples of variable names using adjectives: leftBumper
, rightBumper
Next, you'll modify the "Hello World" app so your robot makes a "beep" sound with its speaker whenever the D13 LED blinks.
You'll need to create a global variable to store the pin number of the speaker (buzzer) that should be connected to I/O pin 9 on the RedBot's circuit board.
Add this code statement before the setup()
function:
Your code should now have two separate code statements before the setup()
function to declare a global variable for the LED and a global variable for the speaker.
Like the LED light, the speaker is also an output because your app will send signals to the speaker to produce sound. So you'll need to set the pin mode for the speaker to be an output.
Add this code statement within the setup()
function:
Your code should now have two separate code statements within the setup()
function to set the pin mode for the LED and set the pin mode for the speaker.
The speaker can only play one tone (sound) at a time. The tone()
method is used to produce a sound of a specific frequency (pitch).
Add this code statement (as a separate line of code) within the loop()
function (after the first digitalWrite()
statement, which turns on the LED):
The tone()
method requires two parameters inside its parentheses (in this order):
The I/O pin number of the speaker, which can be the actual pin number (such as: 9
, etc.) or a variable that stores a pin number. In this case, the variable speaker
is listed (which has a value equal to 9
).
The frequency for the tone, which can be an integer value (whole number) or a variable that stores an integer. The frequency value can be between 20-20000 hertz. Lower numbers will have a lower pitch, while higher numbers will have a higher pitch. In this case, the frequency will be 2000
hertz.
VOLUME: There isn't a way to change the volume of a tone produced by the speaker. However, you will notice that certain frequencies will naturally seem louder to your ears.
When you use the tone()
method in your app code to produce a sound, the speaker will keep playing the sound until you use a separate method in the code to stop the sound.
Let's stop the speaker sound when the LED is turned off.
Add this code statement (as a separate line of code) within the loop()
function (after the second digitalWrite()
statement, which turns off the LED):
The tone()
method requires just one parameter inside its parentheses:
The I/O pin number, which can be the actual pin number (such as: 9
, etc.) or a variable that stores a pin number. In this case, the variable speaker
is listed (which has a value equal to 9
).
Modify the first delay()
method within the loop()
function, so the delay will be 200
milliseconds. This will allow the LED and speaker to blink and beep for only 0.2 seconds.
Modify the second delay()
method within the loop()
function, so the delay will be 1500
milliseconds. This will create a 1.5 second pause between each blink/beep.
If your robot is still connected to your computer and powered on, you should be able to upload the modified app by clicking the Upload icon (looks like a right arrow) at the top of the code editor panel. The code editor will automatically save and verify the app before uploading it to your robot.
Otherwise, if you disconnected your robot from your computer, be sure to:
Connect Robot to Computer
Turn on Robot Power
Select Correct Board and Port
Upload App to Robot
Once the modified app is uploaded to your robot, confirm that it works correctly. The robot's LED and speaker should briefly blink and beep (in sync) in a repeating pattern (with 1.5 second pause between each blink/beep).
An Arduino program (or app) is also referred to as a "sketch" because the Arduino language is designed to allow you to quickly create a program — just like a sketch is a quick drawing.
This guidebook will primarily use the term "app" but just keep in mind that program, app, and sketch all mean the same thing when coding in Arduino: a set of coded software instructions to control the operation of a computing device (which is your robot, in this case).
If you haven't already done so, open your Arduino code editor:
Arduino Create web editor: .
Arduino IDE desktop editor: Double-click the Arduino application icon on your desktop.
If you are using your Arduino code editor for the first time, it should display a new app template by default. The new app template will have some starter code automatically inserted.
CREATE NEW APP: If you do not see a new app template when you open your code editor, you can follow these instructions to .
If you're using the Arduino Create web editor, your new app template will probably look like this:
If you're using the Arduino IDE desktop editor, your new app template will probably look like this:
The starter code in the app template has two core functions that all Arduino programs must include:
Setup Function — which will run only one time when your program first starts. Code statements added within the setup()
function perform one-time startup actions such as: set the pin modes for the device's inputs and outputs, initialize certain settings, etc.
Loop Function — which starts to run after the setup()
function is completed, and then repeats itself in an endless loop (until the device is turned off). Code statements added within loop()
function perform the main tasks of your device's program.
During this tutorial, you will be adding certain code statements within the setup()
function and within the loop()
function. You'll also add certain code statements outside of these two functions.
Here are two rules to follow when coding an Arduino app:
Your app must have a setup()
function and a loop()
function — even if there are no code statements within these functions.
Your app cannot have more than one setup()
function — or more than one loop()
function.
It's recommended to add a comment at the very top of your code to list a title for your app and any other information that might be helpful to you or to anyone else reviewing the program code.
Comments can be embedded throughout a program to provide information or to help clarify portions of the code. Comments are just written in plain language (instead of using code). Any comments added to the program are ignored when the program is compiled and uploaded to your robot.
A single-line comment starts with two forward slashes, like this:
A block comment uses a forward slash and asterisk to mark its beginning and end, like this:
Add a block comment at the beginning of your app code before the setup()
function.
If you're using the Arduino Create web editor, your new app template already has an empty block comment at the beginning of the code, which you can use.
Inside the block comment, list your app's title, your team's information, your teacher's name, and your class period. (Your teacher might have specific information to list in this block comment.)
For example, your block comment might look like this:
A comment can be a or a .