Skip to content

Instantly share code, notes, and snippets.

@loftywaif002
Created February 6, 2017 23:55
Show Gist options
  • Save loftywaif002/c4ed06e710eab1a9c3b16d78d807a0a6 to your computer and use it in GitHub Desktop.
Save loftywaif002/c4ed06e710eab1a9c3b16d78d807a0a6 to your computer and use it in GitHub Desktop.
knock-lock using servo motor
#include <Servo.h> //Include the Servo Library
Servo myServo;
//Name the input/ouput
const int piezo = A0;
const int switchPin = 2;
const int yellowLed = 3;
const int redLed = 4;
const int greenLed = 5;
//Setuo constants to hold throshold for knocks
int knockVal;
int switchVal;
const int quietKnock = 10;
const int loudKnock = 100;
boolean locked = false;
int numberOfKnocks = 0;
//Connect servo to pin 9, set pin mode to input and output
void setup(){
myServo.attach(9);
pinMode(yellowLed, OUTPUT);
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(switchPin, INPUT);
Serial.begin(9600); //initialize serial communication with the computer
digitalWrite(greenLed,HIGH);
myServo.write(0);
Serial.println("The box is unlocked!");
}
void loop(){
if(locked == false){ //if unlocked lock it using switch
switchVal = digitalRead(switchPin);
if(switchVal == HIGH)
{
locked = true;
digitalWrite(greenLed,LOW); //set green led to low
digitalWrite(redLed,HIGH); //set red led to high
myServo.write(90); //Turn 90 degree
Serial.println("The box is locked!");
delay(1000);
}
} //if ends
if(locked == true){ //if locked, then read knocks using peizo
knockVal = analogRead(piezo);
if(numberOfKnocks < 3 && knockVal > 0)
{
if(checkForKnocks(knockVal)==true){
numberOfKnocks++;
}
Serial.print(3 - numberOfKnocks);
Serial.println("more kncoks to go");
}
if(numberOfKnocks >= 3){
locked = false;
myServo.write(0);
delay(20);
digitalWrite(greenLed,HIGH);
digitalWrite(redLed,LOW);
Serial.println("The box is unlocked!");
}
}
}
boolean checkForKnocks(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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment