[Tutor] Serial communication problem
Phil
phillor9 at gmail.com
Wed Dec 6 23:07:15 EST 2023
Thank you for reading this.
I've come to the end of my limited abilities with this and I know that
this is a long shot but someone may spot an obvious error. Two days of
Internet searching has not led to a solution.
This code sends a "1" and "0" to a pico board to turn it's LED on and
off. So far so good and this works.
This code then waits for the pico to send "ok" as an acknowledgement.
This also works.
Next, this code sends an "s" asking for the LED's status. This where the
problem is. The pico does not receive the "s", yet the "1" and "0" are
received using the same read method.
It seems to me that perhaps the serial mechanism is missing something
between sending characters, receiving a response and then sending
another character.
Initially, I thought that using the " with" block may have been the
cause of the problem but it's not.
import time
from serial_write import SerialWrite # these are my simple classes
containing a write, a read
from serial_read import SerialRead # and close methods
# header byte to indicate start of response
HEADER_BYTE = "ok"
with SerialWrite("/dev/ttyACM0", 9600) as ser_write, SerialRead(
"/dev/ttyACM0", 9600
) as ser_read:
while True:
for char in (b"1", b"0"):
ser_write.write(char)
time.sleep(1)
# Wait for header byte to indicate response is ready
while True:
print("in the loop")
byte = ser_read.read()
print(byte)
if byte == HEADER_BYTE:
print(f"after if: {byte}")
ser_write.write(bytes("s", "utf-8")) # b"s")
break
print("outside the loop")
# Read the actual response data
# data = ser_read.read()
time.sleep(2)
data = ser_read.read()
print(f"Received: {data}")
time.sleep(1)
print()
print()
If it helps, this code prints:
in the loop
ok
after if: ok
outside the loop
Received: ok
The last line should the LED's status and not the acknowledgement "ok"
--
Regards,
Phil
More information about the Tutor
mailing list