Slouch Detector v2

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 current_angle as target_angle.
  • Do math shown above to compute slouch_angle.
  • Compare slouch_angle to preset value, SLOUCH_ANGLE.
  • Sound alarm if vaue exceeded.

Here is the code that adds this feature:

Download: file
# 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
# MIT License (https://opensource.org/licenses/MIT)
import time
import math
from adafruit_circuitplayground.express import cpx

SLOUCH_ANGLE    = 10.0
SLOUCH_TIME     = 3
GRAVITY         = 9.80665

# Initialize target angle to zero.
target_angle = 0

# Loop forever
while True:
    # Compute current angle
    current_angle = math.asin(-cpx.acceleration[2] / GRAVITY)
    current_angle = math.degrees(current_angle)
    
    # Set target angle on button press
    if cpx.button_a or cpx.button_b:
        target_angle = current_angle
        cpx.play_tone(900,0.1)
        time.sleep(0.1)
        cpx.play_tone(900,0.1)
        time.sleep(0.1)
        
    # Check if slouching
    if current_angle - target_angle > SLOUCH_ANGLE:
        cpx.play_tone(800, 0.5)
This guide was first published on Dec 21, 2016. It was last updated on Dec 21, 2016. This page (Slouch Detector v2) was last updated on Aug 08, 2019.