MotionSensor/Buffering/Buffering.ino
const unsigned int X_AXIS_PIN = 2;
Line 1
const unsigned int Y_AXIS_PIN = 1;
-
const unsigned int Z_AXIS_PIN = 0;
-
const unsigned int NUM_AXES = 3;
-
const unsigned int PINS[NUM_AXES] = {
5
X_AXIS_PIN, Y_AXIS_PIN, Z_AXIS_PIN
-
};
-
const unsigned int BUFFER_SIZE = 16;
-
const unsigned int BAUD_RATE = 9600;
-
int buffer[NUM_AXES][BUFFER_SIZE];
10
int buffer_pos[NUM_AXES] = { 0 };
-
-
void setup() {
-
Serial.begin(BAUD_RATE);
-
}
15
-
int get_axis(const int axis) {
-
delay(1);
-
buffer[axis][buffer_pos[axis]] = analogRead(PINS[axis]);
-
buffer_pos[axis] = (buffer_pos[axis] + 1) % BUFFER_SIZE;
20
long sum = 0;
-
for (unsigned int i = 0; i < BUFFER_SIZE; i++)
-
sum += buffer[axis][i];
-
return round(sum / BUFFER_SIZE);
-
}
25
-
int get_x() { return get_axis(0); }
-
int get_y() { return get_axis(1); }
-
int get_z() { return get_axis(2); }
-
void loop() {
30
Serial.print(get_x());
-
Serial.print(" ");
-
Serial.print(get_y());
-
Serial.print(" ");
-
Serial.println(get_z());
35
}
-
As usual, we define some constants for the pins we use first. This time, we
also define a constant named
NUM_AXES
that contains the number of axes we
are measuring. We also have an array named
PINS
that contains a list of the
pins we use. This will help us keep our code more generic later.
In line 10, we declare buffers for all axes. They will be filled with the sensor
data we measure, so we can calculate average values when we need them.
We have to store our current position in each buffer, so in line 11, we define
an array of buffer positions.
setup
only initializes the serial port; the real action takes place in
get_axis
.
report erratum • discuss
Finding and Polishing Edge Values • 105
www.it-ebooks.info