这是修改后的代码,初始值读取高得离谱,没有转换!!如何将转换应用于initialTemp以及temperatureC?
据我所知,你所帮助的代码正是我想要实现的目标,但很明显。
再次感谢!!
int pin_tempRead = 0; // temperature sensor pin
int coolLED = 2; // cooling LED digital pin
int heatLED = 3; // heating LED digital pin
float initialTemp;
float cutOffTemp = 30; //cut off temperature = 30°C
void setup()
{
Serial.begin(9600); //Start the serial connection with the computer
pinMode(heatLED, OUTPUT); //initialise as OUTPUT
pinMode(coolLED, OUTPUT); //initialise as OUTPUT
initialTemp = analogRead(pin_tempRead); // read the initial temp
Serial.print("Initial temperature: "); Serial.print(initialTemp); Serial.println("C"); //prints out starting temperature
}
void loop() // run over and over again
{
//getting the voltage reading from the temperature sensor
float current_temp = analogRead(pin_tempRead);
// converting that reading to voltage
float voltage = current_temp * 5.0; voltage /= 1024.0;
float temperatureC = (voltage - 0.5) * 100 ; //converting from 10 mv per degree with 500 mV offset
//to degrees ((voltage - 500mV) times 100)
if(temperatureC > cutOffTemp) {
// temp too high -> turn on the cooling system
digitalWrite(heatLED, LOW);
digitalWrite(coolLED, HIGH);
}else if (temperatureC < initialTemp) {
// temp too low -> turn on the heating system
digitalWrite(heatLED, HIGH);
digitalWrite(coolLED, LOW);
}
Serial.print("Current pump temperature: ");
Serial.print(temperatureC); Serial.println("C");
delay(1000);
}
答案 0 :(得分:1)
loop()
函数反复执行,因此它不是存储初始值的好地方。
您需要做的是定义一个全局变量,在setup()
函数中初始化它,然后您可以在loop()
函数中读取它
极简主义的例子:
int pin_tempRead = 0; // temperature sensor pin
float initial_temp; // define a global variable
void setup() {
initial_temp = analogRead(pin_tempRead); // read the initial temp
}
void loop() {
float current_temp = analogRead(pin_tempRead);
// get the temperature difference respect to the initial one
float difference = initial_temp - current_temp;
delay(1000);
}
PD:将区分定义硬件连接(引脚)的变量与软件连接区分开来也是一种很好的做法。我通常会将pin_
附加到定义连接的变量上。否则,如果tempRead
是温度值或传感器连接的引脚,则不清楚。
此外,对于加热器/冷却系统的开启和关闭:您已经处于循环中(loop()
功能是一个循环),因此您不需要一个while循环。
你的逻辑存在问题。
据我所知,你想要加热直到达到更高的阈值(cutOff),然后冷却直到达到下限阈值(initialTemperature)。
这称为滞后,但你的逻辑错了,这是纠正的错误:
只是做:
void loop() {
if(temperatureC > cutOffTemp) {
// temp too high -> turn on the cooling system
digitalWrite(heatLED, LOW);
digitalWrite(coolLED, HIGH);
}else if (temperatureC < initialTemp) {
// temp too low -> turn on the heating system
digitalWrite(heatLED, HIGH);
digitalWrite(coolLED, LOW);
}
Serial.print("Current pump temperature: ");
Serial.print(temperatureC); Serial.println("C");
delay(1000);
}
顺便说一句,您使用initialTemperature作为打开加热的低阈值。
这是你真正想要的吗?
如果初始温度高于cutOffTemp
怎么办?在这种情况下,您会遇到问题,因为较低的阈值高于较高的阈值。