iRIDE Code
unknown
plain_text
a year ago
2.9 kB
14
Indexable
import RPi.GPIO as GPIO
import time
import sys
import threading
import speech_recognition as sr
from gpiozero import Robot
robot = Robot(left=(7, 8), right=(9, 10))
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
TRIG_FRONT = 4
ECHO_FRONT = 27
def stop():
robot.stop()
def forward():
robot.forward()
def backward():
robot.backward()
def turn_left():
robot.left()
def turn_right():
robot.right()
def get_distance(trig, echo):
GPIO.setup(trig, GPIO.OUT)
GPIO.setup(echo, GPIO.IN)
GPIO.output(trig, GPIO.LOW)
time.sleep(0.02)
GPIO.output(trig, GPIO.HIGH)
time.sleep(0.00001)
GPIO.output(trig, GPIO.LOW)
start_time, stop_time = None, None
timeout = time.time() + 0.02
while GPIO.input(echo) == 0 and time.time() < timeout:
start_time = time.time()
while GPIO.input(echo) == 1 and time.time() < timeout:
stop_time = time.time()
if start_time and stop_time:
elapsed = stop_time - start_time
distance = (elapsed * 34300) / 2
return distance if 2 <= distance <= 400 else None
return None
def listen_for_command():
recognizer = sr.Recognizer()
mic = sr.Microphone()
try:
with mic as source:
print("Listening for commands...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
command = recognizer.recognize_google(audio, language="en-US").lower()
print(f"Command received: {command}")
return command
except sr.UnknownValueError:
print("Command not understood.")
return None
except sr.RequestError:
print("Voice recognition service error.")
return None
def listen_for_voice_command():
while True:
command = listen_for_command()
if command:
if "stop" in command:
stop()
print("Stopped.")
elif "start" in command:
forward()
print("Moving forward.")
elif "left" in command:
turn_left()
print("Turning left.")
elif "right" in command:
turn_right()
print("Turning right.")
def important():
try:
while True:
distance = get_distance(TRIG_FRONT, ECHO_FRONT)
print(f"Distance: {distance} cm")
if distance is not None and distance < 20:
stop()
print("Obstacle detected. Avoiding...")
turn_right()
time.sleep(0.75)
stop()
else:
forward()
print("Moving forward.")
except KeyboardInterrupt:
print("Stopping robot.")
GPIO.cleanup()
if __name__ == "__main__":
voice_thread = threading.Thread(target=listen_for_voice_command, daemon=True)
voice_thread.start()
important()Editor is loading...
Leave a Comment