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