I'm trying to use Python3 on Raspberry to communicate with a serial device. The protocol is as follows:
- Host sends command byte (contains address and data type)
- Device echos command byte
- Host sends operand byte (more data type info)
- Device echos operand byte as well as the first byte of data
- Host echos first byte of data. Device sends second byte of data. Repeat until 5 total data bytes
The device should only receive and send in binary (according to the outdated manual I've been referencing) but when I ask for the second data byte, I get "\t" or some other odd character. The command, operand, and first data byte all seem to work as they should. But after that I start getting some unexpected characters.
Is the device actually communicating in something other than binary?
My coding talents are still in the infant stages so ignore the overuse of print commands. Feel free to nitpick as I am new..
import serial
import time
import binascii
ser = serial.Serial(
port='/dev/ttyUSB0',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout = 2)
command=b"\x92"
operand =b"\x02"
sleepy = 0.2
data = bytearray()
while True:
ser.write(command) #send command byte
time.sleep(sleepy)
print(ser.read(1)) #recieve command byte
time.sleep(sleepy)
ser.write(operand) #send operand byte
time.sleep(sleepy)
echo = ser.read(2)#recieve operand byte & first data byte
print(echo)
time.sleep(sleepy)
data.append(echo[1])
ser.write(bytearray([echo[-1]])) #send first data byte echo
time.sleep(sleepy)
echo = ser.read(10) #recieve second data byte
print(echo)
time.sleep(sleepy)
data.append(echo[-1])
print(echo[-1])
ser.write(bytearray([echo[-1]])) #send second data byte echo
time.sleep(sleepy)
echo = ser.read(10) #recieve third data byte
print(echo)
time.sleep(sleepy)
data.append(echo[-1])
print(echo[-1])
ser.write(bytearray([echo[-1]])) #send third data byte echo
time.sleep(sleepy)
echo = ser.read(10) #recieve fourth data byte
print(echo)
time.sleep(sleepy)
data.append(echo[-1])
print(echo[-1])
ser.write(bytearray([echo[-1]])) #send fourth data byte echo
time.sleep(sleepy)
echo = ser.read(10) #recieve 5th data byte
print(echo)
time.sleep(sleepy)
data.append(echo[-1])
print(echo[-1])
print(data)
ser.close()
For example, when I run this I get the data array "(b'\x04\x08hT^')". I always get the first \x04 but the characters after that are random.