Dimmer

はじめに

PC(である必要はありませんが)からデータを送り、Arduinoボードに接続したLEDの明るさを調整します。

9番ピンにLEDが接続されている想定です。また、シリアル経由でPC等と接続している必要があります。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
  Dimmer

  Demonstrates sending data from the computer to the Arduino board, in this case
  to control the brightness of an LED. The data is sent in individual bytes,
  each of which ranges from 0 to 255. Arduino reads these bytes and uses them to
  set the brightness of the LED.

  The circuit:
  - LED attached from digital pin 9 to ground through 220 ohm resistor.
  - Serial connection to Processing, Max/MSP, or another serial application

  created 2006
  by David A. Mellis
  modified 30 Aug 2011
  by Tom Igoe and Scott Fitzgerald

  This example code is in the public domain.

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

const int ledPin = 9;      // the pin that the LED is attached to

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

setup()

25
26
27
28
29
30
31
void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
  // initialize the ledPin as an output:
  pinMode(ledPin, OUTPUT);
}
 

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

pinMode()で、ledPinを出力モードにします。

loop()

32
33
34
35
36
37
38
39
40
41
42
void loop() {
  byte brightness;

  // check if data has been sent from the computer:
  if (Serial.available()) {
    // read the most recent byte (which will be from 0 to 255):
    brightness = Serial.read();
    // set the brightness of the LED:
    analogWrite(ledPin, brightness);
  }
}

Serial.available()で、シリアル入力があるかを調べます。入力がある場合、Serial.read()を使い、シリアル入力を読み込み、brightnessに代入します。

受信した値(brightness)をanalogWrite()の第2引数に設定し、ledPinに出力する電圧を変化させます。

その他

この例題には、通信相手となるProcessingのプログラムも入っていますが、こちらはよくわからないので掲載していません。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system