AnalogInOutSerial

はじめに

アナログピンから読み取った値をもとに、アナログ出力(PWM)のデューティ比を決定します。また、結果をシリアルコンソールに出力します。

アナログの0番ピンが入力(可変抵抗で入力電圧を変更する)、デジタルの9番ピンに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
27
28
29
/*
  Analog input, analog output, serial output

  Reads an analog input pin, maps the result to a range from 0 to 255 and uses
  the result to set the pulse width modulation (PWM) of an output pin.
  Also prints the results to the Serial Monitor.

  The circuit:
  - potentiometer connected to analog pin 0.
    Center pin of the potentiometer goes to the analog pin.
    side pins of the potentiometer go to +5V and ground
  - LED connected from digital pin 9 to ground through 220 ohm resistor

  created 29 Dec. 2008
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

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

// These constants won't change. They're used to give names to the pins used:
const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0;        // value read from the pot
int outputValue = 0;        // value output to the PWM (analog out)
 

const int型の変数 analogInPinとanalogOutPinを定義し、それぞれ、A0と9を代入します。constで修飾されているためこれらの変数はプログラム内で変更することはできません。A0は、アナログの0番ピンを示す変数です。Arduino Unoの場合、アナログピンは6本あるので、A0からA5まで利用可能です。9はデジタルの9番ピンです(アナログ出力はデジタルピンに対して行います)。

int型の変数 sensorValueとoutputValueを定義し、両方とも0で初期化します。sensorValueは、アナログの0番ピンから読み取った値、outputValueは、9番ピンに出力する際のデューティ比を代入するための変数です。

setup()

30
31
32
33
34
void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
}
 

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

loop()

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
void loop() {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);
  // map it to the range of the analog out:
  outputValue = map(sensorValue, 0, 1023, 0, 255);
  // change the analog out value:
  analogWrite(analogOutPin, outputValue);

  // print the results to the Serial Monitor:
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\t output = ");
  Serial.println(outputValue);

  // wait 2 milliseconds before the next loop for the analog-to-digital
  // converter to settle after the last reading:
  delay(2);
}

analogRead()を使い、analogInPin(値はA0) から値を読み込みます。読み取った値は0から1023のどれかです。

次に、map()を使って、この値をPWMのデューティ比に変換します。アナログ出力の値は、0から255までです。

その後、analogWrite()で、実際に9番ピンに電圧を出力します。

Serial.print()Serial.println()を使い、読み取った値と計算したデューティ比をシリアルコンソールに出力します。

最後に、次のloop()を実行する前にdelay()を使って2ミリ秒待ちます。オリジナルのプログラムのコメントによると、ADコンバータが安定するのを待つためのようです。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system