It starts with a small delay to give the Arduino some time to switch between
analog pins; otherwise, you might get bad data. Then it reads the acceleration
for the axis we have passed and stores it at the current buffer position
belonging to the axis. It increases the buffer position and sets it back to zero
when the end of the buffer has been reached. Finally, we return the average
value of the data we have gathered so far for the current axis.
That’s the whole trick, and the data structure we’ve just built is named
circular
buffer
.
2
To see its effect, leave the sensor untouched on your desk and run the
program with different buffer sizes. If you don’t touch the sensor, you wouldn’t
expect the program’s output to change. But if you set
BUFFER_SIZE
to 1, you
will quickly see small changes. They will disappear as soon as the buffer is
big enough.
The acceleration data we measure now is accurate enough that we can finally
build a game controller that won’t annoy users with unexpected movements.
Building Your Own Game Controller
To build a full-blown game controller, we only need to add a button to our
breadboard. Figure 19, Game controller with accelerometer and pushbutton,
on page 107 shows you how to do it. (Please double-check the pin labels on
your breakout board!)
That’s how it looks inside a typical modern game controller. We won’t build
a fancy housing for the controller, but we still should think about ergonomics
for a moment. Our current breadboard solution is rather fragile (see the fol-
lowing figure), and you cannot really wave around the board when it’s con-
nected to the Arduino. Sooner or later you’ll disconnect some wires, and the
controller will stop working.
To solve this problem, you could try to attach the breadboard to the Arduino
using some rubber bands. That works, but it doesn’t look very pretty, and
it’s still hard to handle.
A much better solution is to use an Arduino Proto Shield—a pluggable
breadboard that lets you quickly build circuit prototypes. The breadboard is
surrounded by the Arduino’s pins, so you no longer need long wires. Shields
are a great way to enhance an Arduino’s capabilities, and you can get shields
for many different purposes, such as adding Ethernet, sound, displays, and
so on. The figure on page 108 shows a bare Proto Shield and a shield containing
our motion sensor.
2.
http://en.wikipedia.org/wiki/Circular_buffer
Chapter 6. Building a Motion-Sensing Game Controller • 106
report erratum • discuss
www.it-ebooks.info