最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to create an if statement with serial data? - Stack Overflow

programmeradmin2浏览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!

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
  • 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. – Paul Cornelius 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. – Vansh Patel 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 – Adon Bilivit Commented Mar 9 at 9:16
Add a comment  | 

2 Answers 2

Reset to default 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":

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()
发布评论

评论列表(0)

  1. 暂无评论