0

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!

3
  • If you want to get help here, you need to do better than "it did not work." Tell us what happened, and what you expected to happen or wanted to happen. Commented Mar 9 at 4:02
  • If you want to execute a function when hello is returned, then just replace the print("Hi") line with the function call. And in the if condition, I think you meant "hello" in quotes. Commented Mar 9 at 4:08
  • You might want to try to find a different module to handle your serial port because the documentation for pyserial 3.5 is no longer applicable to Python 3.13.2 Commented Mar 9 at 9:16

2 Answers 2

2

ser.is_open == hello is wrong. It checks if the serial port is open, not if the message is "hello".

if valueInString.strip() == "hello":

Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.