Files
raspberry-pi/x.py
T
2019-04-02 00:02:38 +11:00

107 lines
2.2 KiB
Python

import usb.core
import usb.util
import time
import RPi.GPIO as GPIO
USB_IF = 0 # Interface
USB_TIMEOUT = 5 # Timeout in MS
SLEEP_TIME = 0.05
BTN_LEFT = 4
BTN_RIGHT = 8
BTN_DOWN = 2
BTN_UP = 1
BTN_STOP = 44 # Space
BTN_EXIT = 32 # ESC
USB_VENDOR = 0x045e # Rii
USB_PRODUCT = 0x028e # Mini Wireless Keyboard
ForwardRight=20
BackwardRight=26
ForwardLeft=18
BackwardLeft=17
GPIO.setmode(GPIO.BCM)
GPIO.setup(ForwardRight, GPIO.OUT)
GPIO.setup(BackwardRight, GPIO.OUT)
GPIO.setup(ForwardLeft, GPIO.OUT)
GPIO.setup(BackwardLeft, GPIO.OUT)
def forward():
GPIO.output(ForwardLeft, GPIO.HIGH)
GPIO.output(ForwardRight, GPIO.HIGH)
time.sleep(SLEEP_TIME)
def backward():
GPIO.output(BackwardRight, GPIO.HIGH)
GPIO.output(BackwardLeft, GPIO.HIGH)
time.sleep(SLEEP_TIME)
def turn_left():
GPIO.output(ForwardLeft, GPIO.HIGH)
GPIO.output(BackwardRight, GPIO.HIGH)
time.sleep(SLEEP_TIME)
def turn_right():
GPIO.output(ForwardRight, GPIO.HIGH)
GPIO.output(BackwardLeft, GPIO.HIGH)
time.sleep(SLEEP_TIME)
def clear():
GPIO.output(ForwardLeft, GPIO.LOW)
GPIO.output(ForwardRight, GPIO.LOW)
GPIO.output(BackwardRight, GPIO.LOW)
GPIO.output(BackwardLeft, GPIO.LOW)
dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT)
endpoint = dev[0][(0,0)][0]
if dev.is_kernel_driver_active(USB_IF) is True:
dev.detach_kernel_driver(USB_IF)
usb.util.claim_interface(dev, USB_IF)
while True:
control = None
try:
control = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, USB_TIMEOUT)
# print(control)
if control[0] == 0:
# print('clear')
clear()
except:
pass
if control != None:
if BTN_DOWN in control:
print('-')
backward()
if BTN_UP in control:
print('+')
forward()
if BTN_LEFT in control:
print('<-')
turn_left()
if BTN_RIGHT in control:
print('->')
turn_right()
if BTN_STOP in control:
print('stop')
if BTN_EXIT in control:
clear()
exit()
else:
clear()
time.sleep(SLEEP_TIME) # Let CTRL+C actually exit