-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobstacleAvoidance.py
More file actions
86 lines (67 loc) · 2.63 KB
/
obstacleAvoidance.py
File metadata and controls
86 lines (67 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""
Obstacle Avoidance Robot using 3V-5.5V SR04P Ultrasonic Ranging Module.
Additional Library:
- adafruit_hcsr04.mpy
- adafruit_motor
"""
import time
import board
import digitalio
import pwmio
from adafruit_motor import motor
import adafruit_hcsr04
class ObstacleAvoidanceRobot:
"""Encapsulates obstacle avoidance robot behavior."""
def __init__(self):
"""Initialize motors, sonar sensor, and button."""
# Ultrasonic Sensor Setup
self.sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.GP16, echo_pin=board.GP17)
# Left Motor
pwm_1a = pwmio.PWMOut(board.GP8, frequency=10000)
pwm_1b = pwmio.PWMOut(board.GP9, frequency=10000)
self.motor_left = motor.DCMotor(pwm_1a, pwm_1b)
# Right Motor
pwm_2a = pwmio.PWMOut(board.GP10, frequency=10000)
pwm_2b = pwmio.PWMOut(board.GP11, frequency=10000)
self.motor_right = motor.DCMotor(pwm_2a, pwm_2b)
self.running = False
def move(self, left_throttle, right_throttle):
"""Apply throttle to both motors."""
self.motor_left.throttle = left_throttle
self.motor_right.throttle = right_throttle
def read_distance(self):
"""Read distance from ultrasonic sensor."""
time.sleep(0.1)
return self.sonar.distance
def avoid_obstacle(self):
"""Main obstacle avoidance loop."""
print("Obstacle avoidance mode active...")
self.running = True
while self.running:
try:
distance = self.read_distance()
print(f"Distance: {distance} cm")
if distance < 10: # Obstacle detected
print("Obstacle detected! Turning left...")
self.move(0.1, 0.5) # Turn Left
time.sleep(1)
else: # No obstacle
self.move(0.5, 0.54) # Move Forward
except RuntimeError:
print("Ultrasonic sensor error. Retrying...")
self.move(0, 0) # Stop in case of sensor error
time.sleep(0.1)
def stop(self):
"""Stop the robot and exit obstacle avoidance mode."""
print("Stopping obstacle avoidance mode...")
self.running = False
self.move(0, 0)
def main():
"""Main entry point for obstacle avoidance robot."""
robot = ObstacleAvoidanceRobot()
while True:
print("Starting obstacle avoidance robot...")
robot.avoid_obstacle()
time.sleep(0.5) # Debounce delay
if __name__ == "__main__":
main()