4. 模拟输入

4.3. 编写程序

第1步 模拟输入接口只有一种工作模式,所以无需使用pinMode()设置工作模式。我们可以直接使用analogRead()来读取传感器的原始量化值。这一数值是将传感器输出电压量化后的数值。analogRead()只有一个参数,就是接口编号。



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

void loop() {   Serial.println(analogRead(0)); }

在模拟过程中点击TMP36元件会出现温度滑块。拖动温度滑块,我们可以通过串口监视器看到数值有规律的变化。这样就证明这支传感器已经开始工作的。


第2步 先声明一个名为将reading的整型(int,用于保存整数)变量,保存analogRead()所返回的原始数值。然后声明一个milliVolts的浮点型(float,用于保存小数),保存换算后得出的传感器输出的电压(毫伏)。

因为单片机将0-5000mV的电压量化为了1024级来表示,所以换算系数为5000÷1024≈4.88,即每量化单位约为4.88mV。



int reading = analogRead(0);
float milliVolts = reading * 4.88;

第3步 使用换算公式将milliVolts换算为摄氏度,保存到浮点型变量temperatureC中。



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

void loop() {   int reading = analogRead(0);   float milliVolts = reading * 4.88;   float temperatureC = (milliVolts-500)/10;   Serial.println(temperatureC); }

第4步 通过串口将temperatureC输出并使用串口监视器查看。这里我们想让输出的信息更加丰富一些,做到下图的效果。


如果只输出固定字符串“Temperature:”,写成Serial.println("Temperature:")就可以了。如何将一段固定的字符串和一个浮点型变量结合起来呢?这就有赖于Arduino中提供的字符串处理功能了。首先我们使用String output = ""新建字符串变量output,两个引号表示初始值为空。然后使用String outputTemp = String(temperatureC)将temperatureC的变量值转换为字符串型存入outputTemp变量中。最后使用+将“Temperature:”和outputTemp两段字符串连接在一起并用串口输出就可以了。



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

void loop() {   int reading = analogRead(0);   float milliVolts = reading * 4.88;   float temperatureC = (milliVolts-500)/10;   String output = "";   String outputTemp = String(temperatureC);   output = "Temperature:" + outputTemp;   Serial.println(output); }

这里对temperatureC的转换是必须的,因为字符串的连接符+只能用于连接字符串类型的数据。熟悉了这些字符串操作后,我们可以简化一部分代码,将



String output = "";
String outputTemp = String(temperatureC);
output = "Temperature:" + outputTemp;
Serial.println(output);

化简为以下代码。



Serial.println("Temperature:" +String(temperatureC));