Raspberry Pi - HC-SR04 (초음파센서)로 거리측정하기

OS/Raspberry Pi 2017.08.19 12:26 Posted by 파란크리스마스

출처 : Using a Raspberry Pi distance sensor (ultrasonic sensor HC-SR04)

배선

Python 소스

<#Libraries
import RPi.GPIO as GPIO
import time
 
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
 
#set GPIO Pins
GPIO_TRIGGER = 23
GPIO_ECHO = 24
 
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
 
def distance():
    # set Trigger to HIGH
    GPIO.output(GPIO_TRIGGER, True)
 
    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)
 
    StartTime = time.time()
    StopTime = time.time()
 
    # save StartTime
    while GPIO.input(GPIO_ECHO) == 0:
        StartTime = time.time()
 
    # save time of arrival
    while GPIO.input(GPIO_ECHO) == 1:
        StopTime = time.time()
 
    # time difference between start and arrival
    TimeElapsed = StopTime - StartTime
    # multiply with the sonic speed (34300 cm/s)
    # and divide by 2, because there and back
    distance = (TimeElapsed * 34300) / 2
 
    return distance
 
if __name__ == '__main__':
    try:
        while True:
            dist = distance()
            print ("Measured Distance = %.1f cm" % dist)
            time.sleep(1)
 
        # Reset by pressing CTRL + C
    except KeyboardInterrupt:
        print("Measurement stopped by User")
        GPIO.cleanup()

실행

$ python3 ultrasonic_distance.py 
Measured Distance = 191.9 cm
Measured Distance = 9.2 cm
Measured Distance = 10.5 cm
Measured Distance = 205.9 cm
Measured Distance = 25.4 cm
Measured Distance = 29.9 cm
Measured Distance = 17.1 cm
Measured Distance = 22.2 cm
Measured Distance = 10.2 cm
^CMeasurement stopped by User
저작자 표시
신고


 

티스토리 툴바