p13_TouchSensorLamp

はじめに

静電容量センサを使ってLEDを制御します。http://arduino.cc/playground/Main/CapacitiveSensorが必要です。

プログラム

定義等

 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
35
36
37
38
39
/*
  Arduino Starter Kit example
  Project 13 - Touch Sensor Lamp

  This sketch is written to accompany Project 13 in the Arduino Starter Kit

  Parts required:
  - 1 megohm resistor
  - metal foil or copper mesh
  - 220 ohm resistor
  - LED

  Software required :
  - CapacitiveSensor library by Paul Badger
    https://www.arduino.cc/reference/en/libraries/capacitivesensor/

  created 18 Sep 2012
  by Scott Fitzgerald

  https://store.arduino.cc/genuino-starter-kit

  This example code is part of the public domain.
*/

// import the library (must be located in the Arduino/libraries directory)
#include <CapacitiveSensor.h>

// create an instance of the library
// pin 4 sends electrical energy
// pin 2 senses senses a change
CapacitiveSensor capSensor = CapacitiveSensor(4, 2);

// threshold for turning the lamp on
int threshold = 1000;

// pin the LED is connected to
const int ledPin = 12;
 
 

静電容量センサライブラリを使うためにCapacitiveSensor.hをインクルードし、CapacitiveSensorインスタンスを作成します。

その後、変数を定義しています。

setup()

40
41
42
43
44
45
46
void setup() {
  // open a serial connection
  Serial.begin(9600);
  // set the LED pin as an output
  pinMode(ledPin, OUTPUT);
}
 

Serial.begin()でシリアル通信の初期化を行います。通信速度は9600bpsです。

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

loop()

47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
void loop() {
  // store the value reported by the sensor in a variable
  long sensorValue = capSensor.capacitiveSensor(30);

  // print out the sensor value
  Serial.println(sensorValue);

  // if the value is greater than the threshold
  if (sensorValue > threshold) {
    // turn the LED on
    digitalWrite(ledPin, HIGH);
  }
  // if it's lower than the threshold
  else {
    // turn the LED off
    digitalWrite(ledPin, LOW);
  }

  delay(10);
}

sensorValueに静電容量センサの値を代入します。

digitalRead()を使ってSwitchPinの値をswitchValに代入します。

Serial.print()でシリアルコンソールに文字列を表示します。

sensorVariableがthresholdより大きいときは、digitalWrite()でledPinをHIGHにし、LEDを点灯します。そうでないときは、ledPinをLOWにし、LEDを消灯します。

delay()で10ミリ秒待ちます。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system