AnalogInput

はじめに

アナログピンから読み取った値をもとに、LEDを点滅させる間隔を変更します。

アナログの0番ピンが入力(可変抵抗で入力電圧を変更する)、デジタルの13番ピンにLEDが接続されている想定です(内蔵のLEDを使います)。

プログラム

定義等

 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
/*
  Analog Input

  Demonstrates analog input by reading an analog sensor on analog pin 0 and
  turning on and off a light emitting diode(LED) connected to digital pin 13.
  The amount of time the LED will be on and off depends on the value obtained
  by analogRead().

  The circuit:
  - potentiometer
    center pin of the potentiometer to the analog input 0
    one side pin (either one) to ground
    the other side pin to +5V
  - LED
    anode (long leg) attached to digital output 13 through 220 ohm resistor
    cathode (short leg) attached to ground

  - Note: because most Arduinos have a built-in LED attached to pin 13 on the
    board, the LED is optional.

  created by David Cuartielles
  modified 30 Aug 2011
  By Tom Igoe

  This example code is in the public domain.

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

int sensorPin = A0;    // select the input pin for the potentiometer
int ledPin = 13;      // select the pin for the LED
int sensorValue = 0;  // variable to store the value coming from the sensor
 

int型の変数sensorPinと ledPin、sensorValueを定義し、それぞれA0と13、0で初期化します。sensorPinは、アナログ入力を行うアナログピンの番号、ledPinは、LEDを接続するピン番号、sensorValueは、アナログピンから読み取った値を代入するための変数です。

sensorPinとledPinは、const int型のほうがいいのではと思います。

setup()

34
35
36
37
38
void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin, OUTPUT);
}
 

pinMode()を使って、ledPin(内蔵LEDが接続されている13番ピン)を出力モードに設定します。

loop()

39
40
41
42
43
44
45
46
47
48
49
50
void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  // turn the ledPin on
  digitalWrite(ledPin, HIGH);
  // stop the program for <sensorValue> milliseconds:
  delay(sensorValue);
  // turn the ledPin off:
  digitalWrite(ledPin, LOW);
  // stop the program for for <sensorValue> milliseconds:
  delay(sensorValue);
}

analogRead()を使い、sensorPin(値はA0) から値を読み込み、sensorValueに代入します。読み取った値は0から1023のどれかです。

次に、digitalWrite()を使って、ledPinにHIGHを出力し、LEDを点灯させます。その後、再びdigitalWrite()を使い、今度はledPinにLOWを出力し、LEDを消灯します。

digitalWrite()した後、delay()を使い、sensorValueミリ秒プログラムを止めています。これにより、アナログ入力の値によってLEDの点滅間隔を調整しています。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system