Piezo-Sensor registriert Klopf-Geräusche und schaltet eine LED ein/aus.
/* Knock Sensor with Piezo
*
* Program using a Piezo element as if it was a knock sensor.
*
* We have to basically listen to an analog pin and detect
* if the signal goes over a certain threshold. It writes
* "knock" to the serial port if the Threshold is crossed,
* and toggles the LED on pin 13.
* The threshold can be set to a custom value below.
*/
int ledPin = 13; // led connected to control pin 13
int knockSensorPin = 0; // the knock sensor will be plugged at analog pin 0
int val = 0; // variable to store the value read from the sensor pin
int statePin = LOW; // variable used to store the last LED status, to toggle the light
int THRESHOLD = 3; // threshold value to decide when the detected sound is a knock or not
void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
Serial.begin(9600); // initialize serial interface
}
void loop() {
val = analogRead(knockSensorPin); // read the sensor and store it in the variable "val"
Serial.println(val); // print value to Serial Monitor
if (val > THRESHOLD) {
statePin = !statePin; // toggle the status of the ledPin ("!": gets the opposite of variable content)
digitalWrite(ledPin, statePin); // turn the led on or off
Serial.println("Knock!"); // send the string "Knock!" back to the computer
}
delay(100);
// we have to make a delay to avoid overloading the serial port
}
