void loopIdle() {
Serial.println("Idle");
bool pressed = false;
while(digitalRead(button1Pin) == LOW) {
// Button 1 was pressed.
// Wait for it to be released again.
pixel.setColor(0, 255, 0, 25);
pressed = true;
delay(5 0);
}
if (pressed) {
mode = COUNTDOWN;
}
}
void loopCountdown() {
const int COUNTDOWN_NUMBER = 5;
Serial.println("Countdown");
pixel.setColor(0, 0, 0, 0); // Pixel OFF
delay(5 00);
// The actual countdown: Like Blink.
for (int i = 0; i < COUNTDOWN_NUMBER; ++i) {
pixel.setColor(0, 255, 0, 25); // G r e e n
delay(5 00);
pixel.setColor(0, 0, 0, 0); // Pixel off
delay(5 00);
}
pixel.setColor(255, 0, 0, 25); // R e d
delay(1000);
pixel.setColor(0, 0, 0, 0); // Pixel off
mode = WAIT_UNTIL_DARK;
}
By now you probably have a pretty good understanding of
the code. The
pressed
variable remembers whether the
button was pressed. If button 1 is pressed, the
w hile ()
loop is run through: The NeoPixel glows green, and the
pressed
variable is set to the
true
value. When button 1
is released, the
w hile ()
loop is abandoned. Finally, the
if()
instruction tests whether the button was pressed. If
so, the mode is set to
COUNTDOWN
. Otherwise,
loopIdle()
is quit and the main loop is invoked again. It
in turn invokes
loopIdle()
again, since the mode hasn’t
changed.
IN IDLE
When in its idle state, the drawer monitor is waiting for
button 1 to be pushed before it starts monitoring. What’s
responsible for that is the
loopIdle()
function, which is
invoked by the main loop in
IDLE
mode.
COUNTDOWN
Here, too, you will be familiar with most of the code. First,
the
COUNTDOWN
_
NUMBER
determines how many seconds
the countdown should last: 5 seconds, in this case. The
NeoPixel is turned off and after 500 milliseconds the
actual countdown is started in the
fo r()
loop: 5 times “on
— wait — off.” Then, the NeoPixel is set to “red” for one
second (1000 milliseconds). Finally, the mode is set to
WAIT
_
UNTIL
_
DARK
and
loopCountdown()
is quit.
void loopUntilDark() {
Serial.println("Wait until dark");
while (analogRead(sensorPin) > DARK_VALUE) {
delay(10);
}
mode = CLOSED;
delay(1000);
}
WAIT_UNTIL_DARK
This is easy: It keeps running through the
while
loop as
long as it’s dark. Measurements are taken every 10
milliseconds. When the
w hile ()
loop is abandoned, the
mode is set to
CLOSED
and
loopUntilDark()
is quit.
PROJECT 17
CodeGamer
CodeGamer manual inside english.indd 51 7/19/16 12:33 PM