Skip to content

Instantly share code, notes, and snippets.

@andywarburton
Last active July 1, 2017 08:29
Show Gist options
  • Save andywarburton/1a1261cc6acbb77e657bcc5f436dfa96 to your computer and use it in GitHub Desktop.
Save andywarburton/1a1261cc6acbb77e657bcc5f436dfa96 to your computer and use it in GitHub Desktop.
simple script for controlling motors and lights with piborg zero motor controller and a raspberry pi
#!/usr/bin/env python
# coding: Latin-1
# Load library functions we want
from inputs import get_gamepad
import piconzero as pz
import time
import sys
import random
import colorsys
# Initiate motor controller
pz.init()
# Control Setup
left_stick = 0.0
right_stick = 0.0
# ACTIVATE BLINKY LIGHTS
pz.setOutputConfig(5, 3)
pz.setBrightness(255)
# Animation functions
def np_police():
while True:
# POLICE LIGHTS
pz.setAllPixels(255,0,0)
time.sleep(0.2)
pz.setAllPixels(0, 0, 255)
time.sleep(0.2)
pz.setAllPixels(255, 255, 255)
time.sleep(0.2)
def np_rainbow():
spacing = 360.0 / 16.0
hue = 0
while True:
# RAINBOW
hue = int(time.time() * 100) % 360
for x in range(16):
offset = x * spacing
h = ((hue + offset) % 360) / 360.0
r, g, b = [int(c*255) for c in colorsys.hsv_to_rgb(h, 1.0, 1.0)]
pz.setPixel(x, r, g, b)
pz.updatePixels()
time.sleep(0.001)
def np_downlights():
# DOWNLIGHTS
pz.setAllPixels(255,255,255, True)
def np_knightrider():
# KNIGHTRIDER
REDS = [0, 0, 0, 0, 0, 16, 64, 255, 64, 16, 0, 0, 0, 0, 0]
start_time = time.time()
while True:
delta = (time.time() - start_time) * 16
# Triangle wave, a snappy ping-pong effect
offset = int(abs((delta % 16) - 8))
for i in range(8):
pz.setPixel(i , 0, REDS[offset + i], 0)
pz.updatePixels()
time.sleep(0.1)
# Controller events
try:
print('Press CTRL+C to quit')
# Loop indefinitely
while True:
events = get_gamepad()
for event in events:
print(event.code, event.state)
# face buttons
if event.code == "BTN_EAST":
np_knightrider()
if event.code == "BTN_SOUTH":
np_rainbow()
if event.code == "BTN_WEST":
np_downlights()
if event.code == "BTN_NORTH":
np_police()
# left stick
if event.code == "ABS_Y":
left_stick = event.state
if left_stick > 130:
left_stick = -(left_stick - 130)
elif left_stick < 125:
left_stick = ((-left_stick) + 125)
else:
left_stick = 0.0
print("Y: " + str(-left_stick))
# right stick
if event.code == "ABS_RZ":
right_stick = event.state
if right_stick > 130:
right_stick = -(right_stick - 130)
elif right_stick < 125:
right_stick = ((-right_stick) + 125)
else:
right_stick = 0.0
print("Y: " + str(-right_stick))
# engage the motors
power_left = int( (left_stick / 125.0) * 100)
power_right = int( (right_stick / 125.0) * 100)
pz.setMotor(0, power_left)
pz.setMotor(1, power_right)
# print(event.ev_type, event.code, event.state)
except KeyboardInterrupt:
# CTRL+C exit, disable all drives
print("stop")
pz.setAllPixels(0,0,0, True)
pz.stop()
pz.cleanup( )
print("bye")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment