1

So i set up my rpi zero w to comunicate at 11500 serial with an arduino... the arduino sends over serial lines such as "~1 11443". My idea is that the ~ character tells the pi when to look for data, and the following number will tell the pi what kindof data is after the space. I wrote some code but i keep getting the error:

Traceback (most recent call last):
  File "serial2rpi.py", line 11, in <module>
    key = int(line[0])
IndexError: list index out of range

My code is this:


import serial

# check this below
serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5)

while True:
    line = serialport.readlines(None)

    # good data
    if  '1' or '2' or '3' or '4' or '5'  in  line:
        key = int(line[0])
    else:
        print("nope")

    if line[0] == '~':
        if key == 1:
            lat = int(line.replace('~1 ', ''))
            print(lat)

        if key == 2:
            lng = int(line.replace('~2 ', ''))
            print(lng)

        if key == 3:
            alt = int(line.replace('~3 ', ''))
            print(alt)

        if key == 4:
            sat = int(line.replace('~4 ', ''))
            print(sat)

        if key == 5:
            crs = int(line.replace('~5 ', ''))
            print(crs)
    else:
        print("oops:")

If anyone knows what error(s) i have made it would be greatly appreciated.

1

So it turns out I had a lot of errors. This is what I ended up using. Aside from trying to check strings that didn't exist the string manipulation formatting was just wrong. I switched to just trimming the front and back of the string which contained'\r\n' and '~1 '

import serial

with serial.Serial('/dev/ttyAMA0', 115200, timeout=1) as ser:
 while True:
  line = ser.readline()
  max_char = len(line)
  a = 3
  # read a '\n' terminated line
  if len(line) > 0:
   if chr(line[0]) == '~':
    key = int(chr(line[1]))
    if key == 1:
     lat = line[a:max_char-2]
     print("lat:")
     print(lat.decode('utf-8'))
    if key == 2:
     lng = line[a:max_char-2]
     print("lng:")
     print(lng.decode('utf-8'))
    if key == 3:
     alt = line[a:max_char-2]
     print("alt:")
     print(alt.decode('utf-8'))
    if key == 4:
     sat = line[a:max_char-2]
     print("sat:")
     print(sat.decode('utf-8'))
    if key == 5:
     crs = line[a:max_char-2]
     print("Crs:")
     print(crs.decode('utf-8'))
   else:
    print("oops:")

| improve this answer | |
0

Why readlines(None)? That does not appear to be a defined usage. I would get rid of None.

If no lines were returned then lines will be empty. That's the error message you are getting, you are trying to index an empty list.

You need to add a test after the readlines call, perhaps something like

if len(lines) > 0:
   # process line
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.