Created
August 24, 2016 17:11
-
-
Save artpoz/ee9e34bf4a7dcba1364afa06611a0a26 to your computer and use it in GitHub Desktop.
RPICAR - PS3 gamepad controlled car based on Raspberry Pi
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.KEYDOWN: | |
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) | |
else: | |
myMotorRight.run(Adafruit_MotorHAT.BACKWARD) | |
myMotorRight.setSpeed(abs(right_speed)) | |
time.sleep(0.01) | |
axis = joystick.get_axis( 3 ) | |
left_speed = int (axis * 255) | |
print("Axis {} value: {:>6.3f}".format(3, axis), left_speed ) | |
if left_speed < 0: | |
myMotorLeft.run(Adafruit_MotorHAT.FORWARD) | |
else: | |
myMotorLeft.run(Adafruit_MotorHAT.BACKWARD) | |
myMotorLeft.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