Hi there, this is regarding a fall detection. I have attached the code. It doesn't seem to print anything in the serial monitor. This is my first time doing this, and I can't find the error.
#include <Wire.h> // I2C communication
#include <BMA250.h> // Accelerometer library
// Accelerometer variables
BMA250 accel_sensor;
int x, y, z;
double temp;
float accelMagnitude;
// Fall detection thresholds
float impactThreshold = 2.5;
float freeFallThreshold = 0.5;
float recoveryThreshold = 1.0;
unsigned long recoveryDelay = 1000;
// Fall detection states
enum FallState { IDLE, IMPACT_DETECTED, FREE_FALL_DETECTED };
FallState fallState = IDLE;
unsigned long impactTime = 0;
unsigned long freeFallTime = 0;
// Setup Serial for different boards
#if defined(ARDUINO_ARCH_SAMD)
#define SerialMonitorInterface SerialUSB
#else
#define SerialMonitorInterface Serial
#endif
void setup() {
SerialMonitorInterface.begin(115200);
Wire.begin();
SerialMonitorInterface.println("Initializing BMA250...");
if (!accel_sensor.begin(BMA250_range_2g, BMA250_update_time_64ms)) {
SerialMonitorInterface.println("ERROR: BMA250 not detected!");
while (1);
}
SerialMonitorInterface.println("BMA250 initialized successfully.");
}
void loop() {
accel_sensor.read(); // Read accelerometer data
x = accel_sensor.X;
y = accel_sensor.Y;
z = accel_sensor.Z;
temp = ((accel_sensor.rawTemp * 0.5) + 24.0);
if (x == -1 && y == -1 && z == -1) {
SerialMonitorInterface.println("ERROR: Invalid data.");
return;
}
accelMagnitude = sqrt(sq(x) + sq(y) + sq(z)); // Calculate magnitude
switch (fallState) {
case IDLE:
if (accelMagnitude > impactThreshold) {
SerialMonitorInterface.println("Impact detected!");
impactTime = millis();
fallState = IMPACT_DETECTED;
}
break;
case IMPACT_DETECTED:
if (accelMagnitude < freeFallThreshold) {
SerialMonitorInterface.println("Free fall detected!");
freeFallTime = millis();
fallState = FREE_FALL_DETECTED;
} else if (millis() - impactTime > recoveryDelay) {
SerialMonitorInterface.println("False alarm, resetting to IDLE.");
fallState = IDLE;
}
break;
case FREE_FALL_DETECTED:
if (accelMagnitude < recoveryThreshold && (millis() - freeFallTime) > 500) {
SerialMonitorInterface.println("Fall confirmed!");
fallState = IDLE;
} else if (millis() - freeFallTime > recoveryDelay) {
SerialMonitorInterface.println("False alarm, resetting to IDLE.");
fallState = IDLE;
}
break;
}
showSerial(); // Debugging output
delay(250); // Adjust delay as necessary
}
void showSerial() {
SerialMonitorInterface.print("X = ");
SerialMonitorInterface.print(x);
SerialMonitorInterface.print(" Y = ");
SerialMonitorInterface.print(y);
SerialMonitorInterface.print(" Z = ");
SerialMonitorInterface.print(z);
SerialMonitorInterface.print(" Temp (C) = ");
SerialMonitorInterface.print(temp);
SerialMonitorInterface.print(" Accel Magnitude = ");
SerialMonitorInterface.println(accelMagnitude);
}