从接近传感器获取特定数据(距离)

2024-06-28 15:17:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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个

Code and output


Tags: 数据距离forlineserialserprintx00