Brandon Mitchell
Brandon Mitchell

Reputation: 3

Error reading serial data transmission

Using a raspberry pi I am having issues reading data that is being transmitted serially. My code was working when I tested it on a different machine but isn't working now.

The baud rate is 9600 w/ no parity, 8 data bits, 1 stop bit and I want the program to handle a variable length of characters (Sometimes 100K+). The reading portion of the code is as follows:

ser = serial.Serial('/dev/ttyAMA0', 9600, parity = serial.PARITY_NONE, timeout=1)

While True:
    data = ser.read(1)
    bytesToRead = ser.inWaiting()
    if bytesToRead:
       data = data + ser.read(bytesToRead)
       encodedData = data.encode('hex')

With this code, Shouldn't I be able to read all the characters as Hex as long as the baud/parity/etc match up with the transmitting system?

Upvotes: 0

Views: 1933

Answers (1)

Peter Gibson
Peter Gibson

Reputation: 19554

While True:
    data = ser.read(1) 

This waits for a single character to be read (times out after 1s due to the timeout specified in the Serial constructor) and stores it in data

    bytesToRead = ser.inWaiting()
    if bytesToRead:
       data = data + ser.read(bytesToRead)
       encodedData = data.encode('hex')

Now instantly check for any other characters in buffer - this will usually be zero. Due to the fact that you're running at 9600 baud, Python will usually see the characters come in one at a time. So your if bytesToRead statement will mostly be false as each incoming character is consumed by the above ser.read(1).

If you just want to process each character individually, you can do:

While True:
    data = ser.read(1) 
    if data:
       encodedData = data.encode('hex')

Or if you want to keep adding it to a buffer, use something like:

data = ''
While True:
    bytesToRead = ser.inWaiting()
    if bytesToRead:
        data += ser.read(bytesToRead) 
        encodedData = data.encode('hex')
        if encodedData.startswith('1234deadb33f`):
            data = data[6:] # strip 6 chars from start of data

Upvotes: 0

Related Questions