Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import RPi.GPIO as GPIO
- import time
- # Motor Driver HAT pins
- LEFT_PWM_PIN = 12
- LEFT_DIR_PIN = 16
- RIGHT_PWM_PIN = 13
- RIGHT_DIR_PIN = 18
- # Set up GPIO
- GPIO.setmode(GPIO.BCM)
- GPIO.setwarnings(False)
- GPIO.setup(LEFT_PWM_PIN, GPIO.OUT)
- GPIO.setup(LEFT_DIR_PIN, GPIO.OUT)
- GPIO.setup(RIGHT_PWM_PIN, GPIO.OUT)
- GPIO.setup(RIGHT_DIR_PIN, GPIO.OUT)
- # Set up PWM
- left_pwm = GPIO.PWM(LEFT_PWM_PIN, 50)
- right_pwm = GPIO.PWM(RIGHT_PWM_PIN, 50)
- # Start PWM
- left_pwm.start(0)
- right_pwm.start(0)
- def set_motor_speeds(left_speed, right_speed):
- if left_speed >= 0:
- GPIO.output(LEFT_DIR_PIN, GPIO.LOW)
- else:
- GPIO.output(LEFT_DIR_PIN, GPIO.HIGH)
- if right_speed >= 0:
- GPIO.output(RIGHT_DIR_PIN, GPIO.LOW)
- else:
- GPIO.output(RIGHT_DIR_PIN, GPIO.HIGH)
- left_pwm.ChangeDutyCycle(min(abs(left_speed), 100))
- right_pwm.ChangeDutyCycle(min(abs(right_speed), 100))
- try:
- while True:
- # Move forward
- set_motor_speeds(50, 50)
- time.sleep(2)
- # Stop
- set_motor_speeds(0, 0)
- time.sleep(2)
- # Move backward
- set_motor_speeds(-50, -50)
- time.sleep(2)
- # Stop
- set_motor_speeds(0, 0)
- time.sleep(2)
- except KeyboardInterrupt:
- pass
- # Clean up
- left_pwm.stop()
- right_pwm.stop()
- GPIO.cleanup()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement