超声波

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

import RPi.GPIO as GPIO
import time

Trig = 17
Echo = 27
#设置编码模式
GPIO.setmode(GPIO.BCM)
GPIO.setup(Trig, GPIO.OUT, initial = GPIO.LOW)
GPIO.setup(Echo, GPIO.IN)

time.sleep(2)
try:
while True:
#先给它一个高电频
GPIO.output(Trig, GPIO.HIGH);
time.sleep(0.001);
#再给它一个低电频
GPIO.output(Trig, GPIO.LOW);
while GPIO.input(Echo) == 0:
pass;
t1 = time.time();
while GPIO.input(Echo) == 1:
pass;
t2 = time.time();
len = (t2-t1)*340/2;
print 'distance: %.3f m'% len;
time.sleep(0.5);
except:
pass;

GPIO.cleanup();

posted @ 2019-06-02 19:49  countryboy666  阅读(116)  评论(0编辑  收藏  举报