Issue
I'm trying to send byte array data from my computer to my Rpi and I have to use Byte Arrays for the task. As seen below in the first code line, which is the code in my private computer, I create the byte array and send it using ttyUSB0. I also decoded the same packet in my computer which gives the expected result. The expected answer is given in the image below. In my RPi,I use ser.read to read the lines I send but as seen at the last image, the entire package changes when I send the data over. I expect to see the same output I see on the first image when I replicate it on RPi.
import struct
import serial
ser = serial.Serial('/dev/ttyUSB0')
packet = bytearray() # Creating the canvas of the packet
packet.append(0xA9) # Header parameter
packet.append(0x01) # Valid value
zero_array = bytearray(4) # To compensate taken data
elements_array = [3.0, 4.0, 5.0, 6.0, 1.0]
for element in elements_array: # Place data in packet
if element != 0.0:
print(element)
out = bytearray(struct.pack("f", element)) # Convert float value to byte
print(out)
packet.extend(out) # Place packet canvas
else:
packet.extend(zero_array)
print(":")
packet.append(0xB8) # Footer parameter
ser.write(packet)
print(packet)
print(struct.unpack('b', packet[(0):(1)]))
print(struct.unpack('b', packet[(1):(2)]))
print(struct.unpack('f', packet[(2):(6)]))
print(struct.unpack('f', packet[(6):(10)]))
print(struct.unpack('f', packet[(10):(14)]))
print(struct.unpack('f', packet[(14):(18)]))
print(struct.unpack('f', packet[(18):(22)]))
print(struct.unpack('b', packet[(22):(23)]))
import time
import serial
import struct
import ctypes
import numpy as np
from struct import *
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate = 57600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout = 10
)
packet = ser.read(23)
if(packet):
print(packet)
print(struct.unpack('b', packet[0:1]))
print(struct.unpack('b', packet[1:2]))
print(struct.unpack('f', packet[2:6]))
print(struct.unpack('f', packet[6:10]))
print(struct.unpack('f', packet[10:14]))
print(struct.unpack('f', packet[14:18]))
print(struct.unpack('f', packet[18:22]))
print(struct.unpack('b', packet[22:23]))
Solution
As others suggested in comments, there was a problem with my baudrate. To solve this, I added the lines:
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate = 57600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout = 10
On my sender's script which solved the problem. Make sure both computers have the same values.
Answered By - ExperiencedSoup Answer Checked By - Katrina (WPSolving Volunteer)