-
void loop() {
15
}
-
-
void output_result(const long result) {
-
digitalWrite(LED_BIT0, result & B001);
-
digitalWrite(LED_BIT1, result & B010);
20
digitalWrite(LED_BIT2, result & B100);
-
}
-
This is all the code we need to implement the first version of a binary die. As
usual, we define some constants for the output pins the LEDs are connected
to. In the
setup
function, we set all the pins into
OUTPUT
mode. For the die, we
need random numbers in the range from one to six. The
random
function
returns random numbers in a specified range using a pseudorandom number
generator. In line 10, we initialize the generator with some noise we read from
analog input pin A0. (See Generating Random Numbers, on page 48, to learn
why we have to do that.) You might wonder where the constant
A0
is from.
The Arduino IDE defines constants for all analog pins named
A0
,
A1
, and so
on. Then we actually generate a new random number between one and six
and output it using the
output_result
function. (The seven in the call to
random
is correct, because it expects the upper limit plus one.)
The function
output_result
takes a number and outputs its lower three bits by
switching on or off our three LEDs accordingly. Here we use the
&
operator
and binary literals. The
&
operator takes two numbers and combines them
bitwise. When two corresponding bits are 1, the result of the
&
operator is 1,
too. Otherwise, it is 0. The
B
prefix allows you to put binary numbers directly
into your source code. For example,
B11
is the same as
3
.
You might have noticed that the
loop
function was left empty, and you might
wonder how such a die works. It’s pretty simple: whenever you restart the
Arduino, it outputs a new number, and to roll the die again, you have to press
the reset button.
Compile the code, upload it to the Arduino, and play with your binary die.
You have mastered your first advanced electronics project! Enjoy it for a
moment!
Whenever you want to see a new result, you have to reset the Arduino. That’s
probably the most pragmatic user interface you can build, and for a first
prototype, this is okay. But it’s more elegant to control the dice with your
own button. That’s what we’ll do in the next section.
report erratum • discuss
First Version of a Binary Die • 47
www.it-ebooks.info