Sid
Published © GPL3+

Trigger Google Assistant on Pi Using Ultrasonic HC-SR04

Trigger Google Assistant SDK on RPi using ultrasonic sensor HC-SR04 on Raspberry Pi.

IntermediateShowcase (no instructions)30 minutes4,194
Trigger Google Assistant on Pi Using Ultrasonic HC-SR04

Things used in this project

Story

Read more

Schematics

Wiring diagram

Wire the HC-SR04 to Pi as shown

Code

HCSR04.py

Python
Script for using HC-SR04 as trigger
#Libraries
import RPi.GPIO as GPIO
import time
 
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
 
#set GPIO Pins
GPIO_TRIGGER = 21
GPIO_ECHO = 20
GPIO_GASSIST =17 
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
GPIO.setup(GPIO_GASSIST, GPIO.OUT)
 
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()
            if distance()<10:
                print ("Trigger Detected at %.1f cm" % dist)
                GPIO.output(GPIO_GASSIST, False)
                time.sleep(0.3)
                GPIO.output(GPIO_GASSIST, True)
            else:
                print ("Waiting For Trigger")
                time.sleep(1)
 
        # Reset by pressing CTRL + C
    except KeyboardInterrupt:
        print("Measurement stopped by User")

Credits

Sid

Sid

22 projects • 178 followers

Comments