The idea of the slouch detector is simple. If the current angle sensed by the Circuit Playground (currentAngle) exceeds a preset value (SLOUCH_ANGLE), then we are slouching and should sound an alarm. We can achieve this with a simple modification of our previous sketch. Here's the code.
/////////////////////////////////////////////////////////////////////////////// // Circuit Playground Slouch Detector v1 // // 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) #include <Adafruit_CircuitPlayground.h> #define SLOUCH_ANGLE 10.0 // allowable slouch angle (deg) #define GRAVITY 9.80665 // standard gravity (m/s^s) #define RAD2DEG 52.29578 // convert radians to degrees float currentAngle; /////////////////////////////////////////////////////////////////////////////// void setup() { // Initialize Circuit Playground CircuitPlayground.begin(); } /////////////////////////////////////////////////////////////////////////////// void loop() { // Compute current angle currentAngle = RAD2DEG * asin(-CircuitPlayground.motionZ() / GRAVITY); // Check if slouching if (currentAngle > SLOUCH_ANGLE) { // Sound alarm CircuitPlayground.playTone(800, 500); } }
The preset angle is defined globally at the top of the sketch.
#define SLOUCH_ANGLE 10.0 // allowable slouch angle (deg)
And then a simple if statement is used to check for slouching.
// Check if slouching if (currentAngle > SLOUCH_ANGLE) { // Sound alarm CircuitPlayground.playTone(800, 500); }
With the above sketch loaded and running on the Circuit Playground, you should hear the alarm sound if the tilt (slouch) angle is greater than 10 degrees.
Text editor powered by tinymce.