Arduino:读取模拟电压

所需硬件

  1. Arduino开发板
  2. 10K欧电位器

电路连接方式

Arduino:读取模拟电压_第1张图片
使用三根导线将电位器连接到开发板。第一根导线从电位器外侧的一端连接到地。第二根导线从电位器外侧的另一端连接到5V。第三根导线从电位器的中间脚连接到模拟输入2脚。

通过转动电位器的旋转轴,将改变电刷两侧的电阻值,该电刷与电位器中间的引脚相连。这样就可以改变中心引脚上的电压值。当中间引脚与连接5伏引脚之间的电阻接近于0时(同时另一侧引脚的电阻值接近于10k),中间引脚上的电压接近于5V。反之,中间引脚上的电压接近于0V。该电压就是要读取的模拟电压作为输入信号。

Arduino开发板的微控制器内部有一个模拟数字转换器(analog-to-digital converter)的电路,可以读取这种变化的电压并将其转换成0到1023之间的数字。当电刷完全转向一侧时,引脚上的电压为0V,此时输入值为0。当电刷转向反方向时,引脚上的电压为5V,此时输入值为1023。当电刷在中间某个位置时,analogRead()将根据引脚分得的电压值成比例返回一个0到1023之间的数值。

代码

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// 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);
}

你可能感兴趣的:(Arduino:读取模拟电压)