In the following example I used a piezo element (as the knock sensor) connected to analog pin 0 with the negative wire connected to ground. Then I placed a 1M resistor between the pin 0 and ground connection.
/* Knock Sensor
* ----------------
*
* 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.
*
* (cleft) 2005 D. Cuartielles for K3
* edited by Scott Fitzgerald 14 April 2013
*/
int ledPin = 13;
int knockSensor = 0;
byte val = 0;
int statePin = LOW;
int THRESHOLD = 8;
void setup() {
pinMode(ledPin, OUTPUT);
//Serial.begin(9600);
}
void loop() {
val = analogRead(knockSensor);
//Serial.println(val);
if (val >= THRESHOLD) {
statePin = !statePin;
digitalWrite(ledPin, HIGH);
delay(10);
digitalWrite(ledPin, LOW);
//Serial.println("Knock!");
}
//delay(100); // we have to make a delay to avoid overloading the serial port
}
I commented out the Serial communication statements because it made the sensor setup less responsive. Initially the threshold value was set to 100, however I found setting the value to 5 made it a lot more sensitive.
Output:
Here's a quick video of the knock sensor in action: