Thames & Kosmos Code Gamer Experiment Manual page 58

Coding workshop ? game with kosmobits
Table of Contents

Advertisement

PROJECT 19
THE PROGRAM
The program is extremely simple. First, the constants are
defined for the pins you are using. In
give a starting value to the random generator.
In the main loop, the brightness of each LED is first set to a
random value,
random(0, 256)
That will produce the flickering of the ghostly eyes.
To produce the hissing noise, you will use
in the
random(0, 1000)
random number — this time between 0 (smallest possible
value) and 999 (greatest possible value).
If the random number is greater than 900, write 3000
random values into the
analogWrite(buzzerPin, random(0, 256));
adjacent
loop. That will produce the hissing sound in
for
the speaker.
The random numbers to be produced with the help of the
function are evenly distributed. That means
random()
that every possible number will occur just as often as any
other over a long period of time. The hissing will only be
output, however, when the random number is greater than
900. That happens about one tenth of the time. If you want
the hissing to happen less often, just choose a number
larger than 900.
Now you can install these ghostly flickering eyes in a
jack-o'-lantern or a homemade ghost.
The ghostly eyes can be combined with lots of other
excellent ideas. How about a siren than howls when you
shine a flashlight on the jack-o'-lantern? You have already
learned how to do that. No doubt, you will also have a lot
of other great ideas of your own!
56
CodeGamer manual inside english.indd 56
setup()
, we will
, with
analogWrite()
statement to create another
if
with
buzzerPin
in the
#include <KosmoBits_Pins.h>
const int buzzerPin = KOSMOBITS_BUZZER_PIN;
const int redPin = 11;
const int greenPin = 6;
.
void setup() {
randomSeed(analogRead(3));
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
}
void loop() {
// Blinking
analogWrite(redPin, random(0, 256));
analogWrite(greenPin, random(0, 256));
delay(200);
// Hissing
if (random(0, 1000) > 900) {
for (int i = 0; i < 3000; ++i) {
analogWrite(buzzerPin, random(0, 256));
}
}
}
▲ Ghostly eyes
</>
7/19/16 12:33 PM

Advertisement

Table of Contents
loading

Table of Contents