switchCase2

はじめに

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

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
  Switch statement with serial input

  Demonstrates the use of a switch statement. The switch statement allows you
  to choose from among a set of discrete values of a variable. It's like a
  series of if statements.

  To see this sketch in action, open the Serial monitor and send any character.
  The characters a, b, c, d, and e, will turn on LEDs. Any other character will
  turn the LEDs off.

  The circuit:
  - five LEDs attached to digital pins 2 through 6 through 220 ohm resistors

  created 1 Jul 2009
  by Tom Igoe

  This example code is in the public domain.

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

特に何もしていません。

setup()

23
24
25
26
27
28
29
30
31
void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  // initialize the LED pins:
  for (int thisPin = 2; thisPin < 7; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}
 

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

デジタルの2番ピンから6番ピンをpinMode()を使い出力モードに設定します。

loop()

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
void loop() {
  // read the sensor:
  if (Serial.available() > 0) {
    int inByte = Serial.read();
    // do something different depending on the character received.
    // The switch statement expects single number values for each case; in this
    // example, though, you're using single quotes to tell the controller to get
    // the ASCII value for the character. For example 'a' = 97, 'b' = 98,
    // and so forth:

    switch (inByte) {
      case 'a':
        digitalWrite(2, HIGH);
        break;
      case 'b':
        digitalWrite(3, HIGH);
        break;
      case 'c':
        digitalWrite(4, HIGH);
        break;
      case 'd':
        digitalWrite(5, HIGH);
        break;
      case 'e':
        digitalWrite(6, HIGH);
        break;
      default:
        // turn all the LEDs off:
        for (int thisPin = 2; thisPin < 7; thisPin++) {
          digitalWrite(thisPin, LOW);
        }
    }
  }
}

Serial.available()でシリアルポートが読み取り可能かどうかを調べます。読み取り可能であれば、Serial.read()で文字を読み取り、inByteに代入します。swtch文を使い、inByteの値に応じて出力するポートを変えます。文字が’a’、‘b’、‘c’、’d’、’e’のときに、それぞれ、2番から6番をHIGHにします。それ以外の場合は、defaultラベルが実行され、すべてのピンをLOWにします。

caseの後ろには、定数式を書くことができます。今回の例では文字定数を記述しています。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system