我有一个 arduino 连接到我的电脑 (COM9),我有 3 个 python 脚本。第一个通过串行发送“1”。 第二个通过串行发送“0”。 第三个发送一个词,你给它。
ser.write("1")
然后在我的 arduino 上我有一些代码。 如果启动 python 脚本 1,它将打开 LED。如果启动 2 秒脚本,它将关闭 LED。如果启动 python 脚本 3,它将把单词打印到液晶显示器上。
所有硬件配置正确。 问题是,当我运行脚本 1 时,不仅 LED 会亮起,液晶显示器上也会有一个 1。其他 2 个脚本按预期工作。
这是我的 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);}
最佳答案
您不能使用 ==
比较字符串
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);
}
关于python - 检查字符串为 1, 0 否则打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35324295/