[英]How to send Hex Data to Raspberry Pi Serial Port using Python
[英]how to read sensor data from serial port using python and raspberry pi 2
我正在尝试从超声波距离传感器读取串行数据。 我得到的唯一输出是像这样的白色正方形:
我有一个来自ebay的rapiberry pi 2和一个ME007-ULS v1超声波传感器,我从手册中得到的:
当触发引脚“ 2.Trigger”处于下降沿且低电平保持在0.1至10ms时,将触发控制器工作一次,然后输出引脚“ 3.TX / PWM”将输出3.3V帧TTL级串行数据
传感器的输出帧格式为:
这是我编写的代码:
import RPi.GPIO as GPIO
import time
from serial import Serial
#GPIO mode
GPIO.setmode(GPIO.BCM)
#assign GPIO pins
GPIO_TRIGGER = 18
#direction of GPIO-Pins (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
def uss_funct():
ser = Serial('/dev/ttyAMA0', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=3)
# set trigger HIGH, sensor is waiting for falling edge
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
test_output = ser.read()
ser.close()
#clean up GPIO pins
GPIO.cleanup()
print (test_output)
if __name__ == '__main__':
uss_funct()
我认为我的接线正确,但以防万一-这是我为传感器接线的方式:
超声波传感器具有5个引脚:
默认情况下,Serial.read()仅读取一个字节。 您需要阅读6:
# read from rx
test_output = ser.read(size=6)
然后看看您有什么尝试:
print(repr(test_output))
通过创建一个空列表,然后附加任何输出ser.read()
,我可以解决问题并摆脱白色方块:
data_output = []
def uss_function():
(...)
#read from rx
data_output.append(ser.read(6))
ser.close()
这给了我这样的输出: ['\\x00\\xff\\x01V\\x00\\xcc']
仍然不完全是我应该得到的读数,但它越来越近了。 我认为这与来自串行端口的错误读数有关,一旦我弄清了所有答案,我将更新此答案。 我认为这是一个新问题的主题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.