Chuck Chuck - 4 months ago 43
Python Question

Read Serial Python

I am reading serial data on my Raspberry Pi with the console:

stty -F /dev/ttyUSB0 1:0:9a7:0:3:1c:7f:15:4:5:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0
cat < /dev/ttyUSB0 &
echo -n -e '\x2F\x3F\x21\x0D\x0A' > /dev/ttyUSB0


And I am getting data line for line:

/ISk5MT174-0001
0.9.1(210832)
0.9.2(1160808)
0.0.0(00339226)
0.2.0(1.03)
C.1.6(FDF5)
1.8.1(0004250.946*kWh)
1.8.2(0003664.811*kWh)
2.8.1(0004897.813*kWh)
2.8.2(0000397.465*kWh)
F.F.0(0000000)
!


Now I am trying to do this with python:

import serial

SERIALPORT = "/dev/ttyUSB0"
BAUDRATE = 300

ser = serial.Serial(SERIALPORT, BAUDRATE)

print("write data")
ser.write("\x2F\x3F\x21\x0D\x0A")

time.sleep(0.5)
numberOfLine = 0

while True:
response = ser.readline()
print("read data: " + response)

numberOfLine = numberOfLine + 1
if (numberOfLine >= 5):
break

ser.close()


But I only get "write data" and no response from my USB0 device.

Any suggestions?

Kind Regards

Answer

I'm guessing your device is the same as discussed here: https://www.loxforum.com/forum/faqs-tutorials-howto-s/3121-mini-howto-z%C3%A4hlerauslesung-iskra-mt174-mit-ir-schreib-lesekopf-und-raspberry

If so, you need to know that by default, pySerial opens ports with 8 databits and no parity. (see: https://pythonhosted.org/pyserial/pyserial_api.html -> __init__)

So, at the very least you want to:

ser = serial.Serial(SERIALPORT, BAUDRATE, SEVENBITS, PARITY_EVEN)

Perhaps you also need to set other flags, but I don't read stty :) To see what that string of numbers means, run the first stty command and then run:

stty -F /dev/ttyUSB0 -a

It'll output the settings in human readable form, that might bring you closer to a solution.

Good luck!