Python 在 If 语句中检查串行字符串 [英] Python checking for serial string in If statement

查看:44
本文介绍了Python 在 If 语句中检查串行字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 python 的新手,我正在尝试使用它来读取文件并将文件的每一行写入 RS-232 端口.我的代码波纹管似乎在大多数情况下都有效,除了我的听和反应段.通过四处探索,如果我从我的设备 (RS-232) 收到Start\r"或End\r"字符串,我的 if 语句似乎无法读取.任何人都可以就缺少的内容提供反馈吗?

As a newbie to python, I'm trying to use it to read a file and write each line of the file to the RS-232 port. My code bellow seems to work for the most part, except for my listen and react segments. From poking around, it seems that my if statements can't read if I've received a "Start\r", or "End\r" string from my device (RS-232). Can anyone provide feedback on what is missing?

import serial
import time

port = "/dev/ttyS0"
speed = 9600

print("\n\n\n\nScript Starting\n\n\n")

ser = serial.Serial(port, speed, timeout=0) 

ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output and discard all that is in buffer

text_file = open("my.file", "r")
lines = text_file.read().split('\n')
i = 0
counter = 0


while i<len(lines):

    response = ser.readline()

    if (counter == 0):
        print("\n\nProbing With Off Data\n")
        ser.write('FFF')
        ser.write('\r')
        counter+=1

    if (response == 'Start'):

        ser.write('FFF')
        ser.write('\r')

    if (response == 'End'):
        print("\nString Transmitted:")
        print lines
        make_list_a_string = ''.join(map(str, lines))
        ser.write(make_list_a_string)
        ser.write('\r')
        print("\n")
        i+=1




text_file.close()
exit(0)

推荐答案

尝试使用 strip() 去掉任何尾随或前面的 '\r's:

Try using strip() to get rid of any trailing or preceding '\r's:

if (response.strip() == 'Start'):

这篇关于Python 在 If 语句中检查串行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆