| 1 |
/* |
| 2 |
Knock Sensor |
| 3 |
|
| 4 |
This sketch reads a piezo element to detect a knocking sound. |
| 5 |
It reads an analog pin and compares the result to a set threshold. |
| 6 |
If the result is greater than the threshold, it writes "knock" to the serial |
| 7 |
port, and toggles the LED on pin 13. |
| 8 |
|
| 9 |
The circuit: |
| 10 |
- positive connection of the piezo attached to analog in 0 |
| 11 |
- negative connection of the piezo attached to ground |
| 12 |
- 1 megohm resistor attached from analog in 0 to ground |
| 13 |
|
| 14 |
created 25 Mar 2007 |
| 15 |
by David Cuartielles <http://www.0j0.org> |
| 16 |
modified 30 Aug 2011 |
| 17 |
by Tom Igoe |
| 18 |
|
| 19 |
This example code is in the public domain. |
| 20 |
|
| 21 |
https://www.arduino.cc/en/Tutorial/BuiltInExamples/Knock |
| 22 |
*/ |
| 23 |
|
| 24 |
|
| 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 |
| 29 |
|
| 30 |
|
| 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 |
| 34 |
|
| 35 |
void setup() { |
| 36 |
pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT |
| 37 |
Serial.begin(9600); // use the serial port |
| 38 |
} |
| 39 |
|
| 40 |
void loop() { |
| 41 |
// read the sensor and store it in the variable sensorReading: |
| 42 |
sensorReading = analogRead(knockSensor); |
| 43 |
|
| 44 |
// if the sensor reading is greater than the threshold: |
| 45 |
if (sensorReading >= threshold) { |
| 46 |
// toggle the status of the ledPin: |
| 47 |
ledState = !ledState; |
| 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!"); |
| 52 |
} |
| 53 |
delay(100); // delay to avoid overloading the serial port buffer |
| 54 |
} |