#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));
}
}
}
The program is extremely simple. First, the constants are
defined for the pins you are using. In
setup()
, we will
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)
, with
analogWrite()
.
That will produce the flickering of the ghostly eyes.
To produce the hissing noise, you will use
random(0, 1000)
in the
if
statement to create another
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
buzzerPin
with
analogWrite(buzzerPin, random(0, 256));
in the
adjacent
for
loop. That will produce the hissing sound in
the speaker.
The random numbers to be produced with the help of the
random()
function are evenly distributed. That means
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!
</>
THE PROGRAM
▲
Ghostly eyes
56
PROJECT 19
CodeGamer manual inside english.indd 56
7/19/16 12:33 PM