Reputation: 118
I am having some trouble with sending the following hex codes 0x01 0x03 0x00 0x00 0x00 0x01 0x0a 0x84 to a serial device (Voltage Sensor) which will return an int for current voltage using Python and pyserial. My code is as follows:
import serial
import time
ser = serial.Serial(
port=1,
baudrate=38400,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.EIGHTBITS,
timeout=0,
xonxoff=0,
rtscts=0)
ByteStringToSend = "\x01\x03\x00\x00\x00\x01\x0a\x84"
ser.write(ByteStringToSend)
time.sleep(1)
RecievedData = ""
while ser.inWaiting() > 0:
RecievedData = ser.read(1)
return RecievedData
The problem is it appears Python is sending each byte as an individual packet see below image from a serial monitor
see image at http://www.centralinfo.com.au/images/SerialOutput.png
The first 8 bytes (00 - 07) is from the python app (note the altinate colors for the different packets) The next 8 bytes (08 - 0f) is a VB.net app sending the same data which works.
My question is how do I send the 8 hex bytes above so it is in one packet (Modbus Protocol) as per the vb.net app?
VB Code for comparison:
' open the serial port if it is closed
If Me.SerialPort1.IsOpen = False Then
Me.SerialPort1.PortName = ComPort
Me.SerialPort1.BaudRate = "38400" 'Set Baud rate
Me.SerialPort1.RtsEnable = False ' Set RTS
Me.SerialPort1.DtrEnable = False ' Set DTR
Me.SerialPort1.Parity = IO.Ports.Parity.None
Me.SerialPort1.StopBits = IO.Ports.StopBits.Two
Me.SerialPort1.DataBits = 8 ' Set data length
Me.SerialPort1.Handshake = Handshake.XOnXOff
Me.SerialPort1.ReadTimeout = 10000
Me.SerialPort1.WriteTimeout = 10000
Me.SerialPort1.Open()
End If
Try
Dim CommandBlock(7) As Byte
CommandBlock(0) = &H1
CommandBlock(1) = &H3
CommandBlock(2) = &H0
CommandBlock(3) = &H0
CommandBlock(4) = &H0
CommandBlock(5) = &H1
CommandBlock(6) = &HA
CommandBlock(7) = &H84
Me.SerialPort1.Write(CommandBlock, 0, CommandBlock.Length)
Thread.Sleep(100)
Return True
Catch ex As Exception
Return False
End Try
Thanks in advance for your time Chris
Upvotes: 1
Views: 5602
Reputation: 954
Your VB app enables XON/XOFF protocol, while your python app does not. Without XON/XOFF turned on, I suspect that your python app is waiting for a certain amount of time between each bytes before sending it, thus the receiving device sees each byte as an individual "packet".
Upvotes: 1