Arduino programming: Build a games console (part 1/2)
SCHOOL OF MAKING
Creating a set of rules for analogue control can
be complicated, but we’ve got an excellent
new function at our disposal
”
”
JOYSTICK CONTROL
We now want to write the code that reads the
joystick values and translates these into ship
movement. An analogue joystick is really just two
potentiometers, one each for the x and y axes,
with each sending a range of values from 0 to
- These values are delivered to the A0 and
A1 analogue inputs in the Arduino. The joystick is
spring-loaded to hold the middle position, where
both x and y potentiometers read 511, and these
values change as you move the stick. There are
many ways these changes can be interpreted, and
they’ll all result in slightly different gameplay. You
could use the joystick as a digital input, for example,
turning on positive x movement when the x value is
greater than 511, but that loses the finer control you
get from an analogue joystick.
Creating a set of rules for analogue control can
be complicated, but we’ve got an excellent new
function at our disposal, and that is called map. The
map function simply converts one range of numbers
to another, such as from 10–20 to 1–10. It can
also handle negative integers, and that makes it
perfect for translating the raw values we get from
the joystick’s analogue inputs into a value range
that could represent the number of pixels we want
our ship to move – in both positive and negative
directions. This can even be accomplished with just
a couple of lines:
xValue = map(analogRead(JOYX), 0, 1024, 5, -8);
yValue = map(analogRead(JOYY), 0, 1024, -5, 5);
Above
An analogue joystick
sends values between
0 and 1023 from (0,0) in
the top left to (1023,1023)
in the bottom right, with
(511,511) in the centre
Right
The analogue joystick
needs power and ground,
shared with the screen,
and two analogue inputs
for x and y and another
digital input for the switch
0,0
top left
0,511
left centre
511,0
top left
511,511
centre
511,1023
bottom centre
1023,511
right centre
1023,0
top right
1023,1023
bottom right
0,1023
bottom left