作为python的新手,我正在尝试使用它来读取文件并将文件的每一行写入RS-232端口。除了我的听力和反应段之外,我的代码似乎在大多数情况下都起作用。从我的设备(RS-232)收到“开始\ r”或“结束\ r”字符串,似乎我的if语句无法读取。任何人都可以提供有关缺失内容的反馈吗?
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)
答案 0 :(得分:0)
尝试使用strip()去掉任何尾随或前面的'\ r's:
if (response.strip() == 'Start'):