2011-08-30 21:33:32 +02:00
|
|
|
/* Knock Sensor
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
This sketch reads a piezo element to detect a knocking sound.
|
|
|
|
It reads an analog pin and compares the result to a set threshold.
|
|
|
|
If the result is greater than the threshold, it writes
|
|
|
|
"knock" to the serial port, and toggles the LED on pin 13.
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
The circuit:
|
|
|
|
- + connection of the piezo attached to analog in 0
|
|
|
|
- - connection of the piezo attached to ground
|
|
|
|
- 1-megohm resistor attached from analog in 0 to ground
|
2011-08-30 21:33:32 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
http://www.arduino.cc/en/Tutorial/Knock
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
created 25 Mar 2007
|
|
|
|
by David Cuartielles <http://www.0j0.org>
|
|
|
|
modified 30 Aug 2011
|
|
|
|
by Tom Igoe
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
This example code is in the public domain.
|
2011-08-30 21:33:32 +02:00
|
|
|
|
2017-07-15 00:35:58 +02:00
|
|
|
*/
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2011-08-30 21:33:32 +02:00
|
|
|
|
|
|
|
// these constants won't change:
|
2017-07-12 19:58:31 +02:00
|
|
|
const int ledPin = 13; // LED connected to digital pin 13
|
2011-08-30 21:33:32 +02:00
|
|
|
const int knockSensor = A0; // the piezo is connected to analog pin 0
|
|
|
|
const int threshold = 100; // threshold value to decide when the detected sound is a knock or not
|
|
|
|
|
|
|
|
|
|
|
|
// these variables will change:
|
|
|
|
int sensorReading = 0; // variable to store the value read from the sensor pin
|
|
|
|
int ledState = LOW; // variable used to store the last LED status, to toggle the light
|
|
|
|
|
|
|
|
void setup() {
|
2013-10-21 09:58:40 +02:00
|
|
|
pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
|
|
|
|
Serial.begin(9600); // use the serial port
|
2011-08-30 21:33:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void loop() {
|
|
|
|
// read the sensor and store it in the variable sensorReading:
|
2013-10-21 09:58:40 +02:00
|
|
|
sensorReading = analogRead(knockSensor);
|
|
|
|
|
2011-08-30 21:33:32 +02:00
|
|
|
// if the sensor reading is greater than the threshold:
|
|
|
|
if (sensorReading >= threshold) {
|
|
|
|
// toggle the status of the ledPin:
|
2013-10-21 09:58:40 +02:00
|
|
|
ledState = !ledState;
|
|
|
|
// update the LED pin itself:
|
2011-08-30 21:33:32 +02:00
|
|
|
digitalWrite(ledPin, ledState);
|
|
|
|
// send the string "Knock!" back to the computer, followed by newline
|
2013-10-21 09:58:40 +02:00
|
|
|
Serial.println("Knock!");
|
2011-08-30 21:33:32 +02:00
|
|
|
}
|
|
|
|
delay(100); // delay to avoid overloading the serial port buffer
|
|
|
|
}
|