Advertisement
microrobotics

Raspberry Pi Motor Driver HAT

Apr 22nd, 2023
771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. import RPi.GPIO as GPIO
  2. import time
  3.  
  4. # Motor Driver HAT pins
  5. LEFT_PWM_PIN = 12
  6. LEFT_DIR_PIN = 16
  7. RIGHT_PWM_PIN = 13
  8. RIGHT_DIR_PIN = 18
  9.  
  10. # Set up GPIO
  11. GPIO.setmode(GPIO.BCM)
  12. GPIO.setwarnings(False)
  13.  
  14. GPIO.setup(LEFT_PWM_PIN, GPIO.OUT)
  15. GPIO.setup(LEFT_DIR_PIN, GPIO.OUT)
  16. GPIO.setup(RIGHT_PWM_PIN, GPIO.OUT)
  17. GPIO.setup(RIGHT_DIR_PIN, GPIO.OUT)
  18.  
  19. # Set up PWM
  20. left_pwm = GPIO.PWM(LEFT_PWM_PIN, 50)
  21. right_pwm = GPIO.PWM(RIGHT_PWM_PIN, 50)
  22.  
  23. # Start PWM
  24. left_pwm.start(0)
  25. right_pwm.start(0)
  26.  
  27. def set_motor_speeds(left_speed, right_speed):
  28.     if left_speed >= 0:
  29.         GPIO.output(LEFT_DIR_PIN, GPIO.LOW)
  30.     else:
  31.         GPIO.output(LEFT_DIR_PIN, GPIO.HIGH)
  32.  
  33.     if right_speed >= 0:
  34.         GPIO.output(RIGHT_DIR_PIN, GPIO.LOW)
  35.     else:
  36.         GPIO.output(RIGHT_DIR_PIN, GPIO.HIGH)
  37.  
  38.     left_pwm.ChangeDutyCycle(min(abs(left_speed), 100))
  39.     right_pwm.ChangeDutyCycle(min(abs(right_speed), 100))
  40.  
  41. try:
  42.     while True:
  43.         # Move forward
  44.         set_motor_speeds(50, 50)
  45.         time.sleep(2)
  46.  
  47.         # Stop
  48.         set_motor_speeds(0, 0)
  49.         time.sleep(2)
  50.  
  51.         # Move backward
  52.         set_motor_speeds(-50, -50)
  53.         time.sleep(2)
  54.  
  55.         # Stop
  56.         set_motor_speeds(0, 0)
  57.         time.sleep(2)
  58.  
  59. except KeyboardInterrupt:
  60.     pass
  61.  
  62. # Clean up
  63. left_pwm.stop()
  64. right_pwm.stop()
  65. GPIO.cleanup()
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement