STE-Nexus's picture
import time import RPi.GPIO as GPIO # For Raspberry Pi class SimpleRobot: def __init__(self): # Initialize motor pins (example for 2-wheel robot) self.left_motor_pin = 17 self.right_motor_pin = 18 # Setup GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(self.left_motor_pin, GPIO.OUT) GPIO.setup(self.right_motor_pin, GPIO.OUT) # Create PWM instances for speed control self.left_pwm = GPIO.PWM(self.left_motor_pin, 100) # 100Hz frequency self.right_pwm = GPIO.PWM(self.right_motor_pin, 100) self.left_pwm.start(0) self.right_pwm.start(0) def move_forward(self, speed=50, duration=1): """Move robot forward at specified speed for duration seconds""" self.left_pwm.ChangeDutyCycle(speed) self.right_pwm.ChangeDutyCycle(speed) time.sleep(duration) self.stop() def turn_left(self, speed=50, duration=0.5): """Turn robot left""" self.left_pwm.ChangeDutyCycle(0) self.right_pwm.ChangeDutyCycle(speed) time.sleep(duration) self.stop() def turn_right(self, speed=50, duration=0.5): """Turn robot right""" self.left_pwm.ChangeDutyCycle(speed) self.right_pwm.ChangeDutyCycle(0) time.sleep(duration) self.stop() def stop(self): """Stop all motors""" self.left_pwm.ChangeDutyCycle(0) self.right_pwm.ChangeDutyCycle(0) def cleanup(self): """Clean up GPIO resources""" self.stop() self.left_pwm.stop() self.right_pwm.stop() GPIO.cleanup() # Example usage if __name__ == "__main__": robot = SimpleRobot() try: print("Moving forward for 2 seconds...") robot.move_forward(duration=2) print("Turning left...") robot.turn_left() print("Moving forward again...") robot.move_forward(duration=1.5) finally: robot.cleanup() - Initial Deployment
cd4b5d9 verified