Multiple if statements in infinite loop

Hi all, I’m new here and a Python newbie also.
My first Python script attempt to control communication between an RPi4 and an Arduino Nano.

import time, serial, subprocess, signal, sys
from picamera2 import Picamera2, Preview
from picamera2.controls import Controls

def sigint_handler(signal, frame):
signal.signal(signal.SIGINT, sigint_handler)

ser = serial.Serial("/dev/ttyS0",19200)
ser.flush() # Get rid of garbage/incomplete data

picam2 = Picamera2()
config = picam2.create_preview_configuration()


print("\nWaiting for Arduino commands")
while True:
    if ser.in_waiting > 0:
        line = ser.readline().decode('utf-8').rstrip()
        linelist = line.split(",")
        item0 = int(linelist[0])
        if (item0 == 1):
            picam2.start_preview(Preview.QTGL, x=10, y=200, width=800, height=600)
        elif (item0 == 2):

When I send ‘1,0,0,’, the start_preview command is correctly executed but the ‘2,0,0,’ condition is never catched. Sorry but I’m really new to Python …
Thanks in advance

On the face of it, it seems that you’re assuming that the linelist is only ever going to contain either 1,0,0 or 2,0,0, but are you sure about that? Is it not possible that linelist could contain both 1,0,0 and 2,0,0, in which case item0 would still index to the first element.

An easy check would be to put print(*linelist) in your code, just above where you have print(item0)

To add: if your linelist needs to be integer values from the string object line (which seems likely, from what I can see in your code), I would construct that object like this:

linelist = [int(n) for n in line.split(",")]

Sorry, in fact I actually found an error in my Arduino code. Forget my first post. I’ll delete it. My apologies …

No worries, but leave it as is: maybe someone else will be able to learn something from the thread.

1 Like