Reputation: 325
I'm using some python code (running on a raspberry pi) in a loop which is extremely time sensitive (shouldn't deviate much more than +=.0001 s). I've found that
if serial.Serial('/dev/ttyUSB0').read(): #what to do when there is data pending
data = serial.Serial('/dev/ttyUSB0').read()
seems to be the problem . I am seldom sending anything through a serial connection and when I do it's under 10 bytes. It seems this code holds up the program until data is received.
For example, if I receive a constant stream of data and print out the execution time for each loop it is around .1ms, which is good for my purposes, but if I don't receive anything for a minute, then receive data, that loop took 60sec to complete.
I need that little bit of code to skip running and not hold up the program if there is no data waiting in the serial.
Here's a more complete portion of code that may be related:
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))
Upvotes: 1
Views: 152
Reputation: 325
Replacing if serial.Serial('/dev/ttyUSB0').read():
with if(serial.Serial('/dev/ttyUSB0').inWaiting>=1):
does it.
This way skips over the code if there is no data waiting. The reference I was using mislead me.
Upvotes: 1