我的实验在这里遇到了一些令人费解的情况。我只是使用电容传感器测量土壤湿度并通过 nodemcu 的模拟引脚读取。之后,我将土壤状况分类为潮湿、中等或干燥。我想为此使用简单的 if-else 语句。但是,由于某种原因,它们没有按预期工作。只有第一个 if 被执行,当它不应该满足条件时...
const int SOIL_MOISTURE_DATA_NOT_FOUND = 0;
const int SOIL_TOO_WET = 1;
const int SOIL_MID_LEVEL_MOISTURE = 2;
const int SOIL_TOO_DRY = 3;
当我使用 else if 语句时,它只执行第一个语句并返回..
int soilStatus = SOIL_MOISTURE_DATA_NOT_FOUND;
int rawHumiditySensorValue = analogRead(A0);
Serial.print("Moisture value : ");
Serial.println(rawHumiditySensorValue);
if( 500 < rawHumiditySensorValue <= 750 )
{
Serial.println("SOIL_TOO_WET");
soilStatus = SOIL_TOO_WET;
}
else if( 750 < rawHumiditySensorValue <= 820 )
{
soilStatus = SOIL_MID_LEVEL_MOISTURE;
Serial.println("SOIL_MID_LEVEL_MOISTURE");
}
else if( 820 < rawHumiditySensorValue <= 920 )
{
soilStatus = SOIL_TOO_DRY;
}
// Invalid reading / no reading cases:
else if( rawHumiditySensorValue < 500 || rawHumiditySensorValue > 1000 )
{
soilStatus = SOIL_MOISTURE_DATA_NOT_FOUND;
}
Serial.print("Soil Status :");
Serial.println(soilStatus);
串行监视器的输出:
我删除了 if else,无论变量值如何,所有 if 语句都将被执行
int soilStatus = SOIL_MOISTURE_DATA_NOT_FOUND;
int rawHumiditySensorValue = analogRead(A0); //readAnalogDataFromHydroSensor(pinID);
Serial.print("Moisture value : ");
Serial.println(rawHumiditySensorValue);
if( 500 < rawHumiditySensorValue <= 750 )
{
Serial.println("SOIL_TOO_WET");
soilStatus = SOIL_TOO_WET;
}
if( 750 < rawHumiditySensorValue <= 820 )
{
soilStatus = SOIL_MID_LEVEL_MOISTURE;
Serial.println("SOIL_MID_LEVEL_MOISTURE");
}
if( 820 < rawHumiditySensorValue <= 920 )
{
soilStatus = SOIL_TOO_DRY;
}
// Invalid reading / no reading cases:
if( rawHumiditySensorValue < 500 || rawHumiditySensorValue > 1000 )
{
soilStatus = SOIL_MOISTURE_DATA_NOT_FOUND;
}
Serial.print("Soil Status :");
Serial.println(soilStatus);
我在串行监视器上得到以下输出:
我在这里想念什么?我检查了所有本地变量的数据类型,都设置为 int。