A pointing-north compass on the Sense HAT
Use the Sense HAT magnetometer to draw an arrow on the LED matrix that always points toward magnetic north.
Compass reads the Sense HAT's magnetometer and draws a small arrow on the 8×8 LED matrix that continuously points toward magnetic north as you rotate the board.
Source code: projects/Compass/Compass.java
How it works
The IMU on the Sense HAT includes a magnetometer, and Pi4J's SenseHat exposes hat.getCompass() which returns a heading in degrees (0° = north, 90° = east, etc.).
The main loop is very simple:
smoothedHeading(hat, 5)— takes 5 readings 10 ms apart and averages them, to smooth out sensor noise.drawArrowToNorth(hat, heading)— clears the matrix and draws a 3-pixel arrow from the center(3, 3)in the direction of north.
Drawing the arrow works as follows:
- Convert the heading to radians and negate it. The arrow needs to point back toward north as the board turns, not follow the same rotation.
- For each step
ifrom 1 to 3, compute an offset withMath.cos(angleRad) * iandMath.sin(angleRad) * i. - Round to the nearest integer to get an
(x, y)position on the 8×8 grid, and paint that pixel dark red for the shaft and bright red for the tip. - Paint the center of the matrix blue as an anchor.
Because the arrow is only 3 pixels long, the resolution is coarse, but you can immediately see it snap to the direction of north as you spin the board.
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/Compass/Compass.java