Fade

はじめに

Arduinoの9番ピンに接続したLEDを、analogWrite()関数を使って、明るくしたり暗くしたりします。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/*
  Fade

  This example shows how to fade an LED on pin 9 using the analogWrite()
  function.

  The analogWrite() function uses PWM, so if you want to change the pin you're
  using, be sure to use another PWM capable pin. On most Arduino, the PWM pins
  are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.

  This example code is in the public domain.

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

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
 

int型の変数 ledとbrightness、 fadeAmount を定義し、それぞれ、9と0、5で初期化します。ブロックの外側で定義されているので、これらの変数はファイル有効範囲を持ちます。すなわち、このファイルで定義している全ての関数から参照することができます。さらに、記憶域クラス指定子の指定がないので外部結合となり、結果としてすべてのファイルから参照することができます。また、静的記憶域期間を持つため、プログラムの実行中はいつでも参照することができます。

setup()

20
21
22
23
24
25
// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}
 

pinMode(led, OUTPUT)で、デジタルピンの9番を入力モードに設定します。ledは、最初に9で初期化しています。

loop()

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

analogWrite(led, brightness)で、「デジタルピン」の9番に、デューティ比 brightness/255 のPWM波を出力します。その後、brightness に fadeAmount を加算します。これが、次のloop()実行時のbrightnessになります。

brightness が0(最小値)以下か255(最大値)以上になると、fadeAmountの符号を反転します。つまり、fadeAmountが5のときは-5になり、-5のときは5になります。これにより、loop()を繰り返して実行すると、analogWrite()を実行するときの brightness の値は、以下のように変化します。

0、5、10、…、245、250、255、250、245、…、10、5、0、5、10、…

その結果として、LEDが明るくなったり暗くなったりします。

最後にdelay(30)で、30ミリ秒待ちます。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system