检查字符串是否为1或0,否则打印字符串。

4

我有一块连接到我的电脑(COM9)的Arduino,以及3个Python脚本。第一个脚本通过串口发送“1”;第二个脚本通过串口发送“0”;第三个脚本则可以发送你指定的单词。

ser.write("1")

然后在我的arduino上有一些代码。 如果运行Python脚本1,则会点亮LED。如果运行2秒的脚本,则会关闭LED。如果运行Python脚本3,则会将单词打印到LCD。 所有硬件都正确配置。 问题在于,当我运行脚本1时,不仅会点亮LED,LCD上还会有一个1。其他两个脚本按预期工作。 这是我的Arduino代码的一部分。
 if (Serial.available())
  {
     wordoftheday = Serial.readString();
     if (wordoftheday == "1"){email = true;}
     if (wordoftheday == "0"){email = false;}
     else { 
      lcd.clear();
      lcd.print(wordoftheday);
      }
  }

  if (email == true){digitalWrite(9, HIGH);}
  if (email == false){digitalWrite(9, LOW);}

2
你想要 else if (wordoftheday == "0") 吗? - chux - Reinstate Monica
@TristanT 当第三种文本消息类型被接收时,你想让LED做什么还不清楚。 - Weather Vane
当第三个文本消息类型被接收时,@Weather不需要执行任何操作。如果LED灯是开着的,它需要保持开着。如果LED灯是关着的,它需要保持关闭。 - Tristan
2个回答

5

使用==不能比较字符串

if (wordoftheday == "1"){email = true;}

应该是

if (strcmp(wordoftheday, "1") == 0){email = true;}

正如@chux指出的那样,似乎你忘记了一个 else

 if (strcmp(wordoftheday, "1") == 0)
     email = true;
 else
 if (strcmp(wordoftheday, "0") == 0)
     email = false;
 else { 
     lcd.clear();
     lcd.print(wordoftheday);
 }

还有另一个逻辑漏洞:正如@chux所提到的,缺少了一个else - Weather Vane
这非常有帮助。但它确实引发了一个错误。无法将“String”转换为“const char *”,以便为参数“1”调用“int strcmp(const char *,const char *)” 我知道它在说什么。但为什么会这样说呢? - Tristan
@TristanT 你是用Python还是C写的?既然你的程序运行正常,除了你的问题“为什么LCD上有一个值?”这个问题可以通过添加“else”解决。 - Weather Vane
好的,我没有看到python标签,wordoftheday被声明为字符串?那么请更改为if (!strcmp(wordoftheday.c_str(), "1")) - David Ranieri
如果它工作了 if (strcmp(wordoftheday.c_str(), "1") == 0) - Tristan

2
除了先前有关比较的答案外,您设置if语句时存在错误。当第一个if为true时,会进入第二个if的else分支。
if (Serial.available())
{
    wordoftheday = Serial.readString();
    if (strcmp(wordoftheday, "1")) {email = true;}
    else if ((strcmp(wordoftheday, "0")){email = false;}
    else { 
        // Enters here only if both of the above are false
        lcd.clear();
        lcd.print(wordoftheday);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接