我已将超声波距离传感器连接到树莓派2.当触发时,传感器应通过串口发回以下6个参数:
- 帧头:0xFF
- 数据1:0x07
- 数据2:0xD0
- 数据3:0x01
- 数据4:0x19
- 校验和:0xF0
醇>
然而,当我尝试阅读输出时,我会得到类似这样的内容:['\x00\xff\x01V\x00\xce']
以下是有关传感器串行帧格式的一些信息:
校验和的计算如下:
SUM =( Frame header + Data_H+ Data_L+ Temp_H+ Temp_L)&0x00FF
注意:校验和仅保留8位的低累加值;
这是我到目前为止编写的代码:
import RPi.GPIO as GPIO
import time
from serial import Serial
GPIO.setmode(GPIO.BCM) #GPIO mode
GPIO_TRIGGER = 18 #assign GPIO pins
GPIO.setup(GPIO_TRIGGER, GPIO.OUT) #direction of GPIO-Pins (IN / OUT)
data_output=[]
def uss_funct():
ser = Serial('/dev/ttyAMA0', baudrate=9600, bytesize=8, parity='N', stopbits=1)
# set trigger HIGH, sensor is waiting for falling edge
time.sleep(0.01000)
GPIO.output(GPIO_TRIGGER, True)
# set trigger LOW after 10ms -> Falling Edge
time.sleep(0.01000)
GPIO.output(GPIO_TRIGGER, False)
# set trigger back HIGH after 2ms, as LOW is supposed to be between 0.1-10ms
time.sleep(0.00200)
GPIO.output(GPIO_TRIGGER, True)
#read from rx
data_output.append(ser.read(6))
ser.close()
#clean up GPIO pins
GPIO.cleanup()
print (data_output)
if __name__ == '__main__':
uss_funct()
答案 0 :(得分:0)
校验和可以很容易地计算,但问题是数据不同步。第一个字节需要是0xff。这里有一些代码可以找到数据的前面(0xff),然后计算温度,距离和校验和:
data_output = ser.read(6)
# the first byte should be 0xff
if len(data_output) == 6 and \
data_output[0] != 0xff and 0xff in data_output:
# find where 0xff is in the data stream
still_needed = data_output.index(0xff)
# read more data, we are out of sync
data_output = data_output[still_needed:] + ser.read(still_needed)
# must get 6 bytes, and the first needs to be 0xff
if len(data_output) != 6 or data_output[0] != 0xff:
good_data = False
else:
# verify the checksum
good_data = (0 == (sum(data_output) & 0xff))
if good_data:
distance = data_output[1] * 256 + data_output[2]
temperature = data_output[3] * 256 + data_output[4]
确保使用超时初始化串行对象:
from serial import Serial
ser = Serial(..., timeout=1)
我没办法测试这个,所以买家要小心。