Raspberry Pi 5 Robot Car Controller
Code:
#!/usr/bin/env python3"""Raspberry Pi 5 Robot Car ControllerFor Ackermann Chassis with servo steering and DC motor drive"""import RPi.GPIO as GPIOimport time# GPIO Pin setupSERVO_PIN = 17MOTOR_DIR1 = 23MOTOR_DIR2 = 24MOTOR_PWM = 25# ConstantsSERVO_CENTER = 7.5 # Duty cycle for center position (adjust as needed)SERVO_LEFT = 5.0 # Duty cycle for full leftSERVO_RIGHT = 10.0 # Duty cycle for full rightMOTOR_FREQ = 100 # PWM frequency for motorclass AckermannRobotCar: def __init__(self): # Set GPIO mode GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Setup servo pin GPIO.setup(SERVO_PIN, GPIO.OUT) self.servo_pwm = GPIO.PWM(SERVO_PIN, 50) # 50Hz for servo self.servo_pwm.start(SERVO_CENTER) # Setup motor pins GPIO.setup(MOTOR_DIR1, GPIO.OUT) GPIO.setup(MOTOR_DIR2, GPIO.OUT) GPIO.setup(MOTOR_PWM, GPIO.OUT) self.motor_pwm = GPIO.PWM(MOTOR_PWM, MOTOR_FREQ) self.motor_pwm.start(0) print("Robot car initialized") def steer(self, angle): """ Steer the car. Angle should be between -1.0 (full left) and 1.0 (full right) """ if angle < -1.0: angle = -1.0 elif angle > 1.0: angle = 1.0 # Convert angle to duty cycle if angle < 0: # Left turn duty_cycle = SERVO_CENTER + angle * (SERVO_CENTER - SERVO_LEFT) else: # Right turn duty_cycle = SERVO_CENTER + angle * (SERVO_RIGHT - SERVO_CENTER) self.servo_pwm.ChangeDutyCycle(duty_cycle) print(f"Steering: {angle:.2f}, PWM: {duty_cycle:.2f}") def drive(self, speed): """ Drive the car. Speed should be between -1.0 (full reverse) and 1.0 (full forward) """ if speed < -1.0: speed = -1.0 elif speed > 1.0: speed = 1.0 # Set direction if speed >= 0: GPIO.output(MOTOR_DIR1, GPIO.HIGH) GPIO.output(MOTOR_DIR2, GPIO.LOW) pwm_value = abs(speed) * 100 else: GPIO.output(MOTOR_DIR1, GPIO.LOW) GPIO.output(MOTOR_DIR2, GPIO.HIGH) pwm_value = abs(speed) * 100 self.motor_pwm.ChangeDutyCycle(pwm_value) print(f"Driving: {speed:.2f}, PWM: {pwm_value:.2f}") def stop(self): """Stop the car (both steering and driving)""" self.steer(0) self.drive(0) print("Car stopped") def cleanup(self): """Clean up GPIO""" self.stop() self.servo_pwm.stop() self.motor_pwm.stop() GPIO.cleanup() print("GPIO cleaned up") # Example usageif __name__ == "__main__": car = AckermannRobotCar() try: print("Testing car controls...") # Center the steering car.steer(0) time.sleep(1) # Test left turn print("Turning left...") car.steer(-0.5) time.sleep(1) # Test right turn print("Turning right...") car.steer(0.5) time.sleep(1) # Center again car.steer(0) time.sleep(1) # Test driving forward print("Driving forward...") car.drive(0.5) time.sleep(2) # Test driving backward print("Driving backward...") car.drive(-0.5) time.sleep(2) # Stop car.stop() except KeyboardInterrupt: print("Program stopped by user") finally: car.cleanup()Statistics: Posted by rediy — Fri Mar 14, 2025 8:00 am