1. 程式人生 > >樹梅派學習 19. 超聲波感測器實驗

樹梅派學習 19. 超聲波感測器實驗

超聲波感測器:

這裡寫圖片描述

接線圖:

這裡寫圖片描述

程式:

#!/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()

原理:

實體圖:

這裡寫圖片描述

執行效果

這裡寫圖片描述