Arduino示例代码讲解:Knock Sensor 敲击感知器
- Knock Sensor 敲击感知器
 - 功能概述
 - 硬件部分:
 - 软件部分:
 
- 代码逐行解释
 - 定义常量
 - 定义变量
 - `setup()` 函数
 - `loop()` 函数
 
- 工作原理
 
Knock Sensor 敲击感知器
这段代码是一个Arduino示例程序,用于检测敲击声。它通过读取一个压电元件(piezo element)的模拟输入值,并将其与一个设定的阈值进行比较。如果读取的值超过阈值,它会在串行端口输出“knock”,并切换引脚13上的LED的状态。这种方法适用于需要检测敲击或其他声音信号的场景。
/* Knock SensorThis 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.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 groundhttp://www.arduino.cc/en/Tutorial/Knockcreated 25 Mar 2007by David Cuartielles <http://www.0j0.org>modified 30 Aug 2011by Tom IgoeThis example code is in the public domain.*/// these constants won't change:
const int ledPin = 13;      // led connected to digital pin 13
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