p08_DigitalHourglass

はじめに

デジタル砂時計です。

デジタルピンの2番から7番にLEDが接続されています。ティルトスイッチが8番ピンに接続されています。

プログラム

定義等

 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
/*
  Arduino Starter Kit example
  Project 8 - Digital Hourglass

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

  Parts required:
  - 10 kilohm resistor
  - six 220 ohm resistors
  - six LEDs
  - tilt switch

  created 13 Sep 2012
  by Scott Fitzgerald

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

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

// named constant for the switch pin
const int switchPin = 8;

unsigned long previousTime = 0; // store the last time an LED was updated
int switchState = 0; // the current switch state
int prevSwitchState = 0; // the previous switch state
int led = 2; // a variable to refer to the LEDs

// 600000 = 10 minutes in milliseconds
long interval = 600000; // interval at which to light the next LED
 

変数を定義しています。

setup()

32
33
34
35
36
37
38
39
40
void setup() {
  // set the LED pins as outputs
  for (int x = 2; x < 8; x++) {
    pinMode(x, OUTPUT);
  }
  // set the tilt switch pin as input
  pinMode(switchPin, INPUT);
}
 

for文を使いxを2から7まで変化させます。for文の中では、pinMode()を使い、デジタルピンの2番から7番を出力モードにしています。switchPinは入力モードに設定しています。

loop()

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
void loop() {
  // store the time since the Arduino started running in a variable
  unsigned long currentTime = millis();

  // compare the current time to the previous time an LED turned on
  // if it is greater than your interval, run the if statement
  if (currentTime - previousTime > interval) {
    // save the current time as the last time you changed an LED
    previousTime = currentTime;
    // Turn the LED on
    digitalWrite(led, HIGH);
    // increment the led variable
    // in 10 minutes the next LED will light up
    led++;

    if (led == 7) {
      // the hour is up
    }
  }

  // read the switch value
  switchState = digitalRead(switchPin);

  // if the switch has changed
  if (switchState != prevSwitchState) {
    // turn all the LEDs low
    for (int x = 2; x < 8; x++) {
      digitalWrite(x, LOW);
    }

    // reset the LED variable to the first one
    led = 2;

    //reset the timer
    previousTime = currentTime;
  }
  // set the previous switch state to the current state
  prevSwitchState = switchState;
}

millis()を使って現在の時刻を取得します。現在時刻と前回時刻の差分をとり、設定した間隔(600000ミリ秒=10分)より大きければ、前回時刻(previousTime)に現在時刻(currentTime) を設定します。次にdigitalWrite()を使ってledに設定されている値のピンに接続されているLEDを点灯します。その後ledをインクリメントし、次に点灯するLEDを設定します。

ledが7になればそれ以上LEDはありませんが、この部分には何もプログラムが書かれていないため意図はよくわかりません。このままだとledの値が増え続けるのではと思います。

analogRead()を使ってswitchPinから値を読みます。今回読んだ値と前回読んだ値とが異なれば、砂時計がひっくり返されたということなので、LEDを消灯し、最初から開始します。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system