User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

Trouble using serial port data -- Python IF

Fri Apr 17, 2020 1:46 pm

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)

gordon77
Posts: 5040
Joined: Sun Aug 05, 2012 3:12 pm

Re: Trouble using serial port data -- Python IF

Fri Apr 17, 2020 2:06 pm

what if you try

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

presumably you are receiving strings not integers

User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

Re: Trouble using serial port data -- Python IF

Fri Apr 17, 2020 2:22 pm

That was it! Thanks Gordon!

Return to “Python”