How would I write the code so if I recieve 'hello' it runs a function?
import serial
ser = serial.Serial(port='/dev/tty.usbmodem11201',baudrate=9600)
while True:
value= ser.readline()
valueInString=str(value, 'UTF-8')
print(valueInString)
if ser.is_open == hello:
print("Hi")
This is what I saw to do but it did not work. How would I get it to work? Thanks!
How would I write the code so if I recieve 'hello' it runs a function?
import serial
ser = serial.Serial(port='/dev/tty.usbmodem11201',baudrate=9600)
while True:
value= ser.readline()
valueInString=str(value, 'UTF-8')
print(valueInString)
if ser.is_open == hello:
print("Hi")
This is what I saw to do but it did not work. How would I get it to work? Thanks!
Share Improve this question asked Mar 9 at 3:53 Lukas SandersLukas Sanders 31 bronze badge 3 |2 Answers
Reset to default 2ser.is_open == hello
is wrong. It checks if the serial port is open, not if the message is "hello"
.
if valueInString.strip() == "hello":
You need to refine your "if" statement. It should be:
if ser.is_open == True:
if valueInString == "hello":
print("Hi")
ser.is_open
is simply a Boolean value for whether the serial communication is open. You want to compare valueInString
for "hello"
Also, consider adding .strip()
to your valueInString
definition to remove white space, like so:
valueInString=str(value, 'UTF-8').strip()
print("Hi")
line with the function call. And in the if condition, I think you meant"hello"
in quotes. – Vansh Patel Commented Mar 9 at 4:08