ReadAnalogVoltage

はじめに

アナログの0番ピンの電圧を読み取り、シリアルモニタに出力します。

可変抵抗器の中央のピンをアナログの0番ピンに接続し、両端のピンをそれぞれ、5VとGNDに接続します。

プログラム

setup()

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

  Reads an analog input on pin 0, converts it to voltage, and prints the result to the Serial Monitor.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.

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

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}
 

Serialは、Arduinoソフトウェアにより事前に定義されている変数(C++のオブジェクト)です。シリアルモニタと通信を行うときに利用します。Serial.begin()により、通信速度を設定(今は9600bps)します。

loop()

19
20
21
22
23
24
25
26
27
// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5.0 / 1023.0);
  // print out the value you read:
  Serial.println(voltage);
}

analogRead(A0)で、アナログピンの0番から値を読み取り、sensorValueに代入します。

読み取った値を実際の電圧に変換します。

analogRead()は、0から1023を返します。ATMega328Pのデータシートによると、0のときに0Vで、1024(1023ではなく)のときに参照電圧(今回は5V)を意味します。このため、本来は、$voltage = sensorValue \times ( 5.0 \div 1024.0)$とする必要があります。

Serial.println()を使って、計算した値をシリアルモニタに送信します。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system