检查字符串为1,否则打印字符串

2024-10-02 18:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个arduino连接到我的计算机(COM9),我有3个python脚本。第一个通过串行发送“1”。 第二个通过串行发送一个“0”。 第三个发送一个词,你给它。你知道吗

ser.write("1")

在我的arduino上我有一些代码。 如果启动python脚本1,它将打开一个指示灯。如果启动2秒脚本,它将关闭一个led。如果启动pythonscript 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);}

Tags: 代码脚本falsetruelediflcdemail
2条回答

不能使用==比较字符串

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);
    }
}

相关问题 更多 >