/* 25/10/2021 * alarmSystemv1 * * Put the led/buzzer and PIR * * * * * pins * 11 buzzer * 12 pir * 13 led */ const int buzzerPin = 11; const int pirPin = 12; const int ledPin = 13; int soundAlarm = 0;//0 alarm is off, 1 alarm is on int alarmState;//used to flash the leds/tone unsigned long alarmTimer; int alarmDelay = 1000; //alarm sounding function void myAlarm(){ if(soundAlarm > 0){//sound alarm if(millis() > alarmTimer){ alarmTimer = millis() + alarmDelay; if(alarmState < 1){ alarmState = 1; digitalWrite(ledPin,HIGH); tone(buzzerPin,500); }else{ alarmState = 0; digitalWrite(ledPin,LOW); tone(buzzerPin,1000); } } } } int soundWarn = 0;//0 warn is off, 1 warn is on int warnState;//used to flash the leds/tone unsigned long warnTimer; //warning sounding function void myWarn(){ if(soundWarn > 0){//sound alarm if(millis() > warnTimer){ if(warnState < 1){ warnState = 1; digitalWrite(ledPin,HIGH); tone(buzzerPin,500); warnTimer = millis() + 100; }else{ warnState = 0; digitalWrite(ledPin,LOW); noTone(buzzerPin); warnTimer = millis() + 500; } } } } int myMovement = 0; unsigned long pirTimer; int pirScanDelay = 100;//time in milliseconds until the next pir scan takes place //pir //function is now controlled by a millis() timer void pirScan(){ if(millis() > pirTimer){ pirTimer = millis() + pirScanDelay; myMovement = digitalRead(pirPin); //Serial.println(myMovement); } } //this function controls what is happening unsigned long controlTimer; int controlState; //0 = no movement, 1 = movement prompt keypad, 2 = alarm sound, 3 = disarmed void alarmControl(){ if(myMovement > 0){//movement detected Serial.print("controlState: "); Serial.println(controlState); switch(controlState){ case 0://if no movement this is a new moment detected...warn to enter code if(millis() > controlTimer){ controlState = 1; controlTimer = millis() + 5000;//5 seconds to enter a code soundWarn = 1; soundAlarm = 0; } break; case 1://ongoing movement... no code entered if(millis() > controlTimer){ controlTimer = millis() + 20000;//alarm to sound 20 seconds controlState = 2; soundWarn = 0; soundAlarm = 1; } break; case 2://alarm is sounding if(millis() > controlTimer){// if the alarm has been sounding for 20 secs...give neigbours a break controlTimer = millis() + 10000;//10 second break in the noise controlState = 0;//start again...could be set to 1 to prompt keycode } break; default: Serial.println("Error...invalid state"); break; } }else{//turn any sounds or leds off as no movement digitalWrite(ledPin,LOW); noTone(buzzerPin); soundWarn = 0; //warning off soundAlarm = 0; //alarm off controlState = 0; } } void setup() { Serial.begin(9600); Serial.println("alarmSystemv1..."); pinMode(buzzerPin,OUTPUT); pinMode(ledPin,OUTPUT); pinMode(pirPin,INPUT); } void loop() { pirScan();//checks for movement alarmControl();//functino controls the system state myAlarm();//sets alarm sound off myWarn();//sets passcode warning sound }