In this article we connect an ADXL337 accelerometer to an STM32 Nucleo, the example was written in the Arduino IDE
The ADXL337 is a small, thin, low power, complete 3-axis accelerometer with signal conditioned voltage outputs. The product measures acceleration with a minimum full-scale range of ±3g. It can measure the static acceleration of gravity in tiltsensing applications, as well as dynamic acceleration resulting from motion, shock, or vibration.
The user selects the bandwidth of the accelerometer using the CX, CY, and CZ capacitors at the XOUT, YOUT, and ZOUTpins. Bandwidths can be selected to suit the application, with a range of 0.5 Hz to 1600 Hz for X and Y axes, and a range of 0.5 Hz to 550 Hz for the Z axis.
Parts List
Connection
Module | STM32 Nucleo |
Vcc | 3.3v |
Gnd | Gnd |
X_OUT | A0 |
Y_OUT | A1 |
Z_OUT | A2 |
Code
No libraries required – this is a sparkfun example
[codesyntax lang=”cpp”]
// Make sure these two variables are correct for your setup int scale = 3; // 3 (±3g) for ADXL337, 200 (±200g) for ADXL377 void setup() { // Initialize serial communication at 115200 baud Serial.begin(115200); } // Read, scale, and print accelerometer data void loop() { // Get raw accelerometer data for each axis int rawX = analogRead(A0); int rawY = analogRead(A1); int rawZ = analogRead(A2); // Scale accelerometer ADC readings into common units // Scale map depends on if using a 5V or 3.3V microcontroller float scaledX, scaledY, scaledZ; // Scaled values for each axis scaledX = mapf(rawX, 0, 675, -scale, scale); // 3.3/5 * 1023 =~ 675 scaledY = mapf(rawY, 0, 675, -scale, scale); scaledZ = mapf(rawZ, 0, 675, -scale, scale); // Print out raw X,Y,Z accelerometer readings Serial.print("X: "); Serial.println(rawX); Serial.print("Y: "); Serial.println(rawY); Serial.print("Z: "); Serial.println(rawZ); Serial.println(); // Print out scaled X,Y,Z accelerometer readings Serial.print("X: "); Serial.print(scaledX); Serial.println(" g"); Serial.print("Y: "); Serial.print(scaledY); Serial.println(" g"); Serial.print("Z: "); Serial.print(scaledZ); Serial.println(" g"); Serial.println(); delay(2000); // Minimum delay of 2 milliseconds between sensor reads (500 Hz) } // Same functionality as Arduino's standard map function, except using floats float mapf(float x, float in_min, float in_max, float out_min, float out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; }
[/codesyntax]
Output
Open the serial monitor and you will see something like this
X: 483
Y: 465
Z: 444
X: 1.29 g
Y: 1.13 g
Z: 0.95 g
X: 610
Y: 532
Z: 501
X: 2.42 g
Y: 1.73 g
Z: 1.45 g
Links
https://www.analog.com/media/en/technical-documentation/data-sheets/ADXL337.pdf