AnalogWriteMega

はじめに

デジタルピンの2番から13番に接続したLEDを明るくしたり、暗くしたりします。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/*
  Mega analogWrite() test

  This sketch fades LEDs up and down one at a time on digital pins 2 through 13.
  This sketch was written for the Arduino Mega, and will not work on other boards.

  The circuit:
  - LEDs attached from pins 2 through 13 to ground.

  created 8 Feb 2009
  by Tom Igoe

  This example code is in the public domain.

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

// These constants won't change. They're used to give names to the pins used:
const int lowestPin = 2;
const int highestPin = 13;
 

int型の変数lowestPinとhighestPinを定義し、それぞれ2と13初期化します。

setup()

23
24
25
26
27
28
29
void setup() {
  // set pins 2 through 13 as outputs:
  for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}
 

pinMode()を使って、2番ピン(lowestPin)から13番ピン(highestPin)を出力モードに設定します。

loop()

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
void loop() {
  // iterate over the pins:
  for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
    // fade the LED on thisPin from off to brightest:
    for (int brightness = 0; brightness < 255; brightness++) {
      analogWrite(thisPin, brightness);
      delay(2);
    }
    // fade the LED on thisPin from brightest to off:
    for (int brightness = 255; brightness >= 0; brightness--) {
      analogWrite(thisPin, brightness);
      delay(2);
    }
    // pause between LEDs:
    delay(100);
  }
}

32行目のforループで、2番ピンから13番ピンを1つずつ、順に選択します。

34行目のforループで、32行目で選択したピンに出力する値を0から254まで変化させます。これにより、ピンに接続したLEDは少しずつ明るくなります。ピンへの出力には、analogWrite()を使います。出力後delay()を使って、2ミリ秒待ちます。

39行目のforループは、34行目のforループと同じ構造ですが、ピンに出力する値を、255から0まで変化させていきます。これにより、ピンに接続したLEDは少しずつ暗くなります。

一つのピンのLEDを制御した後は、delay()用いて、100ミリ秒待った後、次のピンの制御に移ります。

バージョン

Hardware:Arduino Mega
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system