树莓派-超声波-HC_SR04

1.Raspberry-Pi-GPIO-Layout-Revision-2
连线:

Name 树莓派Pin
VCC 2
TRIG 16
ECHO 18
GND 6

2.运行下边的程序:

#!/usr/bin/python
#coding: utf-8

import RPi.GPIO as GPIO
import time
import sys

def my_callback(channel):
    global isExit
    global last_dis
    global last_time
    e= 0
    s= time.time()
    while True:
        x = GPIO.input(GPIO_PORT_ECHO)
        if x==GPIO.LOW:
            e= time.time()
            break
    dis = (e-s)*34029/2
    speed = (last_dis-dis)/(e-last_time)
    last_time = e
    last_dis = dis

    print 'distance:%d cm, speed:%d cm/s\r' % (dis,speed),
    sys.stdout.flush()
    isExit = True

def test_distance():
    GPIO.output(GPIO_PORT_TRIG,GPIO.HIGH)
    time.sleep(0.1)
    GPIO.output(GPIO_PORT_TRIG, GPIO.LOW)

if __name__ == '__main__':
    # config
    GPIO_PORT_TRIG = 23
    GPIO_PORT_ECHO = 24

    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(GPIO_PORT_TRIG,GPIO.OUT)
    GPIO.setup(GPIO_PORT_ECHO,GPIO.IN)
    last_time = time.time()
    last_dis = 0

    GPIO.add_event_detect(GPIO_PORT_ECHO, GPIO.RISING, callback=my_callback)
    while True:
        isExit = False
        test_distance()
        while not isExit:
            time.sleep(0.05)
        time.sleep(0.1)

Comments are closed.