|
读取模拟电压(Read Analog Voltage) 本示例展示了如何读取模拟输入0脚的模拟信号,将来自analogRead()的值转换为电压,并打印输出到 Arduino Software (IDE)的串口监视器。
所需硬件 - Arduino或者Genuino开发板 - 10k欧电位器
电路连接方式
使用三根导线将电位器连接到开发板。第一根导线从电位器外侧的一端连接到地。第二根导线从电位器外侧的另一端连接到5V。第三根导线从电位器的中间脚连接到模拟输入2脚。
通过转动电位器的旋转轴,你将改变电刷两侧的电阻值,该电刷与电位器中间的引脚相连。这样就可以改变中心引脚上的电压值。当中间引脚与连接5伏引脚之间的电阻接近于0时(同时另一侧引脚的电阻值接近于10k),中间引脚上的电压接近于5V。反之,中间引脚上的电压接近于0V。该电压就是你要读取的模拟电压作为输入信号。
Arduino开发板的微控制器内部有一个模拟数字转换器(analog-to-digital converter)的电路,可以读取这种变化的电压并将其转换成0到1023之间的数字。当电刷完全转向一侧时,引脚上的电压为0V,此时输入值为0。当电刷转向反方向时,引脚上的电压为5V,此时输入值为1023。当电刷在中间某个位置时,analogRead()将根据引脚分得的电压值成比例返回一个0到1023之间的数值。 原理图
代码 在下面的代码中,setup函数所做的唯一事情就是使用以下指令建立Arduino板和计算机的每秒9600数据位的串行通信: Serial.begin(9600);
接下来,在代码的主循环,你需要建立一个变量来存储电位器的电阻值(大小在0到1023间,int数据类型); int sensorValue = analogRead(A0);
若要想将该值从0-1023变成与引脚读取的电压相对应的范围内,则需要创建一个float型的变量,并且做一些数学运算。要将该值变到0.0到5.0之间,用5.0除以1023然后乘以sensorValue的值。 float voltage= sensorValue * (5.0 / 1023.0);
最后,你需要将这些信息打印输出到串口监视器,可以使用指令Serial.println()来实现。 Serial.println(sensorValue, DEC)
现在,当打开Arduino IDE上的串口监视器(通过点击窗口右上侧的类似放大镜的图标,或者按快捷键Ctrl+Shift+M),可以看到一串介于0.0 - 5.0之间的稳定数字流.当转动电位器时,这些数值也会立马跟着变化,与电位器的位置相对应。 - /*
- 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.
- */
- // the setup routine runs once when you press reset:
- 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);
- }
复制代码
|