Hello!
I am trying to create the proper code for an Arduino nano and mpu6050 to detect if someone is slouching. The location of the mpu6050 will be located on their neck through a 3d printed case. However, the math to detect if they are slouching is never right nor works. I think it's the math. Would anyone be willing to look over it? Here it is:
#include <Wire.h>
#include <MPU6050.h>
#include <math.h>
#include <SPI.h>
#define buzzer 12
// an MPU6050 object
MPU6050 IMU;
int status;
int LED1 = 3; // Red
int LED2 = 4; // Green
int LED3 = 5; // White
int buzzstate = 0;
void setup() {
Serial.begin(9600);
Wire.begin();
// Initialize MPU6050
IMU.initialize();
if (!IMU.testConnection()) {
Serial.println("IMU initialization unsuccessful");
Serial.println("Check IMU wiring or try cycling power");
while(1) {}
}
// Setting the accelerometer sensitivity (plus or minus 8g)
IMU.setFullScaleAccelRange(MPU6050_ACCEL_FS_8);
// Setting the gyroscope sensitivity (plus or minus 500 degrees per second)
IMU.setFullScaleGyroRange(MPU6050_GYRO_FS_500);
pinMode(LED1, OUTPUT); // Red
pinMode(LED2, OUTPUT); // Green
pinMode(LED3, OUTPUT); // Yellow
digitalWrite(LED1, LOW); // Red
digitalWrite(LED2, LOW); // Green
digitalWrite(LED3, LOW); // Yellow
pinMode(buzzer, OUTPUT); // Buzzer
digitalWrite(buzzer, 0);
}
void loop() {
char data;
if (Serial.available() > 0) {
data = Serial.read();
while (data != '0') {
IMU.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); // Update sensor data
float accelZ = az / 16384.0; // Convert raw accel data to g's
if (accelZ >= 0 && accelZ < 3.5) {
Serial.print("Good posture\n");
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, HIGH);
digitalWrite(buzzer, 0);
buzzstate = 0;
} else if (accelZ >= 3.5 && accelZ < 6.0) {
Serial.print("Okay Posture\n");
digitalWrite(LED1, HIGH);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
digitalWrite(buzzer, 0);
buzzstate = 0;
} else if (accelZ >= 6.0 || accelZ <= -2) {
Serial.print("Bad posture\n");
digitalWrite(LED1, LOW);
digitalWrite(LED2, HIGH);
digitalWrite(LED3, LOW);
if (!buzzstate) {
delay(5000);
}
digitalWrite(buzzer, 1);
buzzstate = 1;
}
delay(1000);
if (Serial.available() > 0) {
data = Serial.read();
}
}
if (data == '0') {
Serial.println("Device switched off.\n");
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
digitalWrite(buzzer, 0);
}
}
}
Thank you ahead of time ![]()