maxime ackermann
Published © CC BY

Motion Detection Security Badge (Prototype)

This is a prototype of a portable motion detection badge designed to protect personal belongings such as backpacks or handbags.

BeginnerWork in progress325
Motion Detection Security Badge (Prototype)

Things used in this project

Story

Read more

Custom parts and enclosures

Licence

README

Schematics

motion alarm scheme

Code

Motion alarm

C/C++
This Arduino code uses an MPU6050 sensor to detect motion. When the push button is pressed, the security system toggles on or off. If activated, it waits 15 seconds before monitoring acceleration and rotation. If significant motion is detected, a buzzer sounds an alarm. An LED indicates whether the system is active. The code also ensures motion is sustained before triggering the alarm.
#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

const int buzzerPin = 2;
const int ledPin = 3;
const int buttonPin = 4;

bool securityActive = false;
bool motionDetected = false;
bool waitingDelay = false;
unsigned long activationTime = 0;

unsigned long sustainedAccelStart = 0;
bool accelSustained = false;

void setup() {
  pinMode(buzzerPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  Wire.begin();
  mpu.initialize();
  Serial.begin(9600);
}

void loop() {
  static bool lastButtonState = HIGH;
  bool currentButtonState = digitalRead(buttonPin);

  if (lastButtonState == HIGH && currentButtonState == LOW) {
    if (!securityActive) {
      securityActive = true;
      waitingDelay = true;
      activationTime = millis();
      digitalWrite(ledPin, HIGH);
      tone(buzzerPin, 2000, 100);
    } else {
      securityActive = false;
      motionDetected = false;
      waitingDelay = false;
      digitalWrite(ledPin, LOW);
      noTone(buzzerPin);
      tone(buzzerPin, 1000, 100);
    }
    delay(200);
  }
  lastButtonState = currentButtonState;

  if (securityActive && !motionDetected) {
    if (waitingDelay && millis() - activationTime >= 15000) {
      waitingDelay = false;
    }

    if (!waitingDelay) {
      int16_t ax, ay, az, gx, gy, gz;
      mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

      float acc = sqrt(ax * ax + ay * ay + az * az) / 16384.0;
      float rot = sqrt(gx * gx + gy * gy + gz * gz) / 131.0;

      if (acc > 1.2 || rot > 50.0) {
        motionDetected = true;
        tone(buzzerPin, 3000);
      }

      if (acc > 1.0) {
        if (!accelSustained) {
          accelSustained = true;
          sustainedAccelStart = millis();
        } else if (millis() - sustainedAccelStart >= 2000) {
          motionDetected = true;
          tone(buzzerPin, 3000);
        }
      } else {
        accelSustained = false;
      }

      Serial.print("Acc: "); Serial.print(acc);
      Serial.print(" | Rot: "); Serial.print(rot);
      Serial.print(" | AccSustained: "); Serial.println(accelSustained);
    }
  }
}

Credits

maxime ackermann
1 project • 1 follower

Comments