【问题标题】:How to select a number received from the serial port如何选择从串口接收的号码
【发布时间】:2018-03-04 04:59:45
【问题描述】:

我通过串行端口从运动传感器设备接收数据。 数据以行格式并以字母开头,如下所示:

所有数字用逗号分隔,每行末尾有'\r'字符。

我有兴趣从以“S”字符开头的行中获取数字,逗号之间总是有 11 个数字。例如,我想在变量(数组或列表)中保存第二个“S”行。

我一直在尝试这个简单的 Python 脚本:

import serial
ser = serial.Serial('/dev/tty.usbserial-00002014', 115200)
try:
    ser.isOpen()
    #ser.flushInput()
    print('serial is open')
except:
    print('error')
    exit()

if (ser.isOpen()):
    try:
        while(1):
            print(ser.read())
    except Exception:
        print('error')
else:
    print('Cannot open serial port')

结果是不断打印端口接收到的字符

b'S'
b','
b'0'
b','
b'0'
b','
b'0'
b','
b'-'
b'2'
b'8'
b','
b'2'
b'1'
b','
b'9'
b'8'
b'5'
b','
b'-'
b'1'
b'5'
b'3'
b','
b'3'
b'0'
b'5'
b','
b'-'
b'1'
b'0'
b'7'
b','
b'1'
b'2'
b'1'
b','
b'9'
b'0'
b'\r'
b'Q'

而且似乎很难得到我需要的数字。

有什么方法可以得到第二个“S”行吗?

问候

【问题讨论】:

    标签: python serial-port pyserial


    【解决方案1】:

    您是否尝试过阅读文档? 您可以使用readline 读取完整的行,然后将其拆分为单词。像这样的:

    numbers = []
    with serial.Serial('/dev/tty.usbserial-00002014', 19200, timeout=10) as ser:
        line = ser.readline()
        if line.startswith('S,'):
            number = int(line.split(',')[1])
            numbers.append(number)
    

    【讨论】:

    • 感谢您的回答。我试过readline()import io ser_io = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1), newline = '\r', line_buffering = True) 更改EOL,现在脚本得到整行,用你的代码我可以得到第一个数字。但是,numbers 几秒钟后里面的数字太多了。你知道如何保存最近收到的 200 个号码吗?我想绘制它们的图并计算 fft。
    • @pablo 可能值得一看 deque
    猜你喜欢
    • 2011-08-18
    • 2015-08-04
    • 2022-01-22
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多