Page 1 of 1

Reading UART0 bytes from RX

Posted: Sat Jan 21, 2017 3:28 pm
by happyday
I have a CO2 sensor that uses a UART. The only UART that seems available is UART0. I am running MicroPython from WebREPL so the CO2 sensor can use the UART.
I create a and upload. The gasdata has the right return bytes from the CO2 sensor (verified with a logic analyzer):

from machine import UART
if __name__ == '__main__':
uart = UART(0,9600)
for value in gasdata:

DOESN'T WORK (bytes in gasdata are all = 0):

from machine import Timer
from machine import UART
def getReadings():
co2 = UART(0,9600)
gasdata = bytearray(9)
for value in gasdata:
def takeReadings():

if __name__ == '__main__':
t = Timer(1)
t.init(period=5000,mode=Timer.PERIODIC,callback=lambda t:takeReadings())

What am I missing to be able to get the correct bytes read and into gasdata? (what am i not understanding?)

thank you.

Re: Reading UART0 bytes from RX

Posted: Sat Jan 21, 2017 8:13 pm
by deshipu
I'm not sure, but perhaps you have to wait for the device to send the reply, not read it immediately.

Re: Reading UART0 bytes from RX

Posted: Sat Jan 21, 2017 8:35 pm
by happyday
Thank you. From looking at the bytes within a logic analyzer and having to code work just within, i do not think it is about waiting. Rather I think it might be the memory allocated to hold the incoming bytes of the UART0 are not being held onto so that the readinto() gets a chance to copy it into it's buffer. I don't know.

Re: Reading UART0 bytes from RX

Posted: Sun Jan 22, 2017 7:24 am
by pythoncoder
Assuming your buffer size is the same in the first example it should work. The uart.readinto method should block until either the buffer fills or a timeout occurs. If the UART timeout exceeds the timer period and you're getting fewer than 9 characters things might get re-entrant.

There are no buffer lifetime issues in your code as far as I can see. The buffer is declared as a local object and it's only used in the function body. It will be deallocated on return from the function because no references to it are in scope; but by then it has served its purpose.

Have you tried issuing takeReadings() at the REPL rather than in response to a timer callback? This would isolate possible re-entrancy issues.

I should perhaps warn that my MicroPython UART experience is restricted to the Pyboard: if there is an ESP8266 specific issue it needs identifying and reporting.