This is quite a specific query so please bear with me.
I have 14 ultrasonic sensors hooked to an Arduino sending live readings to the serial monitor (or Pi when I plug it in) . The readings are sent as follows, with a new line between every 2 digits (except Z).
Z 62 61 64 63 64 67 98 70 69 71 90 XX 75 XX
These measurements are in cm. "XX" implies the reading is out of the two digit range. Z has been assigned as a starting point as the pi reads the sensors very fast and repetitively, to the point of 80 readings in a second or so. So ser.readline() gives multiple samples of the same sensors
When python reads the readings in ser.readline() it does not have a starting point. It may start at 70, XX or Z. I want to assign it into an accessible list so that:
array [0] = Z (always)
array [1] = 62 (first two digits)
array [2] = 61 (second two digits)
..
array [14] = XX (fourteenth two digits)
This is my code which unfortunately doesn't work as list is out of range:
import serial
ser = serial.Serial('/dev/ttyACM0',115200)
print ("Start")
overallcount=1 #initialise 2 counters
arraycount =1
array = [] #initialise 2 lists
line = []
while True:
while overallcount<30: #read 30 random readings from Arduino
ser.readline()
print(str(overallcount)) #print reading number
while arraycount<15: #Number of readings to fill the array to be made
for line in ser.readline():
if line == 'Z': #If element in ser.readline is "Z"
array[0] == line #Assign first list element as Z (starting point)
arraycount=arraycount+1 #Iterate through until 14 sensors are read
arraycount=1 #reset counter
overallcount=overallcount+1 #Iterate through 30 random Arduino readings
overallcount=1 #iterate random counter
If you could please tell me what I'm doing wrong, or if there is a better method for this I'd really really appreciate it!
Thank you
How about this? Note that your checks overallcount<30 and arraycount<15 should really be overallcount<=30 and arraycount<=15.
import serial
ser = serial.Serial('/dev/ttyACM0',115200)
readings = [] # Array to store arrays of readings
reading_id = 1 # Id of current reading
random_lines_expected = 30 # NUmber of random lines
num_sensors = 14 # Number of sensors
def read_random():
for _ in range(random_lines_expected):
ser.readline()
read_random() # Read initial random lines
while True:
print "Reading #", reading_id
reading = [] # Initialize an array to collect new reading
while ser.readline().strip() != 'Z': # Keep reading lines until we find 'Z'
pass
reading.append('Z') # Add Z to reading array
for _ in range(num_sensors): # For 14 sensors...
reading.append(ser.readline().strip()) # Add their value into array
readings.append(reading) # Add current reading to the array or readings
reading_id += 1 # Increment reading ID
#read_random() #Uncomment this if random follows each series of readings