Piezo Buzzers as Knock Sensors

I didn't know where else to go with this information, so I thought I would make a post, in hopes that it would reach someone before they experience the headache I have experienced. The examples at www.arduino.cc/en/Tutorial/Knock? and http://www.arduino.cc/en/Tutorial/KnockSensor will cause you to THINK that something's not working correctly. But it's all in the code. These examples should be updated with a more proper working software approach to this problem. Following the rest of these tutorials is probably fine, but when you get to the software, take a look at the following bold line:

/* 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 = 100;



void setup() {

 pinMode(ledPin, OUTPUT); 

 Serial.begin(9600);

}



void loop() {

  val = analogRead(knockSensor);     

  if (val >= THRESHOLD) {

    statePin = !statePin;

    digitalWrite(ledPin, statePin);

    Serial.println("Knock!");



  }

  [b]delay(100);[/b]  // we have to make a delay to avoid overloading the serial port

}

Notice here, the fundamental flaw, is that the delay executes EVERY iteration of the main loop. This creates a problem, as you may be trying to detect a knock that happens during the delay (it's very likely, especially at 1/10 of a second). To fix this code to behave more "as expected", move the delay inside the if statement, right after the Serial.println( "Knock!" ); statement. This still provides the debounce protection intended (protection from detecting multiple knocks from one knock), while maintaining accurate initial knock detection. If you want, you can tune the delay amount based on whether you need the ability to detect faster intervals between knocks (smaller delay, the smaller the interval between the knocks can be). Just make sure you aren't getting "double knocks". Happy hacking!

Where would I go, or who would I go to, to get the code on the tutorial pages changed?

Why, its just an example showing the steps required to do that.

Oh, by the way there is no bold line. Type face/ font and colour changes can work inside a ode block!

Mark

The original code states that the delay is to stop the serial getting bogged down, not for debouncing.

Im Glad To Find your Post Though, Im Going to Do This Soon I Hope