Sunday, 24 July 2022

PySerial package is reading serial data before writing?

I am trying to send one byte (128) to a device through serial port and expect to receive back 81 in Hex[space].

Note: The device is automatically transmitting the data it has. Before running Python script, I first tested whether my serial connection is working. First I tested the serial connection with a terminal emulation program called RealTerm: Serial/TCP Terminal.

For program configuration, I set Port baud rate to 115200 and kept everything else to default. I set display as Hex[space].

For testing, I connected the device to PC through serial port (rs232), I first sent 128 and successfully received 82 as response from the device. second, I sent 0x82 and successfully received all stored data in the device.

enter image description here

enter image description here

I tested also to see whether the data is read whenever it is available in buffer but it seems that python is reading before writing.

enter image description here

The Python script is just to send first byte, that is 128. I am expecting to have as output 82.

import serial, struct

rs232 = serial.Serial(
    port = 'COM6', 
    baudrate = 115200, 
    bytesize = serial.EIGHTBITS,
    parity = serial.PARITY_NONE,
    stopbits = serial.STOPBITS_ONE
    )
print(rs232.isOpen)
if rs232.isOpen() == True:
    bytes_to_send = struct.pack('B', 128)
    device_write = rs232.write(bytes_to_send)
    device_read = rs232.read(1)
    print(hex(int.from_bytes(device_read, byteorder='little')) )
else:
    print('rs232 is not open.')
    rs232.close()

The output of the script is: b'\x00'.

I am afraid, I am confusing in data conversion which is why I am not receiving the correct output.



from PySerial package is reading serial data before writing?

No comments:

Post a Comment