I am trying to track the vibrational movements of a transducer with an MMA8451. The code I have is below:
Code: Select all
#include <Wire.h>
#include <Adafruit_MMA8451.h>
Adafruit_MMA8451 mma = Adafruit_MMA8451(); // Initialize MMA8451 accelerometer
const int sample_rate = 500; // Sample rate in Hz
const int sample_count = 1000; // Number of samples to collect
const float sensitivity = 0.063; // Sensitivity of MMA8451 accelerometer in LSB/g
void setup() {
Serial.begin(9600); // Initialize serial communication
while (!Serial) {
; // Wait for serial port to connect
}
mma.begin(); // Initialize MMA8451 accelerometer
mma.setRange(MMA8451_RANGE_2_G); // Set accelerometer range to +/-2g
mma.setDataRate(MMA8451_DATARATE_800_HZ); // Set data rate to 800Hz
}
void loop() {
float x, y, z;
float max_x = -1000, min_x = 1000;
float max_y = -1000, min_y = 1000;
float max_z = -1000, min_z = 1000;
unsigned long t1, t2;
float freq, ampl_x, ampl_y, ampl_z;
// Collect accelerometer samples
for (int i = 0; i < sample_count; i++) {
mma.read(); // Read accelerometer values
x = mma.x * sensitivity; // Convert to acceleration in g
y = mma.y * sensitivity;
z = mma.z * sensitivity;
// Update maximum and minimum acceleration values
if (x > max_x) max_x = x;
if (x < min_x) min_x = x;
if (y > max_y) max_y = y;
if (y < min_y) min_y = y;
if (z > max_z) max_z = z;
if (z < min_z) min_z = z;
delay(1000/sample_rate); // Wait for sample interval
}
// Calculate amplitude and frequency
t1 = millis(); // Record start time
freq = sample_rate / (float)sample_count;
ampl_x = (max_x - min_x) / 2 * 9.81 * 1000; // Convert from g to mm/s^2
ampl_y = (max_y - min_y) / 2 * 9.81 * 1000;
ampl_z = (max_z - min_z) / 2 * 9.81 * 1000;
t2 = millis(); // Record end time
// Display amplitude and frequency on serial monitor
Serial.print("Amplitude X: ");
Serial.print(ampl_x, 2);
Serial.print(" mm/s^2, Amplitude Y: ");
Serial.print(ampl_y, 2);
Serial.print(" mm/s^2, Amplitude Z: ");
Serial.print(ampl_z, 2);
Serial.print(" mm/s^2, Frequency: ");
Serial.print(freq, 2);
Serial.print(" Hz, Sampling time: ");
Serial.print((t2 - t1) / 1000.0, 2);
Serial.println(" s");
delay(500); // Wait for 500ms before taking next measurement
}
Any help?
P.S. The movement should be around 1mm in the z, x and y are unknown. The frequency should be around 25Hz