[Tutor] Serial communication problem

Alan Gauld alan.gauld at yahoo.co.uk
Thu Dec 7 04:20:53 EST 2023


On 07/12/2023 04:07, Phil wrote:

> 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.

Presumably you see the LED turn on/off?
That's how you know it works, right?

> This code then waits for the pico to send "ok" as an acknowledgement. 
> This also works.

Because you enter the if statement?

> 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.

How do you know the board does not receive the 's'?
Is there something that happens on the board that tells you
when it receives it? How do you know the board is not receiving
but ignoring it?

You say it should return the LED status. But what exactly would
that look like?

BTW, shouldn't you be converting the received signals to strings?
You may get away with simple messages like OK but I assume the
data received is actually bytes?

>              # 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

I'd normally write this like:

STATUS = b"s"

while True:
   byte = ser_read.read()
   if byte == HEADER_BYTE:
      break
ser_write.write(STATUS)

The write() is not logically part of the loop, it's a one off event
so should be outside. But that's just a cognitive dissonance
type issue...

>              print("outside the loop")
>              # Read the actual response data
>              # data = ser_read.read()
>              time.sleep(2)

What does the sleep() do?
Are you sure the board hasn't removed the data in the interim?

> outside the loop
> Received: ok
> 
> The last line should the LED's status and not the acknowledgement "ok"

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos





More information about the Tutor mailing list