Raspberry Pi‎ > ‎SANKI Device‎ > ‎

Ultrasonic


Ultrasonic  

Ultrasonic Sensor (Distance)

Hardware

 
 
 


Pin Connect

 Raspberry Pi Ultrasonic
+5V 5V 
 GND GND 
Pin 23 OUTPUT
PIN 24 INPUT

Examples

          This example is to display a distance in CM. but you can change to any unit by calculation.
  1. 
    import time
    import RPi.GPIO as GPIO
    
    
    GPIO.setmode(GPIO.BCM)
    
    # Define GPIO to use on Pi
    GPIO_TRIGGER = 23
    GPIO_ECHO = 24
    
    print "Ultrasonic Measurement"
    
    # Set pins as output and input
    GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
    GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo
        
    def reading():
        # Set trigger to False (Low)
        GPIO.output(GPIO_TRIGGER, False)
    
        # Allow module to settle
        time.sleep(0.5)
    
        # Send 10us pulse to trigger
        GPIO.output(GPIO_TRIGGER, True)
        time.sleep(0.00001)
        GPIO.output(GPIO_TRIGGER, False)
        start = time.time()
        while GPIO.input(GPIO_ECHO)==0:
          start = time.time()
    
        while GPIO.input(GPIO_ECHO)==1:
          stop = time.time()
    
        # Calculate pulse length
        elapsed = stop-start
    
        # Distance pulse travelled in that time is time
        # multiplied by the speed of sound (cm/s)
        distance = elapsed * 50000
    
        # That was the distance there and back so halve the value
        distance = distance / 3
      
        return distance
        
    while True: 
        print "Distance : %.1f cm" % reading()
        time.sleep(1);
    
    # Reset GPIO settings
    GPIO.cleanup()

Reference