检查字符串为 1, 0 否则打印字符串
check string to be 1, 0 else print string
我有一个 arduino 连接到我的电脑 (COM9),我有 3 个 python 脚本。第一个通过串行发送“1”。
第二个通过串行发送“0”。
第三个发送一个词,你给它。
ser.write("1")
然后在我的arduino上我有一些代码。
如果启动 python 脚本 1,它会打开 LED。如果启动 2 秒脚本,它将关闭 LED。如果 python 脚本 3 被启动,它将把这个词打印到液晶显示器上。
所有硬件配置正确。
问题是,当我 运行 脚本 1 时,不仅 led 会打开,而且 lcd 上也会有一个 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);
}
除了之前关于比较的回答外,您还错误地设置了 ifs。当第一个if为真时,你就陷入了第二个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);
}
}
我有一个 arduino 连接到我的电脑 (COM9),我有 3 个 python 脚本。第一个通过串行发送“1”。 第二个通过串行发送“0”。 第三个发送一个词,你给它。
ser.write("1")
然后在我的arduino上我有一些代码。 如果启动 python 脚本 1,它会打开 LED。如果启动 2 秒脚本,它将关闭 LED。如果 python 脚本 3 被启动,它将把这个词打印到液晶显示器上。
所有硬件配置正确。 问题是,当我 运行 脚本 1 时,不仅 led 会打开,而且 lcd 上也会有一个 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);
}
除了之前关于比较的回答外,您还错误地设置了 ifs。当第一个if为真时,你就陷入了第二个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);
}
}