The next feature we need to add is a time delay for the alarm. Currently, it sounds the instant the slouch angle is exceeded. But what if you were just leaning over to look at something? We should give you a chance to straighten back up before sounding the alarm.
This idea is shown in the figure below, which shows two cases where the current angle exceeded the slouch angle.
We don't want to sound an alarm for the first case (TIME1). That was a brief event like someone bending over to look at something. However, in the second case, the angle has been exceed for a longer period of time (TIME2). Either the person is slouching or has fallen asleep. In either case, we want to sound the alarm.
To make this work, we need to keep track of time. Specifically, how long we've been slouching, and compare that to a preset value (SLOUCH_TIME). We only sound the alarm if (a) we are slouching, and (b) we've been doing so for longer than this preset value.
Here is the code that adds this feature:
# Circuit Playground Express Slouch Detector v3 # # Push button(s) to set a target angle. # Compute current angle using accelerometer and compare # to preset slouch angle. Sound alarm if slouching after # a preset period of time. # # 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 slouching = False # 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 for slouching if current_angle - target_angle > SLOUCH_ANGLE: if not slouching: slouch_start_time = time.monotonic() slouching = True else: slouching = False # If we are slouching if slouching: # Check how long we've been slouching if time.monotonic() - slouch_start_time > SLOUCH_TIME: # Play a tone cpx.play_tone(800, 0.5)
Text editor powered by tinymce.