首页 > 解决方案 > 从接近传感器(距离)获取特定数据

问题描述

我正在使用 Python 从接近传感器读取串行数据,我只想获取距离并摆脱它产生的所有其他数据。它最初输出的数据是某种 Unicode、十六进制形式。例如:

b'\xfc\x95\x92\x82\x00\x00F\x00\x1f\x04\xef\xff\xd5\x95\x00\n'

是初始输出。当放入 for 循环以访问该行中的数据时,它会给我以下数字。

252 149 146 130 0 0 70 0 31 4 239 255 213

到目前为止我写的代码是:

import serial
ser = serial.Serial(port = "COM5", baudrate = 230400,  bytesize = 
serial.EIGHTBITS, parity= serial.PARITY_NONE, timeout = 1)
try:
    ser.isOpen()
    print("serial Port is open")
 except:
    print("error")
    exit()
if (ser.isOpen()):
    try:

         while True:

            line = ser.readline()

            print (line)

            for data in line:
                print (data)                 
    except Exception:
                print( "Keyboard Interrupt")
else:
            print("cannnot open port")

在上面提供的输出中,“255”是新行的开始,距离测量始终位于向下 9 列,然后每当您看到“255”时将继续重新开始。总而言之,“255”每 16 次出现一次,然后将开始新的一行数据。为了获得距离,我需要能够在 255 发生后访问第九个数据项。

这是一个较长的输出块,以提供更好的示例:

"b'\xfc\xc6\x92O\x00\x00F\x00\x1f\x04\xf1\xff\xd5d\x00\n'

252 198 146 79 0 0 70 0 31 4 241 255 213 100 0 10"

b'\xfc\xc1\x92P\x00\x00I\x00 \x04\xf1\xff\xd5d\x00\n'

252 193 146 80 0 0 73 0 32 4 241 255 213 100 0 10

b'\xfc\xc1\x92Q\x00\x00I\x00\x1f\x04\xf1\xff\xd5a\x00\n'

252 193 146 81 0 0 73 0 31 4 241 255 213 97 0 10

代码和输出

标签: pythonpython-3.xpyserial

解决方案


推荐阅读