树梅派学习 19. 超声波传感器实验

版权声明:(谢厂节的博客)博主文章绝大部分非原创,转载望留链接。 https://blog.csdn.net/xundh/article/details/82119935

超声波传感器:

这里写图片描述

接线图:

这里写图片描述

程序:

#!/usr/bin/env python

import RPi.GPIO as GPIO
import time

TRIG = 11
ECHO = 12

def setup():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(TRIG, GPIO.OUT)
    GPIO.setup(ECHO, GPIO.IN)

def distance():
    GPIO.output(TRIG, 0)
    time.sleep(0.000002)

    GPIO.output(TRIG, 1)
    time.sleep(0.00001)
    GPIO.output(TRIG, 0)


    while GPIO.input(ECHO) == 0:
        a = 0
    time1 = time.time()
    while GPIO.input(ECHO) == 1:
        a = 1
    time2 = time.time()

    during = time2 - time1
    return during * 340 / 2 * 100

def loop():
    while True:
        dis = distance()
        print dis, 'cm'
        print ''
        time.sleep(0.3)

def destroy():
    GPIO.cleanup()

if __name__ == "__main__":
    setup()
    try:
        loop()
    except KeyboardInterrupt:
        destroy()

原理:

参见:
http://baijiahao.baidu.com/s?id=1582213763119045367&wfr=spider&for=pc

实体图:

这里写图片描述

运行效果

这里写图片描述

猜你喜欢

转载自blog.csdn.net/xundh/article/details/82119935