mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

reading batch of serial values from USB and storing as a list

Wed Mar 13, 2019 10:17 am

I have an arduino connected to my raspberry pi via USB. The arduino is using "println()" to output serial values every time a sensor is triggered.
So for example, every 5 minutes or so, the arduino will send over a few hundred lines of data via serial to the raspberry pi that looks like:
536
366
478
322
366
743
477
.....and so on

My question is: Using python on my raspberry pi, how can I "listen" for when the arduino sends over these data points, and store them in a list?

I have tried this code below, and it seems to only grab and print the first data point sent over, then stops.

Code: Select all

import serial
def read_Serial():
	ser = serial.Serial('/dev/ttyACM0', 38400)
	ser.flushInput()
	ser_bytes = ser.readline()
	decoded_bytes = str(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
	print(decoded_bytes)
	
read_Serial()

Ideally the loop would be something like:
  • listening for serial values
  • captures serial values when sent, and stores as a list
  • begins listening again for next batch of serial values
  • captures serial values when sent, overwrites previous list
Thanks in advance for any help!

User avatar
scruss
Posts: 3212
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: reading batch of serial values from USB and storing as a list

Wed Mar 13, 2019 11:33 am

Is your ser_bytes[0:len(ser_bytes)-2] code to remove the \r\n at the end of the line? If so, .strip() will do the same in a more obvious manner. Also, some of the typical line noise from an Arduino can't be reliably represented in UTF-8, so I use .decode('utf-8', errors='replace') to replace ‘bad’ characters with ones that can be safely ignored.

Your problem is that you are opening and closing the serial port. Every time you do that, your Arduino resets (it's a design decision: I'm sure it made sense at the time) so all the previous data are lost. Best to open the serial port once, and read from it as needed. You also need a timeout value specified in the serial open statement, or readline will wait forever. timeout=1 seems to be okay for me unless I'm deliberately playing with buffering.

Serial is asynchronous, so you just have to wait until something shows up. Maybe also put a couple of header lines output in the Arduino setup clause that you can read and ignore to avoid the startup line noise that almost always happens. Some Arduinos (Leonardo, Micro) can be fiddly about data buffering, but you're probably not using them.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.
Pronouns: he/him

mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

Re: reading batch of serial values from USB and storing as a list

Wed Mar 13, 2019 11:03 pm

Thanks for the reply, I appreciate the info! I will try your suggestions.

Return to “Python”