uasyncio - StreamWriter in two async loops.

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
prem111
Posts: 127
Joined: Sun Feb 23, 2020 3:18 pm

uasyncio - StreamWriter in two async loops.

Post by prem111 » Thu Nov 12, 2020 7:28 am

Hi. How to use uasyncio.StreamWriter in two asynchronous loops in the same time? Sometimes when he wants to write to uart at the same time, not everything comes up. Thanks for help!

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: uasyncio - StreamWriter in two async loops.

Post by pythoncoder » Thu Nov 12, 2020 8:27 am

This sounds like very bad practice. If two tasks write to the UART at once, the result will be a garbled mixture of the two messages.

The correct way to handle UART communications is to associate a single StreamWriter and StreamReader with the UART, with a task handling writes and another handling reads. If multiple tasks want to write, they should add their messages to a queue.

The write task has a while True loop which checks for a message on the queue and, if present, writes it to the StreamWriter. That way message integrity is maintained.
Peter Hinch
Index to my micropython libraries.

prem111
Posts: 127
Joined: Sun Feb 23, 2020 3:18 pm

Re: uasyncio - StreamWriter in two async loops.

Post by prem111 » Sat Nov 14, 2020 9:51 am

Everything ok, I did it in queue. Thanks.

Post Reply