![Thames & Kosmos Code Gamer Скачать руководство пользователя страница 49](http://html1.mh-extra.com/html/thames-and-kosmos/code-gamer/code-gamer_experiment-manual_1099224049.webp)
Clap switch
Wouldn’t it be cool if your KosmoDuino could respond to
clapping? You can easily program it to do that with the
help of your sound sensor.
YOU WILL NEED
› KosmoDuino in the interaction board
› Sound sensor
#include <KosmoBits_Pins.h>
#include <Adafruit_NeoPixel.h>
#include <KosmoBits_Pixel.h>
const int sensorPin = KOSMOBITS_SENSOR_PIN;
const int threshold = 500;
KosmoBits_Pixel pixel;
bool on = false;
In
setup()
, the pin mode of the sensor pin is set and the
NeoPixel is switched off.
void setup() {
pinMode(sensorPin, INPUT);
pixel.setColor(0, 0, 0, 0);
}
void loop() {
int sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
if (sensorValue > threshold) {
toggle();
delay(200);
}
}
void toggle() {
if (on) {
pixel.setColor(0, 0, 0, 0);
on = false;
} else {
pixel.setColor(255, 0, 0, 30);
on = true;
}
}
The usual files are linked and the
sensorPin
constant is
defined for the sensor pin. The
threshold
constant
controls the sensitivity of your clap switch. If the value set
there is exceeded by the measurement reading, the switch
toggles over — either from “on” to “off” or vice-versa. In
the
on
variable, you will be storing the current state of
the NeoPixel. If it is on, the variable is assigned the value
true
, otherwise it is assigned the value
false
. At the
beginning of the program, the NeoPixel is off:
bool on = false;
.
</>
THE PROGRAM
In the main loop, the sound sensor is continuously read. If
the measured value is greater than the value set in
threshold
, the
toggle()
function is invoked and there
is a brief pause.
Here, you will write your own
void toggle()
function.
This queries whether the NeoPixel is currently on. If so, the
NeoPixel is switched off and
on
is assigned the value
false
.
Otherwise (“else”), the NeoPixel is switched on and
on
is
assigned the value
true
.
In brief:
toggle()
does exactly what its name suggests. It
switches back and forth between “on” and “off.”
THE PLAN
If you clap once, it turns on the NeoPixel on the interaction
board. If you clap again, it turns off.
THE PROGRAM
Plug the sound sensor into the interaction board and then upload the following little program to your KosmoDuino:
47
PROJECT 16
CodeGamer
CodeGamer manual inside english.indd 47
7/19/16 12:32 PM