switchCase

はじめに

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

プログラム

定義等

 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
/*
  Switch statement

  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, put the board and sensor in a well-lit room,
  open the Serial Monitor, and move your hand gradually down over the sensor.

  The circuit:
  - photoresistor from analog in 0 to +5V
  - 10K resistor from analog in 0 to ground

  created 1 Jul 2009
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

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

// these constants won't change. They are the lowest and highest readings you
// get from your sensor:
const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 600;    // sensor maximum, discovered through experiment
 

const int型の変数sensorMinとsensorMaxを定義し、初期化します。

setup()

29
30
31
32
33
void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}
 

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

loop()

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
void loop() {
  // read the sensor:
  int sensorReading = analogRead(A0);
  // map the sensor range to a range of four options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // do something different depending on the range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability
}

analogRead()でA0の情報を読み取り、sensorReadingに代入します。map()を使い、sensorReadinの値を変換しrangeに代入します。0から3までの整数に変換される想定です。ただし、map()は範囲外の値にも変換するので注意が必要です。範囲を指定したければ、constrain()を使って値を制限することもできます。

switch文により、rangeの値に応じて、dark、dim、medium、brightをSerial.println()を使い、シリアルコンソールに表示します。

caseラベルは、switch文に与えた式の評価結果が同じときの開始地点を表すだけです。処理を終わらせるためには、break文が必要です。例えば、break文を書かずに、以下のようなプログラムとしたときには、

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  switch (range) {
  case 0:    // your hand is on the sensor
    Serial.println("dark");
  case 1:    // your hand is close to the sensor
    Serial.println("dim");
  case 2:    // your hand is a few inches from the sensor
    Serial.println("medium");
  case 3:    // your hand is nowhere near the sensor
    Serial.println("bright");
  } 

rangeが0のときには、dark、dim、medium、brightの4つの文字列がすべて表示されます。

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

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system