HackSpace_-_April_2020

(Frankie) #1
LENS


  • if you’re a Frogger/Bunner aficionado, you may
    wish to implement this as well).
    Reading the accelerometer is as easy as importing
    the appropriate module and running one line:


from adafruit_circuitplayground import cp
x, y, z = cp.acceleration

Sending key presses is similarly easy. You can set up
a keyboard with the following:


from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import
KeyboardLayoutUS
from adafruit_hid.keycode import Keycode

keyboard = Keyboard(usb_hid.devices)

Then send key presses with code such as this:


time.keyboard.press(Keycode.LEFT_ARROW)
time.sleep(0.1)
keyboard.release_all()

The only thing left is to slot in our mechanics. The
X-axis on the accelerometer can determine if the
controller is tilted left or right. The output is between
10 (all the way left) and -10 (all the way right). We
chose to threshold it at 7 and -7 to require the user
to tilt it most of the way. There’s a little bit of fuzz
in the readings, especially as the user flicks the
controller up, so having a high threshold helps avoid
erroneous readings.
The Y-axis is for jumping. In this case, we require
a ‘flap’ where the user first lifts it up (over a
threshold of 5), then back down again.
The full code for our controller is:
import time
from adafruit_circuitplayground import cp
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import
KeyboardLayoutUS
from adafruit_hid.keycode import Keycode


keyboard = Keyboard(usb_hid.devices)

jumping = 0
up=False
while True:
x, y, z = cp.acceleration
if abs(y) > 5:
up=True
if y < 5 and up:
keyboard.press(Keycode.UP_ARROW)

time.sleep(0.3)
keyboard.release_all()
up=False
if x < -7 :
keyboard.press(Keycode.LEFT_ARROW)
time.sleep(0.1)
keyboard.release_all()
if x > 7 :
keyboard.press(Keycode.RIGHT_ARROW)
time.sleep(0.1)
keyboard.release_all()
time.sleep(0.1)
if jumping > 0: jumping=jumping-1
The final challenge we had was that there’s a bit of
wobble when moving the controller around –
especially when trying to jump repeatedly and
quickly. After fiddling with thresholds for a while, we
found that there’s a much simpler solution: increase
the weight of the controller. The easiest way to do
this is to place it inside a book. If you’ve ever held a
copy of Code the Classics, you’ll know that it’s a
fairly weighty tome. Just place the board inside and
close the book around it, and all the jitter disappears.
That’s all there is to the controller. You can use it to
play the game, just as you would any joypad. Start
the game as usual, then start flapping the book
around to get hopping.

Above
It doesn’t take
much CircuitPython
to convert a
microcontroller into
a games controller
Below
Subscribe to
HackSpace
magazine for twelve
months and you get
a Circuit Playground
Express for free –
you can make your
very own Infinite
Bunner controller
Free download pdf