IfStatementConditional

はじめに

if文の使い方を示します。

プログラム

定義等

 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
/*
  Conditionals - If statement

  This example demonstrates the use of if() statements.
  It reads the state of a potentiometer (an analog input) and turns on an LED
  only if the potentiometer goes above a certain threshold level. It prints the
  analog value regardless of the level.

  The circuit:
  - potentiometer
    Center pin of the potentiometer goes to analog pin 0.
    Side pins of the potentiometer go to +5V and ground.
  - LED connected from digital pin 13 to ground through 220 ohm resistor

  - Note: On most Arduino boards, there is already an LED on the board connected
    to pin 13, so you don't need any extra components for this example.

  created 17 Jan 2009
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

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

// These constants won't change:
const int analogPin = A0;    // pin that the sensor is attached to
const int ledPin = 13;       // pin that the LED is attached to
const int threshold = 400;   // an arbitrary threshold level that's in the range of the analog input
 

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

setup()

32
33
34
35
36
37
38
void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communications:
  Serial.begin(9600);
}
 

pinMode()でledPinを出力モードにします。

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

loop()

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
void loop() {
  // read the value of the potentiometer:
  int analogValue = analogRead(analogPin);

  // if the analog value is high enough, turn on the LED:
  if (analogValue > threshold) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }

  // print the analog value:
  Serial.println(analogValue);
  delay(1);        // delay in between reads for stability
}

analogRead()でanalogPinの情報を読み取り、analogValueに代入します。

if文を使って、analogValueの値を検査します。読み取った値がthreshold(=100)より大きい場合は、digitalWrite()によりledPinをHIGHにします(その結果LEDが点灯します)。そうでない場合(100以下の場合)は、elseに続く文が実行され、digitalWrite()によりledPinをLOWにします(その結果LEDが消灯します)。

最後に安定化のため、delay()を使って少し待ちます。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system