Martin Ocando Corleone
Martin Ocando Corleone

Reputation: 104

Serial missing data in RPI3 using Python

I'm using raspberry pi 3 and this code to send a request to a device and receive the response from.

#!/usr/bin/python3.7    

import socket               # Import socket module
import thread
import time
import serial

ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=115200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS
)

input = '5A03010d0a75'    
print "Sending request... "+input
ser.write(input.decode("hex"))
print "Request sent."

output=""
while True:
  output += ser.read(1)
  #time.sleep(0.1)
  print "Reading... "+output.encode('hex')

It handles the response but there are missing bytes, it should receive a 56 bytes length string instead of 53.

This is the output: enter image description here

a5030119010000010001000a20120118180130090100020505030117501701051421000301040120010516039833630004060104c200007d

There are 3 missing bytes

The serial configuration is what the manufacturer says in the documentation. This device works well with my other application made in Delphi.

EXTRA This is a comparison from my delphi app and this py script:

Delphi app
A5030119010000010001000A20120118180130090100020505030117501701051421000301040120010516039833630004060104C200007D
Python script
a503011901000001000100    1201181801300901000205050301175017010514210003010401  010516039833630004060104c200007d

Upvotes: 1

Views: 840

Answers (1)

Martin Ocando Corleone
Martin Ocando Corleone

Reputation: 104

The solution was to set the max byte to the serial.read() method This should be related to the device work behavior

#!/usr/bin/python3.7
#sudo python /home/testing.py

import serial
import time


ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=115200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=5
)

input = '5A03010d0a75'    
print "Sending request... "+input
ser.write(input.decode("hex"))
print "Request sent."

output=""
time.sleep(1)
while ser.inWaiting() > 0:
  output += ser.read(10) #setting it to 10 will fix this problem

print "Reading... "+output.encode('hex')

Upvotes: 1

Related Questions