Untitled
unknown
plain_text
4 months ago
3.4 kB
5
Indexable
import RPi.GPIO as GPIO import time import speech_recognition as sr GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) IN1 = 5 IN2 = 6 IN3 = 23 IN4 = 24 ENA = 12 ENB = 13 TRIG_FRONT = 18 ECHO_FRONT = 27 LINE_SENSOR = 17 GPIO.setup([IN1, IN2, IN3, IN4, ENA, ENB], GPIO.OUT) GPIO.setup(TRIG_FRONT, GPIO.OUT) GPIO.setup(ECHO_FRONT, GPIO.IN) GPIO.setup(LINE_SENSOR, GPIO.IN) pwm_left = GPIO.PWM(ENA, 100) pwm_right = GPIO.PWM(ENB, 100) pwm_left.start(0) pwm_right.start(0) def stop(): GPIO.output([IN1, IN2, IN3, IN4], GPIO.LOW) pwm_left.ChangeDutyCycle(0) pwm_right.ChangeDutyCycle(0) def forward(speed=50): GPIO.output(IN1, GPIO.HIGH) GPIO.output(IN2, GPIO.LOW) GPIO.output(IN3, GPIO.HIGH) GPIO.output(IN4, GPIO.LOW) pwm_left.ChangeDutyCycle(speed) pwm_right.ChangeDutyCycle(speed) def backward(speed=50): GPIO.output(IN1, GPIO.LOW) GPIO.output(IN2, GPIO.HIGH) GPIO.output(IN3, GPIO.LOW) GPIO.output(IN4, GPIO.HIGH) pwm_left.ChangeDutyCycle(speed) pwm_right.ChangeDutyCycle(speed) def turn_left(speed=50): GPIO.output(IN1, GPIO.LOW) GPIO.output(IN2, GPIO.HIGH) GPIO.output(IN3, GPIO.HIGH) GPIO.output(IN4, GPIO.LOW) pwm_left.ChangeDutyCycle(speed / 2) pwm_right.ChangeDutyCycle(speed) def turn_right(speed=50): GPIO.output(IN1, GPIO.HIGH) GPIO.output(IN2, GPIO.LOW) GPIO.output(IN3, GPIO.LOW) GPIO.output(IN4, GPIO.HIGH) pwm_left.ChangeDutyCycle(speed) pwm_right.ChangeDutyCycle(speed / 2) def get_distance(trig, echo): GPIO.output(trig, GPIO.LOW) time.sleep(0.02) GPIO.output(trig, GPIO.HIGH) time.sleep(0.00001) GPIO.output(trig, GPIO.LOW) timeout = time.time() + 0.02 while GPIO.input(echo) == 0 and time.time() < timeout: start_time = time.time() timeout = time.time() + 0.02 while GPIO.input(echo) == 1 and time.time() < timeout: stop_time = time.time() elapsed = stop_time - start_time distance = (elapsed * 34300) / 2 if distance > 400 or distance <= 2: return None return distance def follow_line(): if GPIO.input(LINE_SENSOR) == 1: forward(50) else: turn_left(30) def listen_for_command(): recognizer = sr.Recognizer() mic = sr.Microphone() try: with mic as source: recognizer.adjust_for_ambient_noise(source) audio = recognizer.listen(source) command = recognizer.recognize_google(audio, language="en-US").lower() return command except sr.UnknownValueError: return None except sr.RequestError: return None def main(): try: while True: distance = get_distance(TRIG_FRONT, ECHO_FRONT) if distance and distance < 20: stop() turn_right(50) time.sleep(0.5) forward(50) else: follow_line() command = listen_for_command() if command: if "stop" in command: stop() elif "start" in command: forward(50) elif "left" in command: turn_left(50) elif "right" in command: turn_right(50) except KeyboardInterrupt: GPIO.cleanup() if __name__ == "__main__": main()
Editor is loading...
Leave a Comment