void loopClosed() {
Serial.println("In the dark");
sensorValue = analogRead(sensorPin);
if (sensorValue < DARK_VALUE) { // It is
// still dark.
delay(1000); // Wait 1 second, loop() invokes
// this function again.
} else {
// It is bright! Check again
// after 0.5 seconds.
delay(5 00);
if (analogRead(sensorPin) >= DARK_VALUE) {
// It is bright: drawer opened!
mode = OPEN;
}
}
}
void loopOpen() {
Serial.println("Opened");
delay(5 0);
button2 = digitalRead(button2Pin);
sensorValue = analogRead(sensorPin);
if (button2 == LOW) {
output();
} else if (sensorValue < DARK_VALUE) {
// Drawer closed again.
++counter;
mode = CLOSED;
}
}
MONITORING
(
CLOSED
)
The actual monitoring of the drawer happens in
CLOSED
mode, i.e. in
loopClosed()
. First, the current level of
brightness is measured. If it’s dark, it waits one second
(1000 milliseconds).
loopClosed()
is then invoked once
again from the main loop.
If it’s bright, another reading is performed in 0.5 seconds. If
it’s still bright, it counts as “drawer is open.” The mode is
set to
OPEN
: In the next pass through the loop, then,
lo o p O P E N()
is invoked.
INTRUDERS?
(
OPEN
)
If the drawer has been opened, the drawer monitor still has
to find out if it’s due to an intruder. Maybe, after all, you
opened it yourself. That task is handled by
loopOpen()
.
This function is invoked from the main loop whenever
mode
has the value
OPEN
. We start by checking button 2: If it is
pressed, the monitoring result is output by invoking the
output()
function.
If button 2 is not pressed, the brightness is checked in the
else if
part. If it is now dark, the drawer was closed
again.
counter
is then raised by the value of 1 with
++counter
.
If button 2 is not pressed and the drawer has not been
closed again, the function is abandoned and invoked once
again by the main loop.
void output() {
Serial.print("The drawer was opened ");
Serial.print(counter);
Serial.print(" times!\n");
if (counter > 0) {
pixel.setColor(255, 0, 0, 25);
} else {
pixel.setColor(0, 255, 0, 25);
}
delay(2000);
reset();
}
OUTPUT
The
output()
function is what takes care of the
monitoring result output. First, the exact result is output
via the serial interface. For a quick check without having a
computer connected, though, the result is also output via
the NeoPixel. If the drawer has been opened and then
closed again (i.e.,
counter > 0
), the NeoPixel glows red
for 2 seconds. Otherwise, it glows green. Then the monitor
is returned to its starting state with
r e s e t()
.
PROJECT 17
CodeGamer manual inside english.indd 52 7/19/16 12:33 PM