-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnock_Lock.ino
More file actions
81 lines (73 loc) · 1.77 KB
/
Knock_Lock.ino
File metadata and controls
81 lines (73 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <Servo.h>
Servo myServo;
const int piezo = A0;
const int switchPin = 2;
const int yellowLed = 3;
const int greenLed = 4;
const int redLed = 5;
int knockVal;
int switchVal;
const int quietKnock = 10;
const int loudKnock = 100;
boolean locked = false;
int numberOfKnocks = 0;
void setup() {
// put your setup code here, to run once:
myServo.attach(9);
pinMode(yellowLed, OUTPUT);
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(switchPin, INPUT);
Serial.begin(9600);
digitalWrite(greenLed, HIGH);
myServo.write(0);
Serial.println("The box is unlocked!");
}
void loop() {
// put your main code here, to run repeatedly:
if(locked == false){
switchVal = digitalRead(switchPin);
if(switchVal == HIGH){
locked = true;
digitalWrite(greenLed, LOW);
digitalWrite(redLed, HIGH);
myServo.write(90);
Serial.println("The box is locked!");
delay(1000);
}
}
if(locked == true){
knockVal = analogRead(piezo);
if(numberOfKnocks < 3 && knockVal > 0){
if(checkForKnock(knockVal) == true){
numberOfKnocks++;
}
Serial.print(3-numberOfKnocks);
Serial.println(" more knocks to go");
}
if(numberOfKnocks >= 3){
locked = false;
numberOfKnocks = 0;
myServo.write(0);
delay(20);
digitalWrite(greenLed, HIGH);
digitalWrite(redLed, LOW);
Serial.println("The box is unlocked!");
}
}
}
boolean checkForKnock(int value){
if(value > quietKnock && value < loudKnock){
digitalWrite(yellowLed, HIGH);
delay(50);
digitalWrite(yellowLed, LOW);
Serial.print("Valid knock of value ");
Serial.println(value);
return true;
}
else{
Serial.print("Bad knock value ");
Serial.println(value);
return false;
}
}