Knock

はじめに

Knock加速度センサから情報を取得し、シリアルポートに送信します。

アナログ0番から5番まで順に、自己診断、z軸、y軸、x軸、アース、Vccを接続します。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
  Knock Sensor

  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.

  The circuit:
	- positive connection of the piezo attached to analog in 0
	- negative connection of the piezo attached to ground
	- 1 megohm resistor attached from analog in 0 to ground

  created 25 Mar 2007
  by David Cuartielles <http://www.0j0.org>
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/Knock
*/


// 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
 

const int型の変数ledPinとknockSensor、thresholdを定義し初期化します。

int型の変数sensorReadingとledStateを定義し初期化します。

setup()

35
36
37
38
39
void setup() {
  pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
  Serial.begin(9600);       // use the serial port
}
 

pinMode()を使い、ledPinを出力モードにします。

Serial.begin()でシリアルポートを初期化します。

loop()

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
void loop() {
  // read the sensor and store it in the variable sensorReading:
  sensorReading = analogRead(knockSensor);

  // if the sensor reading is greater than the threshold:
  if (sensorReading >= threshold) {
    // toggle the status of the ledPin:
    ledState = !ledState;
    // update the LED pin itself:
    digitalWrite(ledPin, ledState);
    // send the string "Knock!" back to the computer, followed by newline
    Serial.println("Knock!");
  }
  delay(100);  // delay to avoid overloading the serial port buffer
}

analogRead()を使い読み取った値がthreshold以上のときは、ledStateを逆転させ(HIGHのときはLOWに、LOWのときはHIGHにし)、その値をdigitalWrite()を使いledPinに出力します。またSerial.println()を使ってシリアルポートに送信します。

最後にdelay()を使い、しばらく待ちます。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

November 1, 2022

inserted by FC2 system