Categories

Using Ultrasonic (HC SR-04) with Raspberry Pi

In this tutorial we will be Using Ultrasonic Sensor (SR-04) with Raspberry Pi –

Step 1 – Connections

  • Here we will be using GPIO24 as Trigger pin and GPIO25 as Echo pin.
  • For this, connections will be as shown –

  • We have to connect echo pin in a Voltage Divider, made by 330Ω and 470Ω as Shown.

Step 2 – Working on Code –

  • Create a new file in IDLE and write the code as given
  • The Code for the Following will be –
#This code is Written by Robu.in
import RPi.GPIO as GPIO
import time

#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

#set GPIO Pins
GPIO_TRIGGER = 24
GPIO_ECHO = 25

#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()
  • Now save this as python file as ultrasonic.py
  • Open terminal and type command sudo python ultrasonic.py and press Enter.
  • Now you will get Realtime reading by Ultrasonic Sensor on the terminal.

  • You can press Ctrl+C any time to stop the program.

Hope that you would have liked it. For any Querry, you can leave a comment below : – )


 

 

 

About the Author

abhishek@robu.in

Abhishek Thakur, Embedded Systems Enthusiast

Related Post

Submit a Review

Display Name

Email

Title

Message