这节课将向大家展示如何读取模拟引脚 0 上的模拟输入。输入从analogRead() 转换为电压,并打印到Arduino软件(IDE)的串行监视器中。
1、所需组件
- 1 ×面包板
- 1 × Arduino Uno R3
- 1 × 5K 可变电阻器(电位器)
- 2 ×跳线
2、电路程序
按照电路图将组件连接到面包板上,如下图所示。
3、电位器
电位器(也称为电位计)是一个简单的机电换能器。它将输入刷子的旋转或直线运动转换为阻力的变化。这种变化可以用于控制从高保真系统的音量到巨型集装箱船的方向的任何内容。
我们所知道的电位器最初被称为变阻器(本质上是可变绕线电阻器)。现在可用种类非常惊人,对于初学者来说,很难确定哪种类型适合给定的任务。
左图显示了电位器的标准示意图符号。右图是电位器。
4、新建编码草图
在计算机上打开Arduino IDE软件。用Arduino语言编码控制电路。通过单击“新建”(New) 打开新的草图文件。
5、Arduino代码
/* 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. */
// 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);
}
6、过程解释
(1)在给出的程序草图中,您在设置功能中做的第一件事是以每秒 9600 位的速度开始串行通信,实现代码是:
Serial.begin(9600);
(2)在代码的主循环中,您需要建立一个变量来存储来自电位计的电阻值(介于 0 和 1023 之间,非常适合 int 数据类型)
int sensorValue = analogRead(A0);
(3)要将值从 0-1023 更改为与电压相对应的范围,您需要创建另一个变量,一个浮点数,并进行一些计算。要在 0.0 和 5.0 之间缩放数字,请将 5.0 除以 1023.0,然后乘以 sensorValue:
float voltage= sensorValue * (5.0 / 1023.0);
(4)最后,您需要将此信息打印到串行窗口。您可以在最后一行代码中使用命令 Serial.println() 来执行此操作
Serial.println(voltage)
现在,通过单击顶部绿色栏右侧的图标或按 Ctrl+Shift+M,在 Arduino IDE 中打开 Serial Monitor。
7、执行结果
您将看到从 0.0 到 5.0 的稳定数字流。当您转动电位器时,对应于引脚 A0 处的电压值将发生变化。