简体   繁体   中英

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

In order to make script sleep for 30 seconds, just add following:

time.sleep(30)

before x = ser.read() .

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.

The easiest way I have found to poll a serial port is to utilize the time module. This is done by calculating the end point in time you wish to run to, and using that as the condition for a while loop.

#Set up serial connection
import time
time_end = time.time() + 30

while time.time() < time_end:
    x = ser.read(16)
    if x is not None:
        break

As an aside, according to the pySerial api , passing a timeout value of None enters a blocking mode. In other words, the serial port sits and listens to the port until data is read.I would suggest passing a float instead (the value of which depends on your application).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM