p02_SpaceshipInterface

はじめに

スイッチの状態によってLEDを制御します。

2番ピンにスイッチが、3番ピンに緑色のLEDが、4番ピンと5番ピンに赤色の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
/*
  Arduino Starter Kit example
  Project 2 - Spaceship Interface

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

  Parts required:
  - one green LED
  - two red LEDs
  - pushbutton
  - 10 kilohm resistor
  - three 220 ohm resistors

  created 13 Sep 2012
  by Scott Fitzgerald

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

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

// Create a global variable to hold the state of the switch. This variable is
// persistent throughout the program. Whenever you refer to switchState, you’re
// talking about the number it holds
int switchstate = 0;
 

int型の変数switchstateを定義し、0で初期化します。

setup()

27
28
29
30
31
32
33
34
35
36
void setup() {
  // declare the LED pins as outputs
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  // declare the switch pin as an input
  pinMode(2, INPUT);
}
 

pinMode()を使い、デジタルピンの3番と4番、5番を出力モードに、2番を入力モードに設定します。

loop()

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
void loop() {

  // read the value of the switch
  // digitalRead() checks to see if there is voltage on the pin or not
  switchstate = digitalRead(2);

  // if the button is not pressed turn on the green LED and off the red LEDs
  if (switchstate == LOW) {
    digitalWrite(3, HIGH); // turn the green LED on pin 3 on
    digitalWrite(4, LOW);  // turn the red LED on pin 4 off
    digitalWrite(5, LOW);  // turn the red LED on pin 5 off
  }
  // this else is part of the above if() statement.
  // if the switch is not LOW (the button is pressed) turn off the green LED and
  // blink alternatively the red LEDs
  else {
    digitalWrite(3, LOW);  // turn the green LED on pin 3 off
    digitalWrite(4, LOW);  // turn the red LED on pin 4 off
    digitalWrite(5, HIGH); // turn the red LED on pin 5 on
    // wait for a quarter second before changing the light
    delay(250);
    digitalWrite(4, HIGH); // turn the red LED on pin 4 on
    digitalWrite(5, LOW);  // turn the red LED on pin 5 off
    // wait for a quarter second before changing the light
    delay(250);
  }
}

digitalRead()を使って2番ピンの値を読み取り、switchstateに代入します。読み取った値はHIGHもしくはLOWです。

読み取った値がLOWの場合、digitalWrite()を使って、3番ピンにHIGHを、4番ピンと5番ピンをLOWにします。これにより、緑色のLEDが点灯し2つの赤色のLEDが消灯します。

読み取った値がLOWでない場合(=HIGHの場合)、まず、3番ピンと4番ピンをLOWに、5番ピンをHIGHにします。その後、delay()で250ミリ秒待ち、4番をHIGHに、5番をLOWにします。その後、また、250ミリ秒待ちます。緑色のLEDは消灯し、4番ピンに接続した赤色のLEDは消灯→点灯、5番ピンに接続した赤色のLEDは点灯→消灯します。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system