If 语句在 ESP32 上没有按预期工作

If statements not working as expected on ESP32

我的实验遇到了一些令人费解的情况。我只是使用电容传感器测量土壤湿度并通过 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 语句时,它只执行第一条语句和 returns..

  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.

关系运算符是具有从左到右结合性的二元运算符。结果为 0 或 1。

表达式500 < rawHumiditySensorValue <= 750等价于(500 < rawHumiditySensorValue) <= 750。由于 (500 < rawHumiditySensorValue) 的结果将为 0 或 1,并且这两个值都小于或等于 750,因此整个表达式的结果为 1。

您可能想要的是 500 < rawHumiditySensorValue && rawHumiditySensorValue <= 750


您可以使用 else if:

简化代码中关系运算符的使用
  // Invalid reading / no reading cases:
  if( rawHumiditySensorValue < 500 || rawHumiditySensorValue > 1000 )
  {
    soilStatus = SOIL_MOISTURE_DATA_NOT_FOUND;
  }
  else if( rawHumiditySensorValue <= 750 )
  {
    soilStatus = SOIL_TOO_WET;
  }
  else if( rawHumiditySensorValue <= 820 )
  {
    soilStatus = SOIL_MID_LEVEL_MOISTURE;
  }
  else if( rawHumiditySensorValue <= 920 )
  {
    soilStatus = SOIL_TOO_DRY;
  }
  else
  {
    soilStatus = SOIL_FAR_TOO_DRY; /* Original code did not handle this case! */
  }