void loop() {
const int x = analogRead(X_AXIS_PIN);
const int y = analogRead(Y_AXIS_PIN);
const int z = analogRead(Z_AXIS_PIN);
min_x = min(x, min_x); max_x = max(x, max_x);
min_y = min(y, min_y); max_y = max(y, max_y);
min_z = min(z, min_z); max_z = max(z, max_z);
Serial.print("x(");
Serial.print(min_x);
Serial.print("/");
Serial.print(max_x);
Serial.print("), y(");
Serial.print(min_y);
Serial.print("/");
Serial.print(max_y);
Serial.print("), z(");
Serial.print(min_z);
Serial.print("/");
Serial.print(max_z);
Serial.println(")");
}
We declare variables for the minimum and maximum values of all three axes,
and we initialize them with numbers that are definitely out of the sensor’s
range (-1000 and 1000). In the
loop
function, we permanently measure the
acceleration of all three axes and adjust the minimum and maximum values
accordingly.
Compile and upload the sketch, then move the breadboard with the sensor
in all directions, and then tilt it around all axes. Move it slowly, move it fast,
tilt it slowly, and tilt it fast. Be careful when moving and rotating the bread-
board that you don’t accidentally loosen a connection.
After a short while, the minimum and maximum values will stabilize, and
you should get output like this:
x(247/649), y(253/647), z(278/658)
Write down these values, because we’ll need them later, and you’ll probably
need them when you do your own sensor experiments.
Now let’s see how to get rid of the jitter. In principle, it’s simple. Instead of
returning the acceleration data immediately, we collect the last readings and
return their average. This way, small changes will be ironed out. The code
looks as follows:
Chapter 6. Building a Motion-Sensing Game Controller • 104
report erratum • discuss
www.it-ebooks.info