Created
April 3, 2017 07:18
-
-
Save artpoz/7625cc2e64699bc26efd824cf90bdd1e to your computer and use it in GitHub Desktop.
PS4 gamepad car
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
__author__ = 'Artur Poznanski' | |
from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor | |
import time | |
import atexit | |
import pygame | |
# create a default object, no changes to I2C address or frequency | |
mh = Adafruit_MotorHAT(addr=0x60) | |
# recommended for auto-disabling motors on shutdown! | |
def turnOffMotors(): | |
mh.getMotor(1).run(Adafruit_MotorHAT.RELEASE) | |
mh.getMotor(2).run(Adafruit_MotorHAT.RELEASE) | |
mh.getMotor(3).run(Adafruit_MotorHAT.RELEASE) | |
mh.getMotor(4).run(Adafruit_MotorHAT.RELEASE) | |
atexit.register(turnOffMotors) | |
myMotorRight = mh.getMotor(4) | |
myMotorLeft = mh.getMotor(3) | |
pygame.init() | |
size = [500, 700] | |
screen = pygame.display.set_mode(size) | |
pygame.display.set_caption("My Game") | |
pygame.joystick.init() | |
joystick = pygame.joystick.Joystick(0) | |
joystick.init() | |
done = False | |
while done==False: | |
# EVENT PROCESSING STEP | |
for event in pygame.event.get(): | |
if event.type == pygame.JOYBUTTONDOWN: | |
print("Joystick button pressed.") | |
#axis29 = joystick.get_axis( 18 ) | |
#if axis29 > 0: | |
done = True | |
myMotorRight.run(Adafruit_MotorHAT.RELEASE) | |
myMotorLeft.run(Adafruit_MotorHAT.RELEASE) | |
time.sleep(1.0) | |
axis0 = joystick.get_axis( 1 ) | |
right_speed = int(axis0 * 255) | |
#print("Axis {} value: {:>6.3f} speed: {}".format(1, axis0, right_speed) ) | |
if right_speed < 0: | |
myMotorRight.run(Adafruit_MotorHAT.FORWARD) | |
myMotorLeft.run(Adafruit_MotorHAT.FORWARD) | |
else: | |
myMotorRight.run(Adafruit_MotorHAT.BACKWARD) | |
myMotorLeft.run(Adafruit_MotorHAT.BACKWARD) | |
myMotorRight.setSpeed(abs(right_speed)) | |
myMotorLeft.setSpeed(abs(right_speed)) | |
time.sleep(0.01) | |
axis = joystick.get_axis( 0 ) | |
left_speed = int (axis * 255) | |
print("Axis {} value: {:>6.3f}".format(0, axis), left_speed ) | |
if left_speed < 0: | |
myMotorLeft.run(Adafruit_MotorHAT.FORWARD) | |
myMotorRight.run(Adafruit_MotorHAT.BACKWARD) | |
else: | |
myMotorLeft.run(Adafruit_MotorHAT.BACKWARD) | |
myMotorRight.run(Adafruit_MotorHAT.FORWARD) | |
myMotorLeft.setSpeed(abs(left_speed)) | |
myMotorRight.setSpeed(abs(left_speed)) | |
time.sleep(0.01) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment