Joystick
Plug a gamepad into the Pi with a USB cable, and your program can read its sticks, triggers and buttons. A DualShock 4 can also rumble and light its light bar.
Many USB cables only carry power, for charging. With one of those the gamepad never connects: its light bar stays dark and the program never sees it.
Gamepad and DualShock4 come from a library, not from the language, so this code won't build without it. In
IntelliJ, choose Tools | Nylon | Add Nylon Library… and pick gamepad. That adds one line to your project's
build.markup.code:
(+dependencies : RepositoryDependency coordinate={"com.grandtheorem:gamepad:0.1.0"} /)
Read the sticks
Gamepad comes from the gamepad library, and nylon.time gives us sleep.
# Print the left stick's position whenever it moves.
namespace sticks
import grandtheorem.gamepad.Gamepad
import namespace nylon.time
The program remembers where the left stick was, so it only prints when the stick moves.
# Where the stick was, so the
# program prints only when it moves.
entrypoint.default main() {
var lastX = f32(0)
var lastY = f32(0)
Gamepad.resolve(0) gives you the first pad plugged in, or nothing until there is one. read
gives you the pad's newest state, whether or not anything is pressed, waiting up to the timeout
for one. If none comes, the if skips its block.
# Look for a pad each time round, then
# its newest state, waiting up to 100 ms.
while (true) {
if (let pad? = Gamepad.resolve(0)) {
if (let state? = pad.read(100.milliseconds())) {
A stick is a pair of numbers. Print them only when they've changed, and remember them for next time.
# Print only when the stick has
# moved, then remember where it is.
if (state.leftX != lastX or state.leftY != lastY) {
println("left stick at ${state.leftX}, ${state.leftY}")
lastX = state.leftX
lastY = state.leftY
}
}
}
A pad reports hundreds of times a second, so wait a moment between reads, or the run window will flood.
# The pad reports far faster than
# anyone can read, so slow down.
sleep(100.milliseconds())
}
}
Move the left stick and its position appears in the run window, one line at a time. The program
loops forever, so press Stop in IntelliJ to end it. Everything the pad can tell you is on state:
On state | What it gives you |
|---|---|
leftX, leftY, rightX, rightY | A stick, from -1 to 1. It's 0 at rest, and up and right are positive |
leftTrigger, rightTrigger | A trigger, from 0 released to 1 fully pressed |
buttons.south(), east(), west(), north() | The four face buttons by where they sit, true while held |
buttons.leftShoulder(), rightShoulder() | The shoulder buttons, true while held |
buttons.leftStickPress(), rightStickPress() | A stick pressed in, true while held |
buttons.back(), start(), home(), extra() | The middle buttons, true while held |
dpad | Which way the D-pad points, or nothing |
The buttons are named by where they sit, so a program reads every pad the same way. On a DualShock
4, south is ✕, east ○, west □ and north △. A program that gets its pad from DualShock4.resolve(0), as
Rumble and light does, can also use the pad's own names: pad.buttons(state) gives
cross, circle, square, triangle, l1, r1, l3, r3, share, options, ps and
touchpad, each true while held.
Read the D-pad
The D-pad might not be pressed at all, so dpad may be missing. When it's there, it's one of eight
directions.
Direction is the type of dpad.
# Print which way the D-pad points.
namespace pointing
import grandtheorem.gamepad.Gamepad
import grandtheorem.gamepad.Direction
import namespace nylon.time
match! makes the compiler check that you've handled all eight.
# A name for each of the eight directions.
# match! checks that none is missing.
let name(way: Direction): string = match!(way) {
Direction.Up -> "up"
Direction.UpRight -> "up and right"
Direction.Right -> "right"
Direction.DownRight -> "down and right"
Direction.Down -> "down"
Direction.DownLeft -> "down and left"
Direction.Left -> "left"
Direction.UpLeft -> "up and left"
}
This if runs only while the D-pad is pressed, when dpad holds a direction.
# dpad is missing while nothing is
# pressed, so the if skips it then.
entrypoint.default main() {
while (true) {
if (let pad? = Gamepad.resolve(0)) {
if (let state? = pad.read(100.milliseconds())) {
if (let way? = state.dpad) {
println(name(way))
}
}
}
sleep(100.milliseconds())
}
}
Rumble and light
The rumble motors and the light bar belong to the DualShock 4, so a program that uses them asks for
one by name: DualShock4.resolve(0) gives you the first pad plugged in if it's a DualShock 4.
DualShock4 comes from the gamepad library too.
# Rumble with the triggers, under a blue light bar.
namespace feel
import grandtheorem.gamepad.DualShock4
import namespace nylon.time
light takes a color as 0xRRGGBB, so this is blue. It stays that way until you set it again.
# 0x0000FF is blue. The light stays
# until it's set again.
entrypoint.default main() {
while (true) {
if (let pad? = DualShock4.resolve(0)) {
pad.light(0x0000FF)
rumble takes the strong motor and then the weak one, each from 0 to 1. The triggers are already
in that range, so they can drive the motors directly.
# Each trigger, 0 to 1, drives one motor:
# left the strong one, right the weak one.
if (let state? = pad.read(100.milliseconds())) {
pad.rumble(state.leftTrigger, state.rightTrigger)
}
}
sleep(20.milliseconds())
}
}
The pad buzzes as you squeeze the triggers. Let go before you press Stop, because the rumble stays at the last level set.
Brighten the light bar with a trigger
The pad's own light bar can follow a trigger, so this needs nothing wired.
The start is the same as before.
# Brighten the light bar as the right
# trigger is squeezed.
namespace glow
import grandtheorem.gamepad.DualShock4
import namespace nylon.time
One pad, and nothing else.
# One pad, and nothing to wire.
entrypoint.default main() {
while (true) {
if (let pad? = DualShock4.resolve(0)) {
In 0xRRGGBB, blue is the last byte, so 0 to 255 runs from off to full blue. Scale the trigger's
0 to 1 up to that.
# The trigger's 0 to 1 becomes 0 to 255,
# the blue byte of 0xRRGGBB.
if (let state? = pad.read(100.milliseconds())) {
pad.light(i32(state.rightTrigger * f32(255)))
}
}
sleep(20.milliseconds())
}
}
The light bar brightens as you squeeze the right trigger, and dims as you let go.
Good to know
A stick at rest reads exactly 0. Within 8% of the middle, a stick counts as centered, so a pad left alone won't drift. Past that edge the reading climbs from 0, so full tilt is still 1.
Pulling a stick up is positive. leftY is 1 at the top, the way you'd expect, even though the
pad itself reports it the other way up.
A pad can come and go. Unplug it and Gamepad.resolve(0) finds nothing, and plug it back in
and it carries on.
Up to four pads. resolve takes 0 to 3, one for each pad plugged in. Any other number ends the
run with a fault that names it.
The DualShock 4 is the pad it reads. Switch Pro support is coming soon.
USB only. Bluetooth support, so a pad can pair without a cable, comes in V2.
Boards: Raspberry Pi 4. Zero 2 W: soon.