3 This sketch reads a piezo element to detect a knocking sound.
4 It reads an analog pin and compares the result to a set threshold.
5 If the result is greater than the threshold, it writes
6 "knock" to the serial port, and toggles the LED on pin 13.
9 * + connection of the piezo attached to analog in 0
10 * - connection of the piezo attached to ground
11 * 1-megohm resistor attached from analog in 0 to ground
13 http://www.arduino.cc/en/Tutorial/Knock
16 by David Cuartielles <http://www.0j0.org>
20 This example code is in the public domain.
25 // these constants won't change:
26 const int ledPin = 13; // led connected to digital pin 13
27 const int knockSensor = A0; // the piezo is connected to analog pin 0
28 const int threshold = 100; // threshold value to decide when the detected sound is a knock or not
31 // these variables will change:
32 int sensorReading = 0; // variable to store the value read from the sensor pin
33 int ledState = LOW; // variable used to store the last LED status, to toggle the light
36 pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
37 Serial.begin(9600); // use the serial port
41 // read the sensor and store it in the variable sensorReading:
42 sensorReading = analogRead(knockSensor);
44 // if the sensor reading is greater than the threshold:
45 if (sensorReading >= threshold) {
46 // toggle the status of the ledPin:
48 // update the LED pin itself:
49 digitalWrite(ledPin, ledState);
50 // send the string "Knock!" back to the computer, followed by newline
51 Serial.println("Knock!");
53 delay(100); // delay to avoid overloading the serial port buffer