在Python Arduino中查找字符串

0 投票
2 回答
537 浏览
提问于 2025-04-18 06:36

我有一个小的Python脚本,我刚开始接触这个语言。我想检查在ser.readline()中是否出现了某个特定的词。我的if语句写得不对,我不太确定该怎么写才能让它持续读取串口中的“sound”这个词。我下面附上了一张输出的图片,你可以看到它是怎么打印的。我希望在找到“sound”这个词时能触发一个MP3,但到目前为止,我甚至还没能让它打印出确认信息,说明它找到了这个词。

import serial
import time
ser = serial.Serial('COM6', 9600, timeout=0)

while 1:
 try:
  print (ser.readline())
  time.sleep(1)

  **if "sound" in ser.readline():
        print("foundsound")**

 except ser.SerialTimeoutException:
  print('Data could not be read')
  time.sleep(1)

Serial Printing

2 个回答

1

你能试试这个:

import serial
import time
ser = serial.Serial('COM6', 9600, timeout=0)

while 1:
 try:
  line = ser.readline()
  print line
  time.sleep(1)

  **if "sound" in line:
        print("foundsound")**

 except ser.SerialTimeoutException:
  print('Data could not be read')
  time.sleep(1)
1

你可能在读取端口数据时比你想的要频繁。我的建议是,在你的主循环每次运行时,只调用一次 ser.readline()

while True:
    try:
        data = ser.readline().decode("utf-8")     # Read the data
        if data == '': continue                   # skip empty data

        print(data)                               # Display what was read
        time.sleep(1)

        if "sound" in data:
           print('Found "sound"!')

    except ser.SerialTimeoutException:
        print('Data could not be read')
        time.sleep(1)

撰写回答