analogRead()

Last revision:2025/05/10

名称

analogRead()

説明

指定したアナログピンから値を読み取る。

例えば、Arduino UNOボードは、10ビットのマルチチャネルアナログ-デジタル変換機を搭載している。これにより、0Vから動作電圧(+5VDC)の入力電圧を、0から1023の整数値に変換する。読み取り精度は、5/1024Vもしくは、0.0049V(4.9mV)となる。

入力電圧の範囲と精度はanalogReference()を使うことで変更できる。Arduinoボードの、analogRead()のデフォルト分解能は、互換性のため10ビットに設定されている。分解能を高めるには、analogReadResolution()を使う必要がある。

書式

アナログ入力のサンプル読取には、以下の関数を使う。

analogRead(pin)

C言語シグネチャ(avr)

int analogRead(uint8_t pin);

引数

この関数は以下の引数を受け付ける。

pin読み取りに利用するアナログ入力ピンの番号。

戻り値

この関数は、ピンから読み取ったアナログ値を返す。アナログ-デジタル変換器の精度によって制約がある。10ビットの場合は0-1024、12ビットの場合は0-4095など。データ型: int

コード例

analogPinから電圧を読み取って表示する。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
int analogPin = A3; // potentiometer wiper (middle terminal) connected to analog pin 3
                    // outside leads to ground and VCC
int val = 0;  // variable to store the value read

void setup() {
  Serial.begin(9600);           //  setup serial
}

void loop() {
  val = analogRead(analogPin);  // read the input pin
  Serial.println(val);          // debug value
  delay(200);
}

以下の方法を使い、読み取ったアナログ値を電圧に変換することもできる。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Constants
const float V_REF = 5.0;     // Analog reference voltage (e.g., 5V or 3.3V)
const float R_BITS = 10.0;   // ADC resolution (bits)
const float ADC_STEPS = (1 << int(R_BITS)) - 1; // Number of steps (2^R_BITS - 1)

const int potentiometerPin = A3; // Potentiometer wiper connected to analog pin A3

void setup() {
  Serial.begin(9600); // Initialize serial communication
  Serial.println(ADC_STEPS);
}

void loop() {
  int rawValue = analogRead(potentiometerPin); // Read the analog input
  float voltage = (rawValue / ADC_STEPS) * V_REF; // Convert to voltage

  Serial.print("Voltage: ");
  Serial.print(voltage, 3); // Print voltage with 3 decimal places
  Serial.println(" V");
  
  delay(200); // Small delay to avoid flooding the serial monitor
}

注意

アナログ入力ピンに何も接続されていないとき、analogRead()が返却する値は、種々の要因(他のアナログ入力の値、手とボードとの距離等)によって変動する。

訳者註

ピン番号の指定

アナログピンの番号は0から5までの数字以外に、A0からA5という変数を使うこともできます。A0は、(Arduino Unoの場合)14と定義されていますが、analogRead()の最初に、ピン番号が14以上のときは14を引くという処理が入っているので、特に問題なく動作します。

戻り値の扱い

オリジナルの説明が微妙ですが、Arduino Uno(ATmega328P)の場合、0Vから5Vが、0から1024(1023ではなく)にマッピングされます。結果は、0から1023です(10ビットなので)。

ATmega328Pのデータシートには、以下のように記載されています。

For single ended conversion, the result is

$$ ADC = \frac{V_{in}\cdot 1024}{V_{REF}} $$

where $V_{IN}$ is the voltage on the selected input pin and $V_{REF}$ the selected voltage reference.

参照

オリジナルのページ

https://docs.arduino.cc/language-reference/en/functions/analog-io/analogRead/

実装の解析

analogRead()

最終更新日

July 12, 2026

inserted by FC2 system