How to save Strings from UART the right way
I'm using a GPy and LTE-M for transmitting measurement data to my own server. The GPy receives a String via UART, which gets send by an Arduino, which collects measurement data. At the moment, I have a working solution, but I'm not happy about the fact, how I save the measurement String:
def serialrecv(uartport): #read the length of the data, letter by letter until we reach EOL dataString = "" char = uart1.read(1) if char is not None: print("") print("Reading string from Serial:") while char is not None: dataString += char.decode("utf-8") char = uart1.read(1) return dataString
I'm basically destroying and re-creating things, which kinda scares me after reading this article: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/
Based on a great tutorial in the Arduino Forum about the basics of Serial Inputs, I've managed to avoid doing that on the Arduino platform. Now I'm using C Strings and create arrays, which I'm using as buffers for data read from a Serial Port of the Arduino.
I don't know the proper way in Python yet.
Is it also common to create a buffer for saving strings received from an UART Port?
Is there a C String equivalent in Python?
Is it necessary to do it on Pycom-Hardware to avoid memory issues and Heap-Fragmentation?
I would be glad for any input, which points me into the right direction.
The strings the GPy receives from the Arduino look like that:
I thank everybody in advance!
@robert-hh Thank you so much for that input! I'm really new to Python in regards of MCU's, so there is still alot to learn for me. Now I'm less afraid, that something could go wrong. :)
robert-hh last edited by robert-hh
@SciWax The code above is fine. Creating and discardign object is a normal operation in Python, so you do not have to care too much about it. Only in very time critical sections like interrupt service routines it is advisable to use preallocated buffers. Such buffers would be preallocated as
buffer = bytearray(size), and then you can index into it. But that is not needed here.
The UART has in internal ringbuffer which is long enough to store your sample string. So there is no risk of loosing characters.
You could improve your code a little bit by applying decode on the final string, not on each character. That saves one object creation/discarding step per character.
dataString = "" char = uart1.read(1) if char is not None: print("") print("Reading string from Serial:") while char is not None: dataString += char char = uart1.read(1) return dataString.decode("utf-8")