繁体   English   中英

Arduino温度传感器

[英]Arduino temperature sensor

我正在尝试用arduino使用温度传感器构建一个小程序。

我以为我知道怎么做但我得到一些奇怪的输出。

这是我的代码:

int sensorPin = 0;
void setup()
{
    Serial.begin(9600);
}
void loop()
{
    int reading = analogRead(sensorPin);
    float voltage = reading * 5.0 / 1024;
    float temperatureC = (voltage - 0.5) * 100;
    Serial.print(temperatureC); Serial.print(" degrees C, ");
    Serial.print(voltage); Serial.println(" volts");
    delay(1000);
}

这段代码给了我输出:

-26.56 degrees C, 0.23 volts
-26.56 degrees C, 0.23 volts
-27.05 degrees C, 0.23 volts
-26.56 degrees C, 0.23 volts
-26.07 degrees C, 0.24 volts
-26.07 degrees C, 0.24 volts

为什么-以度为单位? 为什么我可以将它更改为我想要的任何引脚,它仍然会给我类似的输出?

模拟输入0不是引脚0。

您应该使用定义的符号:
A0,A1,...,A7
用于模拟输入。

尝试

int sensorPin = A0;  

你的程序应该工作。

如果您对实际值感到好奇,请在Arduino IDE安装下查看文件
.. \\五金\\ Arduino的\\变种\\标准\\ pins_arduino.h

您正在正确阅读此输入。 为了让你不能获得负面学位,你必须以不同的方式处理它。

有了这个:

float temperatureC = (voltage - 0.5) * 100;

任何值< 0.5导致负数乘以100。

尝试使用可交换属性将其分解。

  • (voltage - 0.5) * 100(voltage * 100) - (0.5 * 100)
  • 这可以进一步简化为(voltage * 100) - 50

但是,对于voltage < 0.5的所有值,温度将为负。

  • 我建议将temperatureC乘以-1以使其为正,而不是将传感器放在任何“〜> = 50摄氏度”附近。

另外,正如jdr5ca在这里指出的那样,你实际上并没有从传感器获得任何数据...... :(

你可能从任何pin0获得噪音(或垃圾)。

编辑

最佳做法是使用括号使操作顺序更加清晰。

  • 即:
    • float voltage = reading * 5.0 / 1024;
    • 应该
    • float voltage = reading * (5.0 / 1024);

首先,您必须使用定义的符号A0

int sensorPin = A0;

in the next

float voltage = reading * (5.0 / 1024);

File/Examples/Basic/AnalogReadSerial有一个例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM