float scaledX, scaledY, scaledZ; // Scaled values for each ax
is
if (micro_is_5V) // microcontroller runs off 5V
{
scaledX = mapf(rawX, 0, 675, scale, scale); // 3.3/5 * 10
23 =~ 675
}
else // microcontroller runs off 3.3V
{
scaledX = mapf(rawX, 0, 1023, scale, scale);
}
We first declare the scaled variables as floats, since we want decimal
places. We then check whether the microcontroller is running off of 5V or
3.3V with the boolean
micro_is_5V . Based on that we scale the raw
integer value of x,
rawX , into a decimal value measured in g forces, called
scaledX using a mapping function. We also do this for the Y and Z axis
however I left those out above since they follow the exact same process.
Remember that the 675 came from the fact that a 5V Arduino will measure
3.3V as 675, while a 3.3V Arduino will measure 3.3V as 1023.
The
mapf() function exists in the sketch and works exactly the same as
Arduino standard
map() function, which you can reference here. The
reason I didn’t use the standard map was because it deals with integers
only, and, for our purposes, we need decimal places. Thus, I essentially
rewrote the exact same function using floats instead.
After scaling, we print both the raw and scaled data to the Serial Monitor.
You probably only care to view the scaled data unless your debugging,
however I left both there so you can compare. Here’s how to print the raw
and scaled data for each axis:
// Print out raw X,Y,Z accelerometer readings
Serial.print("X: "); Serial.println(rawX);
// Print out scaled X,Y,Z accelerometer readings
Serial.print("X: "); Serial.print(scaledX); Serial.println
(" g");
This allows you to see the data in both forms. Afterward, we use a delay
before making extra sensor reads.
delay(2000);
In the example sketch, we pause for 2 seconds (2000 milliseconds) since
we are simply printing to the Serial Monitor for viewing and learning
purposes. In your actual project, you can read the sensor at 500Hz at most,
which means you want a minimum of 2 milliseconds in between sensor
reads.
Then it’s back to the beginning of
loop() . Hope this helps you collect and
analyze accelerometer data in your own project.
Resources & Going Further
Thanks for reading! By now you’ve become familiar with both the hardware
and software to use the ADXL337 and ADXL377 accelerometers. We’re
excited to see what you build with these sensors. The following resources
may be helpful for you when building your related projects:
• ADXL337 Datasheet
• ADXL377 Datasheet
• ADXL337 Breakout Github Repository
Page 5 of 6