@@ -77,6 +77,12 @@ bool bAwaitingConnection = false;
7777bool bTiltDetected = false;
7878bool bEnableTiltDetection = true;
7979
80+ // Define thresholds and deadzone for tilt detection to compensate for noise/drift
81+ // 20° corresponds to approx. 960
82+ #define TILT_THRESHOLD_UPPER 970
83+ #define TILT_THRESHOLD_LOWER 935
84+ #define GYRO_STABLE_THRESHOLD 3
85+
8086// Default LED effect when no other effect is set
8187LedEffect_t ledEffectDefault = {0 };
8288// LED state set by the user
@@ -885,24 +891,30 @@ zaf_event_distributor_app_proprietary(event_nc_t *event)
885891 abs (gyro_reading .y - last_gyro_reading .y ) < 25 &&
886892 abs (gyro_reading .z - last_gyro_reading .z ) < 25 ) {
887893 stable_gyro_readings ++ ;
894+ // Prevent overflows
895+ if (stable_gyro_readings > 0xffff ) {
896+ stable_gyro_readings = GYRO_STABLE_THRESHOLD ;
897+ }
888898 } else {
889899 stable_gyro_readings = 0 ;
890900 }
891901 last_gyro_reading = gyro_reading ;
892902
893- if (stable_gyro_readings < 3 ) {
903+ if (stable_gyro_readings < GYRO_STABLE_THRESHOLD ) {
894904 // Not enough stable readings, ignore this one
895905 return ;
896906 }
897907
898908 // Indicate bad orientation (more than 20° from vertical) in calibration mode
899- if (gyro_reading .z < -960 || gyro_reading .z > 960 ) {
900- if (bTiltDetected ) {
901- // Mark the user LED effect as modified, so it gets used again
902- trigger_led_effect_refresh ();
903- }
909+ if (bTiltDetected && (gyro_reading .z < - TILT_THRESHOLD_UPPER || gyro_reading .z > TILT_THRESHOLD_UPPER )) {
910+ // Tilt no longer detected when crossing the upper threshold
904911 bTiltDetected = false;
905- } else if (!bTiltDetected ) {
912+ // Mark the user LED effect as modified, so it gets used again
913+ trigger_led_effect_refresh ();
914+ } else if (!bTiltDetected && gyro_reading .z > - TILT_THRESHOLD_LOWER && gyro_reading .z < TILT_THRESHOLD_LOWER ) {
915+ // Tilt no longer detected when crossing the lower threshold
916+ bTiltDetected = true;
917+ // Indicate incorrect tilt using the LED
906918 LedEffectFade_t fade = {
907919 .color = red ,
908920 .brightness = 0xff ,
@@ -914,7 +926,6 @@ zaf_event_distributor_app_proprietary(event_nc_t *event)
914926 .type = LED_EFFECT_FADE ,
915927 .effect .fade = fade
916928 };
917- bTiltDetected = true;
918929 }
919930
920931 if (!bRequestGyroMeasurement ) {
0 commit comments