Thames & Kosmos Code Gamer Experiment Manual page 54

Coding workshop ? game with kosmobits
Table of Contents

Advertisement

PROJECT 17
MONITORING ( CLOSED )
The actual monitoring of the drawer happens in
mode, i.e. in
loopClosed()
brightness is measured. If it's dark, it waits one second
(1000 milliseconds).
loopClosed()
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
: In the next pass through the loop, then,
OPEN
is invoked.
loopOPEN()
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
This function is invoked from the main loop whenever
has the value
. We start by checking button 2: If it is
OPEN
pressed, the monitoring result is output by invoking the
output()
function.
If button 2 is not pressed, the brightness is checked in the
part. If it is now dark, the drawer was closed
else if
again.
is then raised by the value of 1 with
counter
.
++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.
OUTPUT
The
function is what takes care of the
output()
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
for 2 seconds. Otherwise, it glows green. Then the monitor
is returned to its starting state with
52
CodeGamer manual inside english.indd 52
CLOSED
. First, the current level of
is then invoked once
loopOpen()
.
mode
), the NeoPixel glows red
.
reset()
void loopClosed() {
Serial.println("In the dark");
sensorValue = analogRead(sensorPin);
if (sensorValue < DARK_VALUE) {
// still dark.
delay(1000);
// Wait 1 second, loop() invokes
// this function again.
} else {
// It is bright! Check again
// after 0.5 seconds.
delay(500);
if (analogRead(sensorPin) >= DARK_VALUE) {
// It is bright: drawer opened!
mode = OPEN;
}
}
}
void loopOpen() {
Serial.println("Opened");
delay(50);
button2 = digitalRead(button2Pin);
sensorValue = analogRead(sensorPin);
if (button2 == LOW) {
output();
} else if (sensorValue < DARK_VALUE) {
// Drawer closed again.
++counter;
mode = CLOSED;
}
}
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();
}
</>
// It is
7/19/16 12:33 PM

Advertisement

Table of Contents
loading

Table of Contents