为什么 pyserial 暂停 python 程序
Why is pyserial pausing python program
我在一个对时间极其敏感的循环中使用了一些 python 代码(运行 on a raspberry pi)(偏差不应超过 +=.0001秒)。我发现
if serial.Serial('/dev/ttyUSB0').read(): #what to do when there is data pending
data = serial.Serial('/dev/ttyUSB0').read()
似乎是问题所在。我很少通过串行连接发送任何东西,当我这样做时,它小于 10 字节。这段代码似乎在接收到数据之前阻止了程序。
例如,如果我收到持续不断的数据流并打印出每个循环的执行时间,它大约为 .1 毫秒,这对我的目的来说很好,但如果我一分钟没有收到任何东西,然后接收数据,该循环需要 60 秒才能完成。
我需要那一小段代码来跳过 运行 并且在串行中没有数据等待时不阻止程序。
下面是可能相关的更完整的代码部分:
raspi=serial.Serial('/dev/ttyUSB0')
if raspi.read(): #what to do when there is data pending
print data #this is a messy debugging tool to see what the pi recieves
data = raspi.read()
raspi.write(confirmed + data) #this is the data confirmed message
if((str(data)[0]=='s' or str(data)[0]=='S' or str(data)[0]=='b' or str(data)[0]=='B')): #this is for going straight. Command is s# or b#, # being 1-9.
lspeed=str(data)[1]
print('lspeed is now ' + str(lspeed))
raspi.write('lspeed is now ' + str(lspeed))
rspeed=str(data)[1]
print('rspeed is now ' + str(rspeed))
raspi.write('rspeed is now ' + str(rspeed))
if(str(data)[0]=='r' or str(data)[0]=='R'):
rspeed=str(data)[1]
print('rspeed is now ' + str(rspeed))
raspi.write('rspeed is now ' + str(rspeed))
if((str(data)[0]=='l' or str(data)[0]=='L') and str(data)!='launch'):
lspeed=str(data)[1]
print('lspeed is now ' + str(lspeed))
raspi.write('lspeed is now ' + str(lspeed))
用 if(serial.Serial('/dev/ttyUSB0').inWaiting>=1):
替换 if serial.Serial('/dev/ttyUSB0').read():
就可以了。
如果没有数据等待,这种方式会跳过代码。我使用的参考误导了我。
我在一个对时间极其敏感的循环中使用了一些 python 代码(运行 on a raspberry pi)(偏差不应超过 +=.0001秒)。我发现
if serial.Serial('/dev/ttyUSB0').read(): #what to do when there is data pending
data = serial.Serial('/dev/ttyUSB0').read()
似乎是问题所在。我很少通过串行连接发送任何东西,当我这样做时,它小于 10 字节。这段代码似乎在接收到数据之前阻止了程序。
例如,如果我收到持续不断的数据流并打印出每个循环的执行时间,它大约为 .1 毫秒,这对我的目的来说很好,但如果我一分钟没有收到任何东西,然后接收数据,该循环需要 60 秒才能完成。
我需要那一小段代码来跳过 运行 并且在串行中没有数据等待时不阻止程序。
下面是可能相关的更完整的代码部分:
raspi=serial.Serial('/dev/ttyUSB0')
if raspi.read(): #what to do when there is data pending
print data #this is a messy debugging tool to see what the pi recieves
data = raspi.read()
raspi.write(confirmed + data) #this is the data confirmed message
if((str(data)[0]=='s' or str(data)[0]=='S' or str(data)[0]=='b' or str(data)[0]=='B')): #this is for going straight. Command is s# or b#, # being 1-9.
lspeed=str(data)[1]
print('lspeed is now ' + str(lspeed))
raspi.write('lspeed is now ' + str(lspeed))
rspeed=str(data)[1]
print('rspeed is now ' + str(rspeed))
raspi.write('rspeed is now ' + str(rspeed))
if(str(data)[0]=='r' or str(data)[0]=='R'):
rspeed=str(data)[1]
print('rspeed is now ' + str(rspeed))
raspi.write('rspeed is now ' + str(rspeed))
if((str(data)[0]=='l' or str(data)[0]=='L') and str(data)!='launch'):
lspeed=str(data)[1]
print('lspeed is now ' + str(lspeed))
raspi.write('lspeed is now ' + str(lspeed))
用 if(serial.Serial('/dev/ttyUSB0').inWaiting>=1):
替换 if serial.Serial('/dev/ttyUSB0').read():
就可以了。
如果没有数据等待,这种方式会跳过代码。我使用的参考误导了我。