Hi,
I need help to write a code for my project. I have complied two different codes which work for me so far, I have already created a successful project which can detect motion and triggers an buzzer which then needs to be turned off by pressing the switch, this is shown in PIR alarm code, below.
The other code is the 4x4 keypad, I have tested that all buttons work within this code. shown in 4x4 keypad code.
Now, I want to write a code for my PIR motion based security alarm which is activated and deactivated by a 4x4 keypad. I want to set a password which will activate the motion sensor/alarm, if motion is detected then the alarm goes off. To turn off the alarm you must enter the same password.
PIR Alarm:
void setup() {
// Declaring Pins
const int buzzerPin = 5;
const int ledPin = 6;
const int motionPin = 7;
const int buttonPin = 12;
// Setting Buzzer mode to False
boolean buzzer_mode = false;
// For LED
int ledState = LOW;
long previousMillis = 0;
long interval = 100; // Interval at which LED blinks
void setup() {
pinMode(ledPin,OUTPUT);
pinMode(buzzerPin,OUTPUT);
pinMode(buttonPin, INPUT);
// Wait before starting the alarm
delay(5000);
}
void loop() {
// To chech whether the motion is detected or not
if (digitalRead(motionPin)) {
buzzer_mode = true;
}
}
// If alarm mode is on,blink LED
if (buzzer_mode){
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// Switch the LED
digitalWrite(ledPin, ledState);
}
tone(buzzerPin,1000);
}
// If alarm is off
if (buzzer_mode == false) {
// No tone & LED off
noTone(buzzerPin);
digitalWrite(ledPin, LOW);
}
// If our button is pressed Switch off ringing and Setup
int button_state = digitalRead(buttonPin);
if (button_state) {buzzer_mode = false;}
}
}
void loop() {
// put your main code here, to run repeatedly:
}
4x4 keypad code:
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keyMap[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {3, 4, 5, 6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {7, 8, 9, 10}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keyMap), rowPins, colPins, ROWS, COLS );
void setup(){
Serial.begin(9600);
}
void loop(){
char key = keypad.getKey();
if (key){
Serial.println(key);
}
}