风筝
发表于: 2016-5-29 15:27:14 | 显示全部楼层

读取模拟输入(AnalogReadSerial)

该示例展示了如何读取模拟输入信号,实例中采用了一只电位器。电位器(potentiometer)是一个简单的机械式器件,当转动旋转轴时,它可以提供不同的电阻值。通过将经由一个电位器的电压传递给Arduino板的模拟输入端,就有可能以模拟量的形式测量出该电位器分出的电阻值。在本示例中,当Arduino或Genuino与电脑建立好串行通信并且运行Arduino 软件(IDE)后,你就可以监测电位器的状态。


所需硬件

-    Arduino控制板

-    10k电位器


电路连接方式

将电位器的三根线连接到Arduino控制板上,首先将电位器外侧引脚的其中一个连接到地,然后将电位器外侧引脚的另外一个连接到5V,接着将电位器中间的引脚连接到模拟输入引脚A0上。

AnalogReadSerial_BB.png

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


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


原理图

AnalogReadSerial_sch.png


代码

在下面的代码中,setup函数所做的唯一事情就是使用以下指令建立Arduino板和计算机的每秒9600数据位的串行通信:

Serial.begin(9600);


接下来,在代码的主循环,你需要建立一个变量来存储电位器的电阻值(大小在0到1023间,int数据类型);

int sensorValue = analogRead(A0);


最后,你需要将这些信息打印输出到串口监视器,可以使用指令Serial.println()来实现。

Serial.println(sensorValue, DEC)


现在,当打开Arduino IDE上的串口监视器(通过点击窗口右上侧的类似放大镜的图标,或者按快捷键Ctrl+Shift+M),可以看到一串介于0~1023之间的稳定数字流,与电位器的位置相对应。当转动电位器时,这些数值也会立马跟着变化。

  1. /*
  2.   AnalogReadSerial
  3.   Reads an analog input on pin 0, prints the result to the serial monitor.
  4.   Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
  5.   Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  6.   This example code is in the public domain.
  7. */

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

  13. // the loop routine runs over and over again forever:
  14. void loop() {
  15.   // read the input on analog pin 0:
  16.   int sensorValue = analogRead(A0);
  17.   // print out the value you read:
  18.   Serial.println(sensorValue);
  19.   delay(1);        // delay in between reads for stability
  20. }
复制代码

原英文地址:Analog Read Serial

跳转到指定楼层
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题 700 | 回复: 1480



手机版|

GMT+8, 2024-4-18 20:37 , Processed in 0.138852 second(s), 6 queries , Gzip On, MemCache On. Powered by Discuz! X3.5

YiBoard一板网 © 2015-2022 地址:河北省石家庄市长安区高营大街 ( 冀ICP备18020117号 )

快速回复 返回顶部 返回列表