Hey. I have a project in which I check the posture of a person, with a Accelerometer(MPU6050). When the y value (see void GetAngle ()) is between 110 and 90 degrees, the person has a good posture. Everything outside of it is a bad posture. Now I have designed it so that the tool first checks whether the person has a correct or incorrect posture and then sends a message (see case: CHECK), When the person has a Bad posture (y >= 110 || y <= 70) the program switches to case: COUNTDOWN. Now I want to implement a timer in the case COUNTDOWN, that if the person still has a wrong posture after 2 minutes, then the program switches to the case: MESSAGE. How can I implement this timer? I also want to stop the loop when a 0 comes in via the bluetooth. This does not work yet. Thanks in advance for your help.
Below is the full program.
#include <SoftwareSerial.h>
#include <Wire.h>
#include <math.h>
SoftwareSerial BT(0, 1); // RX, TX-pin
int BluetoothData = 0; // BT init state
const int MPU_addr = 0x68;
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
int minVal = 265;
int maxVal = 402;
int StartMillis;
bool StartSign = false;
double x;
double y;
double z;
int c;
enum state { CHECK, COUNTDOWN, MESSAGE };
state current_state;
unsigned long countdownMs;
void setup()
{
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B);
Wire.write(0);
Wire.endTransmission(true);
current_state = CHECK;
}
void GetAngle()
{
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr, 14, true);
AcX = Wire.read() << 8 | Wire.read();
AcY = Wire.read() << 8 | Wire.read();
AcZ = Wire.read() << 8 | Wire.read();
int xAng = map(AcX, minVal, maxVal, -90, 90);
int yAng = map(AcY, minVal, maxVal, -90, 90);
int zAng = map(AcZ, minVal, maxVal, -90, 90);
x = RAD_TO_DEG * (atan2(-yAng, -zAng) + PI); // Rad to degrees
y = RAD_TO_DEG * (atan2(-xAng, -zAng) + PI);
z = RAD_TO_DEG * (atan2(-yAng, -xAng) + PI);
}
void loop()
{
while (1)
{
if (Serial.available())
{
c = Serial.read();
switch (c)
{
case ('1'):
StartSign = true;
Serial.println("program start");
break;
case ('0'):
StartSign = false;
Serial.println("program stopped");
break;
}
if (!Serial.available())
{
while (StartSign == true)
{
GetAngle();
switch (current_state)
{
case CHECK:
if (y >= 110 || y <= 70) // Wrong posture
{
countdownMs = millis();
current_state = COUNTDOWN;
Serial.println("Bad posture");
}
else // Good posture
{
// do nothing;
Serial.println("Good posture");
}
break;
case COUNTDOWN:
if ((y >= 110 || y <= 70)) // Still a wrong posture
{
current_state = MESSAGE;
}
else // Good posture
{
current_state = CHECK;
}
break;
case MESSAGE:
if (y >= 110 || y <= 70)
{
Serial.println("Bad posture");
}
else
{
current_state = CHECK;
Serial.println("Good posture");
}
break;
}
}
}
}
}
}