← Back to projects
Moving a pixel with the Sense HAT joystick

Joystick reads events from the Sense HAT joystick (up/down/left/right/center) and moves a single pixel around the 8×8 LED matrix. Pressing the center button toggles the pixel between green and red.

Source code: projects/Joystick/Joystick.java

How it works

The Sense HAT joystick is exposed to Pi4J as a GameController with the keys UP, DOWN, LEFT, RIGHT and CENTER. This example uses polling (hat.getEvents()) rather than a listener.

Every iteration of the main loop:

  1. Reads all pending joystick events with hat.getEvents().
  2. For each event, looks at the key() and action() (either PRESSED or RELEASED).
  3. If the key is CENTER and it was pressed, toggles currentColor between green and red.
  4. If the key is a direction, stores it in heldDirection on press and clears it on release — that gives us "press and hold" movement.
  5. If a direction is currently held, moves the (x, y) pixel by the corresponding delta using Math.floorMod for wrap-around at the edges.
  6. Redraws the matrix and sleeps 150 ms.

The result feels a lot like driving a cursor on a tiny screen — a nice building block for menus or small games.

Running it

This script depends on a specific branch of pi4j-drivers (my igfasouza branch), so clone and install it locally first:

git clone -b igfasouza https://github.com/igfasouza/pi4j-drivers.git
cd pi4j-drivers
mvn install

Then run it with JBang on a Raspberry Pi with a Sense HAT attached:

jbang projects/Joystick/Joystick.java