Help with adding a sensor

So I have made a program which uses a remote to input a 4 digit code and which then locks the alarm, also sets the red led to red. To disarm the alarm and make the led green you need to re-enter that 4 digit code..

I want to use a ldr sensor (Photocell) to detect movement and trigger a buzzer. I already have a buzzer in the program which makes noise when arming and disarming the alarm.

My question is how would I implement it so when its in an armed state (e.g. when the password is set and red led is on) it triggers and turns the buzzer on making an alarm noise. As well as detecting I want it to stay making the triggered noise until the 4 digit passcode is re-entered and the alarm is set to off (green LED).

Any help would be great, I have attached the code below.

password_lock.ino (4.57 KB)

Have you considered using a PIR sensor? That is the sensor typically used for this application.

The first thing to do (if you haven't already) is to write a simple test sketch using only the LDR to reliably detect motion and indicate the detection by printing something to the Serial Monitor. Only then should you start incorporating the sensor into your project. Save the test sketch for use later if you need to do troubleshooting.

Once you can detect motion, incorporating it into your code will be easy. Basically you want to set a global flag variable when motion is triggered and alarm is armed and control the buzzer based on the state of that flag as well as the current buzzer state. For example:

  if (alarmArmed == true && motionAlarmOn == false && detectMotion() == true) {
    motionAlarmOn = true;
  }

Then we can control the buzzer based on both reasons for triggering an alarm, rather than having the buzzer code duplicated twice:

  if (buzzerOn == false && (motionAlarmOn == true || passwordFailAlarm == true)) {
    digitalWrite(buzzer, HIGH);//buzzer
    buzzerOn = true;
  }