I am a new to Python.
What I want to do is that playing different videos depends on distance using Ultrasonic sensor.
For example,
if the distance <= 20, play movie1.
if the distance > 20, play movie2.
It works, and that seems quite simple.
But I have a problem. The video is not changed instantly. After playing it completely, it responds again.
So even though the distance is <20, the movie1 is still going. After finishing it, movie2 appears.
I want to change the video as soon as the distance is changed, not waiting until the video is finished. Maybe I need some code to kill OMXPlayer? I have no idea.
Below is my code.
#Libraries
import RPi.GPIO as GPIO
import time, sys, os
from subprocess import Popen
import subprocess as sp
distance = 400
zone = 1
# to know if omxplayer is playing (= None) or not
#GPIO Mode (BOARD / BCM)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#set GPIO Pins
GPIO_TRIGGER = 18
GPIO_ECHO = 24
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
# Videos definitions
movie1 = ('/home/pi/Videos/test1.mp4')
movie2 = ('/home/pi/Videos/test2.mp4')
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)
if (distance() <= 20):
zone = 1
elif (distance() > 20):
zone = 2
if (zone == 1):
Popen(['omxplayer', '-b', movie1])
if (zone == 2):
Popen(['omxplayer', '-b', movie2])
except KeyboardInterrupt:
# exits when you press CTRL+C
os.system('killall omxplayer.bin')
GPIO.cleanup()