Week 2 - sgould/naps_code_club GitHub Wiki
This week we're going to explore communicating with the Arduino from your computer via the USB port. This is called a serial interface---and is the same interface used to load programs onto the Arduino in the first place. We have pre-loaded a mastermind guessing game on your Arduino.
-
Plug the Arduino into your computer. You should see a flashing sequence on the LEDs.
-
Open CodeBender in your Chrome browser (replace
*NAPS_PASS_WORD*
with the password provided for the NAPS Code Club):
https://edu.codebender.cc/class/*NAPS_PASS_WORD*
-
Open a serial interface by clicking on the Serial Monitor button:
-
Instructions should come up in the Serial Monitor window. You can now play a game of mastermind. The LED pattern will tell you the positions you got right. Press the reset button on the Arduino to re-start the game.
Now let's start writing code...
Hello World
We'll start with a small program that asks the user for to type their name and then prints a hello message. Remember the program is running on the Arduino and communicating with the computer via the USB port.
void setup() {
// initialize serial port and wait for it to open
Serial.begin(9600);
while (!Serial) {
// do nothing
}
}
void loop() {
// print message and wait for reply
Serial.println("What is your name?");
while (Serial.available() == 0) {
// do nothing
}
// get the reply
String name = Serial.readString();
Serial.println("Hello " + name);
}
Instead of having to type in all this code yourself you can download it (with a few extra bells and whistles) from this link: https://raw.githubusercontent.com/sgould/naps_code_club/master/lessons/week2/week2.ino
Then click the
button and choose Load to read in the file into CodeBender. Compile it and upload it to the Arduino.
Inputting Strings and Numbers
Variables are where your program stores data. Variables can have different types such as int
for numbers and String
to text (words and sentences). To read in a number or text variable from the Serial interface use
String text = Serial.readString();
or
int number = Serial.parseInt();
respectively.
Variables need to be declared with their type the first time they are used (or even before they are used). After that you don't need to add the type. For example,
String text;
text = Serial.readString();
Note that variables are not available everywhere. Programmers call this the variable's scope. This can sometimes be confusing because two variables can have the same name but different scope (and so hold different data). The following is an example what can go wrong because of scope.
void setup() {
String name = "Stephen";
}
void loop() {
Serial.println("Hello " + name);
}
This code results in an error because the variable name
is only defined in the setup()
function and not available in the loop()
function. One way to get around this is to give the variable global scope. For example:
String name;
void setup() {
name = "Stephen";
}
void loop() {
Serial.println("Hello " + name);
}
Now both functions have access to the (global) variable name
. Note, that global scope should only be used when a variable needs to be accessed in a bunch of different places. Otherwise declare the variable only where it will be used.
Generating Random Numbers
Sometimes you'll want to generate random numbers. For example, when programming the mastermind game. Computers can't generate true random numbers but generate what are called pseudo-random numbers. The following code snippet shows you how to generate a random number between 1 and 10.
// choose a random number
randomSeed(analogRead(0));
random_number = random(10) + 1;
Don't forget to make random_number
a global variable so that you can set it inside the setup()
function and use it inside the loop()
function.
Write Your Own Guessing Game
Now write your own guessing game competition. The idea is to generate a random number between 1 and 10 and have a user guess the number. After each guess you should tell the user whether their guess is correct, too low, or too high. You can light the yellow LED if it's correct, the green LED if it's too low, and the red LED if it's too high.
Start with the Hello World program and modify it as outlined in the instructions below. Work in groups and don't forget to share who gets to type.
In the setup()
function:
- Make sure the LED are pin modes are set to
OUTPUT
and the LEDs are turned off (writeLOW
) - Make sure the serial port is initialized like in your Hello World program
- Generate a random number between 1 and 10. Store it in a global variable called
secret_number
- Print out a message to the serial port asking the user to guess the number, e.g.,
Serial.println("Guess a number between 1 and 10.");
In the loop()
function:
- Wait for input from the serial port using the following code
// wait for serial input
while (Serial.available() == 0) {
// do nothing
}
- Read the user's guess into a variable called
guess
. The code below also shows how to get rid of any extra stuff sent over the serial port (such as text written after the guess or a code to say that the Enter key was pressed).
// get the guess
int guess = Serial.parseInt();
// clear buffer
while (Serial.available() > 0) {
Serial.read();
}
- Check if the guess was correct, too low, or too high and respond appropriately by sending a message back over the serial port and turning on the corresponding LED. The following code snippet shows you how to check the guess against the secret.
if (guess > secret_number) {
// write code here for when the guess is too high
} else if (guess < secret_number) {
// write code here for when the guess is too low
} else {
// write code here for when the guess is correct
}
After writing to the serial port (using println
) you may want to make sure that the message is displayed on the serial monitor before continuing with your code. This is done using the Serial.flush()
command, so your code may look something like:
Serial.println(String(guess) + " is too low. Guess again.");
Serial.flush();
- Compile your code regularly to check for mistakes. Once you think you have it working upload it to your Arduino and try playing the game. A new random number should be generated each time you play.