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

标签 python c arduino pyserial

我有一个 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/

相关文章:

c++ - Arduino 类中未声明的字符串

python - 如何使用 NumpyDoc 正确记录属性

python - WSGI/APACHE/DJANGO ..导入错误: Could not import settings

c++ - 如何在 Ubuntu 中使用 C 语言的命令终端

c - 对大页面使用 mmap 和 madvise

python - 所有线程均未与QThread以及QtSerialPort(对于Arduino)和Matplotlib一起运行

python - 检查 python 日期列表中的任何日期是否在两个日期列之间

python - 使用日期时间获取 pandas 数据帧索引中的第一次出现

c - 选择 "leader and follower"怎么办?

c++ - 控制结构让我失望