The Arduino Inventor's Guide (20 page)

BOOK: The Arduino Inventor's Guide
5.32Mb size Format: txt, pdf, ePub
Calculate and Display the Reaction Time

Next, the sketch computes the reaction time

by subtracting the
startTime
from the current timer value, which is fetched with the
millis()
command.

As a final step, the LEDs are turned off, and the
reactTime
value is printed to the serial communication line. To make the information more readable, the sketch prints the string
"Nice job! Your reaction time was "
to the Serial Monitor using the
print()
method

of the
Serial
object. This method sends the text between the quotation marks and doesn’t move the cursor to a new line. In fact, it keeps the cursor on the same line so that you can append more information, like the actual reaction time, which is added at

with
Serial.print(reactTime);
. The sentence is finished with a call to the
println()
method

, which prints the string
" milliseconds"
and then moves the cursor to a new line.

LOGICAL COMPARISON OPERATORS

Logical comparison operators
perform operations that test one value against another value. For example, the double equal sign (
==
) compares two values to see whether they are equal. A logical operation can return only one of two values:
true
, meaning the comparison evaluates correctly, or
false
, meaning it doesn’t evaluate correctly. In Arduino, there are many ways to compare two values, and all of the operators are listed in the following table:

OPERATOR

COMPARISON

==

Equal to

!=

Not equal to

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

For example, if you enter
2 == 4
in the Arduino IDE, it will return
false
, because two is not equal to four. However, if you enter
2 <= 4
in the Arduino IDE, it will return
true
, because two is less than or equal to four. In sketches, comparison operators are often used with
if()
or
while()
statements to run a certain block of code based on a certain condition. For example, the
while()
loop in
Listing 4-2
says, “while
digitalRead(3) == HIGH
is
true
, repeat the holding loop; otherwise, skip to the next bit of code.”

A common bug is to mistakenly use a single equal sign when working with comparisons. Remember: a single equal sign sets a variable, whereas the double equal sign compares the two values.

You’ll use comparison operators more and more as you start to evaluate data your Arduino gathers from various sensors and inputs, and we’ll use some of them later in this chapter, too.

Notice that every character must be explicitly printed, including any spaces you want between numbers or characters. You can use the
print()
and
println()
methods, as in this example, to combine, format, or organize text that you display in the Serial Monitor.

The final line of code in the
loop()
function is a short
delay()
function to pause the sketch before it loops back and starts the Reaction Timer again.

SPECIAL COMMAND CHARACTERS

When printing data or text, you must represent every individual character, including spaces, and every formatting command in your code. There’s a set of reserved characters, called
escape sequences
, to indicate special formatting. For example,
\n
moves the cursor to a new line; so,
Serial.print("Hello Arduino!\n");
is equivalent to
Serial.println("Hello Arduino!");
.

You can use escape sequences in your
print
statements to add formatting or other special characters to your text. The following table lists a handful of useful escape sequences.

ESCAPE SEQUENCE

RESULT

\t

Tab

\n

New line

\'

Single quotation mark

\"

Double quotation mark

\x
hh

ASCII character, where
hh
is a hexadecimal number

Test the Reaction Timer Sketch

That’s all the code you need to test your Reaction Timer game circuit! Save your sketch, compile it, and upload it to your Arduino now. To see the data that your sketch sends on the serial communication line, open the Serial Monitor window by clicking
Tools

Serial Monitor
or the magnifying glass button in the upper-right corner of the IDE.

Notice that the bottom-right corner of the Serial Monitor has a pull-down menu to control the serial data rate in
baud
(bits per second), which defaults to 9,600 baud (see
Figure 4-12
). This is the same value this sketch uses to initialize the
Serial
object, using the
Serial.begin(9600)
instruction. Always check that the Serial Monitor speed is the same as the rate set in the sketch with
Serial.begin()
—otherwise, you may just get gibberish!

FIGURE 4-12:
The Arduino IDE’s Serial Monitor window testing the Reaction Timer

NOTE

Some components, such as GPS or a serial-enabled LCD screen, will communicate with the Arduino at different baud rates, so when using a new part, it’s a good idea to check what rate it uses and set that in the sketch.

You can set the serial data rate to any standard rate from 300 to 250,000 baud, but 9,600 baud is the most common speed. Generally speaking, slower speeds are more reliable and use less power and fewer resources on the Arduino, but they also introduce a delay that slows down the
loop()
. If you need a really fast response and don’t care much about power usage, you can use a faster baud rate.

Now, let’s play! Run the sketch and watch your LED closely. When it lights up, push the button. Your code will print your reaction time, in milliseconds, to the Serial Monitor, like in
Figure 4-12
. How fast are you? Go challenge one of your friends! The average is about 215 ms. How do
you
measure up?

TRY IT OUT: MAKE WAITTIME MORE RANDOM

In most digital devices like an Arduino, it’s hard to get a
truly
random number because the random number is generated through a mathematical calculation. On an Arduino, each time the
random()
function is called, the function bases its calculation on the previous result from
random()
. Because the next “random” number is calculated from the previous result, the sequence of numbers will always be the same.

For example, on our Arduino (and probably yours), the first call to
random(2000, 4000)
will always set
waitTime
to
2807
. The second number generated will always be
3249
, the third will be
2073
, and so on.

You can make the
waitTime
value appear more random by calling the function
randomSeed()
in your
setup()
function. This generates a
seed
value that tells
random()
where the pseudorandom sequence should start. When your Arduino starts running a sketch, the seed defaults to
1
, which is why
2807
is always the first number generated by the
random(2000, 4000)
call.

To make your Reaction Timer behave more randomly, add this line of code to your
setup()
routine, just before the closing curly bracket:

randomSeed
(
analogRead
(A5));

This seeds the random-number generator with the current voltage value on the Arduino’s analog pin A5. We’ll cover
analogRead()
in more detail in Chapter 5, but for now, just know that it reads the voltage level on the analog pin passed to it. Because pin A5 isn’t connected to anything in the Reaction Timer, the voltage
floats
, or bounces around somewhat unpredictably.

If you choose to add this line of code, then each time you run your sketch, the first call to
random(2000, 4000)
should return a different number. To confirm, add these two lines of code after the
delay(waitTime)
call in your sketch:

Serial
.
print
(
"waitTime = "
);
Serial
.
println
(waitTime);

Now, comment out the
randomSeed()
call by adding
//
at the beginning of the line, run your sketch a few times, and note the initial
waitTime
values printed. Uncomment the
randomSeed()
call and repeat the process. Over time and a lot of data points, there will still be a pattern, but that’s a topic for another book—or perhaps for a degree in computer science!

Play Again?

To play again, simply press the Arduino’s reset button—the brass-colored button near the corner of the board, shown in
Figure 4-13
. This will restart your code and let you play again. Watch the LED closely. Are you any faster?

FIGURE 4-13:
Press the reset button to play again.

Add a Game Element

To add a little carnival-game style to this project, you can add a visual speed indicator to show if you’re faster than a given reaction time. We suggest starting with the average, 215 ms, as the time to beat. To do this, you’ll need to add two more LEDs: a green one to indicate that you were faster than the time set in the code and a red one to say you were slower. Since you already used pin 13 for the stimulus LED, you’ll connect these two LEDs to pins 11 and 12. Add these to your breadboard as shown in
Figures 4-14
and
4-15
.

FIGURE 4-14:
Circuit diagram with two extra LEDs

Other books

Ejecta by William C. Dietz
Peace in an Age of Metal and Men by Anthony Eichenlaub
H.E.R.O. - Horde by Rau, Kevin
Let Go by Michael Patrick Hicks