【发布时间】:2017-04-23 10:38:45
【问题描述】:
我正在尝试读取一些 GPIO 的值。代码如下:
import serial
import codecs
import time
ser = serial.Serial(port = 'COM4', baudrate = 9600, \
parity = serial.PARITY_NONE, \
stopbits = serial.STOPBITS_ONE, \
bytesize = serial.EIGHTBITS, \
timeout = 0, \
)
print('connected to: ',ser.name)
ser.close()
def SSend(input):
ser.write(codecs.decode(input, "hex_codec")) #send as ASCII
print('sent: ', input)
def ReadIO():
#open the port
try:
ser.open()
except:
print('error opening serial port')
exit()
#flush the buffers
ser.flushInput()
ser.flushOutput()
#write data to read from GPIO
#causes SC18IM to return a byte containing each of the 8 I/O values
SSend(b'4950')
time.sleep(0.1) #allow time for the data to be received
#read the data
serialData = False
serialData = ser.readline()
ser.close()
return serialData
while 1:
print(ReadIO())
time.sleep(0.5)
这将打印以下内容:
发送: b'4950'
b''
(我期待返回 0x00 或 0x20 而不是空字节)
我知道我的硬件和我发送的一样好,因为它恢复了我在使用 Realterm 时所期望的并且在我的脚本中的其他地方成功写入命令。
我运气不错
#read the data
serialData = False
for c in ser.readline():
print('in loop')
print(c)
serialData = c
ser.close()
但是,我真的不明白它为什么起作用,而且似乎只是间歇性地起作用。
感谢阅读。
【问题讨论】: