Search code examples
pythonpython-2.7serial-portpyserialadafruit

pySerial splits up the packet and sends data. How do I send large bytes in one go?


my code for connecting to the serial port

    ser = serial.Serial(
port='COM4',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,timeout=0.5
)

if (ser.isOpen):
  ser.close()

ser.open()
buf=b''


out = ''
while 1:
while ser.inWaiting() > 0:
    sleep(1)
    #if ser.outWaiting()==0:
    out = ser.read(ser.inWaiting())

if out != '':
    handle_command(out, ser)
    print ">>" + out.encode('hex')

    out = ''

This part is where I write the data to the port

    elif(some condition):

       if(ser.outWaiting()==0):
         out=ser.write(pSportTotals_p1)
         sleep(0.001)
         ser.flush()


       if(ser.outWaiting()==0):
        ser.write(pSportTotals_p2)
        sleep(0.001)
        ser.flush()

But the output is erratic, and pSportsTotals_p1 is sent in two parts and pSportTotals_p2 is sometimes sent along with the rest of the previous packet. In the attached screenshot, 0a signifies the start of each packet and in the second image you can see that it is attached with the remaining chunk of the previous packet. I am new to serial programming and will appreciate any help in making me understand my errors.first packet second packet


Solution

  • I don't have specific knowledge about pyserial, but having dealt with serial communication before in different languages, I've come to a conclusion you can't know for sure how your data is going to be sent/received.

    You have multiple options :

    • Always send the same amount of N bytes, and on the receiving end, wait until the buffer has more than N data before reading a chunk of N bytes.
    • Implement a protocol with delimiters (for example '\n') and parse the received data to reconstruct your data by looking for the delimiters.