Jul-11-2021, 07:12 PM
Working more and more on this code, I was able to fix the looping issue (thanks Deanhystad), but still having an issue of receiving back from the serial port.
I'm was getting inconsistent returns from the serial port each time I run the program (see output).
I noticed that I do not get return information each time the program does a ser.read(ser.inWaiting(), only the first time even though I think I am doing repeated ser.write. Also ser.isOpen value changes between program runs. I don't understand this.
If the program receives RX b'\x01\x01\x01\xad' on the first read, then the program ends as expected, but, if the first read is something like RX b'\x1exxxx' then it won't end well.
Please help.
Here is my code:
I'm was getting inconsistent returns from the serial port each time I run the program (see output).
I noticed that I do not get return information each time the program does a ser.read(ser.inWaiting(), only the first time even though I think I am doing repeated ser.write. Also ser.isOpen value changes between program runs. I don't understand this.
If the program receives RX b'\x01\x01\x01\xad' on the first read, then the program ends as expected, but, if the first read is something like RX b'\x1exxxx' then it won't end well.
Please help.
Here is my code:
#// Sends a message via serial & receives back information via serial. import time import serial ser = serial.Serial('/dev/ttyS0', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) print (ser.isOpen()) track_req = bytearray([170,7,2,0,4,180]) state_req = bytearray([170,1,0,171]) state_ret = bytearray([0,0,0,0,0]) Zeros = bytearray([0,0,0]) Playing = True track_req[5] = track_req[0]+ track_req[1]+ track_req[2]+ track_req[3]+ track_req[4] print ("Script Started", track_req) ser.write(track_req) time.sleep(2) while Playing: print ("Loop Query Requested") print ("---> ", ser.isOpen()) ser.write(state_req) time.sleep(1) if (ser.inWaiting()>0): print ("ReadLine", ser.inWaiting()) print ("===> ", ser.isOpen()) state_ret = ser.read(ser.inWaiting()) print("RX ", state_ret) if (state_ret == Zeros): Playing = False print ("Done") ser.close()
Output:pi@raspberrypi:~ $ sudo python3 SerialTest2.py
True
Script Started bytearray(b'\xaa\x07\x02\x00\x04\xb7')
Loop Query Requested
---> True
ReadLine 4
===> True
RX b'\x01\x01\x01\xad'
Loop Query Requested
---> True
Loop Query Requested
---> True
Loop Query Requested
---> True
ReadLine 3
===> True
RX b'\x00\x00\x00'
Done
pi@raspberrypi:~ $ sudo python3 SerialTest2.py
True
Script Started bytearray(b'\xaa\x07\x02\x00\x04\xb7')
Loop Query Requested
---> True
ReadLine 5
===> True
RX b'\x1exxxx'
Loop Query Requested
---> True
Loop Query Requested
---> True
Loop Query Requested
---> True
Loop Query Requested
---> True
^CTraceback (most recent call last):
File "SerialTest2.py", line 30, in <module>
time.sleep(1)
KeyboardInterrupt
pi@raspberrypi:~ $