Page 1 of 1

Trouble using serial port data -- Python IF

Posted: Fri Apr 17, 2020 1:46 pm
by richiepp
Hey All,
I'm working on getting my Arduino and Raspberry Pi to talk to each other over serial. I've got the basics figured out but I'm having trouble using the data the Pi receives from the Arduino. I've started modifying a bit of python to include a couple of IF statements but they don't seem to be working.

I suspect it has something to do with the data type. I think what's happening is when I read from the serial port it's reading as a string but what I need is an int. But I don't know

Code: Select all

line = ser.readline().decode('utf-8').rstrip()
Here's the code in full. It reads the serial port but the IF statements do not respond. What's missing?

Code: Select all

#!/usr/bin/env python3
import serial
import time

line = 0

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyS0', 115200, timeout=1)
    ser.flush()
    while True:
#       ser.write(b"Hello from Raspberry Pi!\n")
       line = ser.readline().decode('utf-8').rstrip()
       print(line)
       if line == 1: print('NIGHT MODE ON')
       if line == 0: print('NIGHT MODE OFF')
       time.sleep(1)

Re: Trouble using serial port data -- Python IF

Posted: Fri Apr 17, 2020 2:06 pm
by gordon77
what if you try

if line == '1': print('NIGHT MODE ON')

presumably you are receiving strings not integers

Re: Trouble using serial port data -- Python IF

Posted: Fri Apr 17, 2020 2:22 pm
by richiepp
That was it! Thanks Gordon!