While the v1 version of our slouch detector works, there are a few features we need to add. The first is to account for the fact that the Circuit Playground may not sit perfectly vertical when being worn.

To deal with this, we need to generalize the problem a little further. Here is another version of our SFoE with some more angle definitions.

The dashed lines represent the SFoE sitting with good posture, which we are defining as the targetAngle. We want to determine if the SFoE exceeds the slouchAngle (SLOUCH_ANGLE), but the Circuit Playground only reports the angle relative to the vertical line, currentAngle.

If we could determine the targetAngle, we could compute the slouchAngle from the currentAngle as follows:

currentAngle = targetAngle + slouchAngle

(rearrange)

slouchAngle = targetAngle - currentAngle

So how do we come up with the targetAngle? We will make this settable by using the buttons on the Circuit Playground. The idea will be:

• Attach Circuit Playground to clothing.
• Sit with good posture.
• Press either button to set currentAngle as targetAngle.
• Do math shown above to compute slouchAngle.
• Compare slouchAngle to preset value, SLOUCH_ANGLE.
• Sound alarm if vaue exceeded.

Here is the code that adds this feature:

```///////////////////////////////////////////////////////////////////////////////
// Circuit Playground Slouch Detector v2
//
// Push button(s) to set a target angle.
// Compute current angle using accelerometer and compare
// to preset slouch angle. Sound alarm if slouching.
//
// Author: Carter Nelson

#define SLOUCH_ANGLE        10.0      // allowable slouch angle (deg)
#define GRAVITY             9.80665   // standard gravity (m/s^s)

float currentAngle;
float targetAngle;

///////////////////////////////////////////////////////////////////////////////
void setup() {
// Initialize Circuit Playground
CircuitPlayground.begin();

// Initialize target angle to zero.
targetAngle = 0;
}

///////////////////////////////////////////////////////////////////////////////
void loop() {
// Compute current angle
currentAngle = RAD2DEG * asin(-CircuitPlayground.motionZ() / GRAVITY);

// Set target angle on button press
if ((CircuitPlayground.leftButton()) || (CircuitPlayground.rightButton())) {
targetAngle = currentAngle;
CircuitPlayground.playTone(900,100);
delay(100);
CircuitPlayground.playTone(900,100);
delay(100);
}

// Check if slouching
if (currentAngle - targetAngle > SLOUCH_ANGLE) {
// Sound alarm
CircuitPlayground.playTone(800, 500);
}
}```

Now you can press either button to set the targetAngle to the currentAngle. Two small beeps will sound to confirm this.

This guide was first published on Dec 21, 2016. It was last updated on Mar 08, 2024.

This page (Slouch Detector v2) was last updated on Dec 15, 2016.