rgomez rgomez - 18 days ago 8
Python Question

Python read from serial

I have a Card read connected to a ttyUSB0 device, I need to make a python script that when ran will wait (for instance 30s) for a card to pass and after it passes and receives a line with data closes the script and prints the line with data only. If the card does not pass within 30s closes the script.

Here is the script:

#!/usr/bin/python

import time
import serial

ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate = 4800,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS,
timeout=1
)

counter=0

while 1:
x=ser.readline()
print x


With this what happens is that it keeps printing the line for ever until I hit Ctrl+C

EDIT: Found how to wait for the read I want, now, what would be the best way to make the whole script timeout after 30s?

#!/usr/bin/python

import time
import serial

ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate = 4800,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS,
timeout=None
)


#while 1:
x=ser.read(size=16)
print x

Answer

You could certainly wait for 30 seconds to finish before testing if anything is inserted (as is suggested by Fejs' answer), but I assume you wouldn't want to wait 30 full seconds every time something is inserted.

If you wanted to continuously test for anything and terminate the script if something is found, you could do something like this:

for x in range(30):
    if ser.read(size=16) != None:
        x = ser.read(size=16)
        #(DO WHATEVER WITH X HERE)
        break
    else:
        time.sleep(1)

This will check for something readable continuously once every second, for 30 seconds. If something is found, it terminates the for loop.

Comments