Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending byte strings to serial device

I'm using Python3 running on a Raspberry. I have a serial device (max232/PiC16F84) connected to the Raspberry via an USB to Serial adapter. I try to send two bytes to the device (e.g 0000 0011) which then will be interpreted as a command by the PIC. The USB - serial adapter is configured correctly and the parameter such as bauderate should be ok. I guess that my code doesn't send the correct bytes to the serial port.

import serial

ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=1200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    xonxoff=serial.XOFF,
    rtscts=False,
    dsrdtr=False
)

ser.open()
ser.isOpen()

print("Initializing the device ..")

ser.write(bytes(0x00))

print("Write command")
ser.write (bytes(0x04))

print('Done')
like image 330
joebee Avatar asked Mar 18 '23 07:03

joebee


1 Answers

You are using the bytes constructor incorrectly. When you call it with an int as argument, you get:

bytes(int) -> bytes object of size given by the parameter initialized with null bytes

So bytes(0x00) (which is just bytes(0)) is the empty string, and bytes(0x04) is four zero bytes:

>>> bytes(0x00)
b''
>>> bytes(0x04)
b'\x00\x00\x00\x00'

What you want is bytes([ 0x00 ]) etc., or simply an array with all your byte values:

>>> bytes([0, 4])
b'\x00\x04'

If the string is short, you could simply write it as a constant: b'\x00\x04', for example. See the documentation of bytes() for more options.

like image 114
alexis Avatar answered Mar 27 '23 23:03

alexis