Project 16: Clap Switch - Thames & Kosmos Code Gamer Experiment Manual

Coding workshop ? game with kosmobits
Table of Contents

Advertisement

PROJECT 16
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
THE PROGRAM
The usual files are linked and the
defined for the sensor pin. The
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
variable, you will be storing the current state of
on
the NeoPixel. If it is on, the variable is assigned the value
, otherwise it is assigned the value
true
beginning of the program, the NeoPixel is off:
bool on = false;
.
In
setup()
, the pin mode of the sensor pin is set and the
NeoPixel is switched off.
In the main loop, the sound sensor is continuously read. If
the measured value is greater than the value set in
, the
toggle()
threshold
is a brief pause.
Here, you will write your own
This queries whether the NeoPixel is currently on. If so, the
NeoPixel is switched off and
.
false
Otherwise ("else"), the NeoPixel is switched on and
assigned the value
true
In brief:
toggle()
does exactly what its name suggests. It
switches back and forth between "on" and "off."
CodeGamer manual inside english.indd 47
constant is
sensorPin
constant
threshold
. At the
false
function is invoked and there
void toggle()
function.
is assigned the value
on
on
.
THE PLAN
If you clap once, it turns on the NeoPixel on the interaction
board. If you clap again, it turns off.
#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;
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;
is
} else {
pixel.setColor(255, 0, 0, 30);
on = true;
}
}
CodeGamer
</>
47
7/19/16 12:32 PM

Advertisement

Table of Contents
loading

Table of Contents