After seeing Steve Hoefer's Secret Knock Detecting Lock (http://www.youtube.com/watch?v=zE5PGeh2K9k), I thought I'd make a Secret Knock Box.
Requirements:
I wanted the knock sensor to be more sensitive, so that a modest tap would register;
It should be battery operated (battery inside the box);
It should have a failsafe mode of entry in case you forget the knock or the battery dies;
When you record a new knock, it should remember it even when turned off.
I found ideas for improving the piezo's sensitivity to a knock here:
http://interface.khm.de/index.php/lab/e ... o-element/
I first ran the output of the piezo through an op amp. This helped, but I still couldn't find a good balance between sensitivity to gentle taps and over-sensitivity (when one knock gets read as two.)
I then epoxied a 25 gram fishing weight to a few different piezos. I thought that gluing the piezo directly to the surface might damp out its vibration faster and make it less likely to read multiple knocks from a single tap. For comparison, I also tried a mount similar to the one described in the above setup. By prying the back off of a Radio Shack 273-073 piezo buzzer, I had a piezo that could vibrate independently from the surface it was mounted to. I compared all three setups as shown below:
All three mountings improved the sensitivity, but the one that is not rigidly attached to the knock surface is by far the best. (Just like the web site above suggested.) When that output was fed to the non-inverting input of an op amp with just 2 x gain, there was excellent sensitivity and no mistaking one knock for two.
I included a battery testing circuit so that the LEDs flash to warn of low batteries (so you don't get locked out of the box) and I also have a secret method to jumpstart the box in case the batteries do die, or you forget the code. Here's the secret Just touch a 9 volt battery to the metal LED casings and it will power up the arduino and unlock the box. (I include a diode so that accidentally touching the diodes with a conductor won't short the battery inside, and reversing the polarity of the battery will do no harm.)
Finally, I store the secret code in EEPROM instead of SRAM so that it is retained even when the Arduino is turned off.
Here are pictures of the final setup and a link to a video of it working:
http://www.youtube.com/watch?v=fwCppXGV ... Jy6yLElPeo
Thanks to all of the users on this forum who helped answer my questions and debug my circuit!
Sean
More sensitive knock sensor for secret knock box
Moderators: adafruit_support_bill, adafruit
Please be positive and constructive with your questions and comments.
- spiff
- Posts: 19
- Joined: Mon Feb 21, 2011 2:37 am
- adafruit_support_bill
- Posts: 88093
- Joined: Sat Feb 07, 2009 10:11 am
Re: More sensitive knock sensor for secret knock box
Nice looking box! Thanks for posting
-
- Posts: 18
- Joined: Wed May 09, 2012 9:48 am
Re: More sensitive knock sensor for secret knock box
Spiff,
I've been thinking of putting together the same thing with some of the same mods. Is there more you could share about using the Op Amp, the schematic and code for the dead battery "back door", and perhaps your code for storing in EEPROM.
Any help you could offer would be greatly appreciated.
Rex
I've been thinking of putting together the same thing with some of the same mods. Is there more you could share about using the Op Amp, the schematic and code for the dead battery "back door", and perhaps your code for storing in EEPROM.
Any help you could offer would be greatly appreciated.
Rex
- spiff
- Posts: 19
- Joined: Mon Feb 21, 2011 2:37 am
Re: More sensitive knock sensor for secret knock box
Hi Rex,
It turns out that the modifications I made to increase sensitivity were not necessary. I had been testing the sensitivity of my knock sensor using the sample code from the Arduino site: http://www.arduino.cc/en/Tutorial/Knock/
But there is a bug in this code that makes it much less sensitive. Details about the bug are here:
http://arduino.cc/forum/index.php?PHPSE ... ic=85154.0
I later built a second knock box without the op-amp and without the lead weight attached to the piezo and it works fine.
Below is a circuit diagram for the revised knock box: I've attached my full code below.
EDIT: This is now the correct code for this version of the knock box.
Good luck! Hope this helps.
Spiff
It turns out that the modifications I made to increase sensitivity were not necessary. I had been testing the sensitivity of my knock sensor using the sample code from the Arduino site: http://www.arduino.cc/en/Tutorial/Knock/
But there is a bug in this code that makes it much less sensitive. Details about the bug are here:
http://arduino.cc/forum/index.php?PHPSE ... ic=85154.0
I later built a second knock box without the op-amp and without the lead weight attached to the piezo and it works fine.
Below is a circuit diagram for the revised knock box: I've attached my full code below.
EDIT: This is now the correct code for this version of the knock box.
Code: Select all
/* Code for revised knock box without Op-amp
Detects patterns of knocks and triggers a servo to unlock the box
it if the pattern is correct.
Original code:
By Steve Hoefer http://grathio.com
Version 0.1.10.20.10
Licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0
http://creativecommons.org/licenses/by-nc-sa/3.0/us/
(In short: Do what you want, just be sure to include this line and the four above it, and don't sell it or use it in anything you sell without contacting me.)
Modified by Sean Fottrell in December 2011 to work for a locked box instead of a door lock.
Analog Pin 0: Piezo speaker (connected to ground with 1M pulldown resistor)
Analog Pin 2: Battery Tester
Digital Pin 2: Switch to enter a new code. Short this to +5 Volts to enter programming mode.
Digital Pin 3: Servo connected to latch. (Or a motor controller or a solenoid or other unlocking mechanisim.)
Digital Pin 4: Jump Start detection. (A fail-safe in case you forget the secret knock pattern or the batteries die.)
Digital Pin 5: Red LED.
Digital Pin 6: Green LED.
Update: Nov 09 09: Fixed red/green LED error in the comments. Code is unchanged.
Update: Nov 20 09: Updated handling of programming button to make it more intuitive, give better feedback.
Update: Jan 20 10: Removed the "pinMode(knockSensor, OUTPUT);" line since it makes no sense and doesn't do anything.
*/
// Pin definitions
const int knockSensor = A0; // Piezo sensor on pin 0.
const int battery = A2; // Reads battery voltage divided by 2
const int lockMotor = 2; // Servo used to unlatch the box.
const int programSwitch = 3; // If this is high we program a new code.
const int jumpStart = 4; // Goes high when external battery is contacting LED holders and triggers box to unlock
const int redLED = 5; // Status LED
const int greenLED = 6; // Status LED
// Tuning constants. Could be made vars and hoooked to potentiometers for soft configuration, etc.
const int threshold = 3; // Minimum signal from the piezo to register as a knock
const int rejectValue = 25; // If an individual knock is off by this percentage of a knock we don't unlock..
const int averageRejectValue = 15; // If the average timing of the knocks is off by this percent we don't unlock.
const int knockFadeTime = 150; // milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.)
const int lockTurnTime = 200; // milliseconds that we run the servo to toggle the latch.
const int maximumKnocks = 20; // Maximum number of knocks to listen for.
const int knockComplete = 1200; // Longest time to wait for a knock before we assume that it's finished.
const int locked = 115; // angle of servo when box is locked
const int unlocked = 85; // angle of servo when box is unlocked
const float lowBatteryThreshold = 6.3; // If battery voltage is lower than this (+1), the box will immediately unlock
#include <EEPROM.h> //secret code is stored in EEPROM, so it persists even when box is turned off
// Set up servo to control latch
#include <Servo.h>
Servo lockServo; // creates a servo object to control a servo
// Variables.
int latchPosition = locked; // variable to store the servo position
int knockReadings[maximumKnocks]; // When someone knocks this array fills with delays between knocks.
int knockSensorValue = 0; // Last reading of the knock sensor.
int programButtonPressed = false; // Flag so we remember the programming button setting at the end of the cycle.
void setup() {
pinMode(lockMotor, OUTPUT);
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(programSwitch, INPUT);
pinMode(jumpStart, INPUT);
lockServo.attach(lockMotor, 550, 2550); // attaches the servo on pin "lockMotor" to the servo object; callibrates min and max range of motion
lockServo.write(locked);
delay(lockTurnTime);
lockServo.detach(); //turn off the servo when not in use
testBattery();
// Serial.begin(9600); // Uncomment the Serial.bla lines for debugging.
// Serial.println("Program start."); // but feel free to comment them out after it's working right.
digitalWrite(greenLED, HIGH); // Green LED on, everything is go.
}
void loop() {
testBattery();
if (digitalRead(programSwitch)==HIGH){ // is the program button pressed?
programButtonPressed = true; // Yes, so lets save that state
for (int i = 0; i < 6; i++) { // flash the LEDs for 3 seconds so you can close the box before knocking
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, LOW);
delay(250);
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
delay(250);
}
digitalWrite(redLED, HIGH); // and turn on the red light too so we know we're programming.
digitalWrite(greenLED, LOW);
long now = millis();
while (millis() < (now + 2000)) { // provide 2 seconds after box is closed to start knocking
knockSensorValue = analogRead(knockSensor);
if (knockSensorValue >=threshold){
listenToSecretKnock();
}
}
// Serial.println("Done recording knock.");
}
programButtonPressed = false;
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
// Listen for any knock at all.
knockSensorValue = analogRead(knockSensor);
if (knockSensorValue >=threshold){
listenToSecretKnock();
}
}
// Records the timing of knocks.
void listenToSecretKnock(){
// Serial.println("knock starting");
int i = 0;
// First lets reset the listening array.
for (i=0;i<maximumKnocks;i++){
knockReadings[i]=0;
}
int currentKnockNumber=0; // Incrementer for the array.
unsigned long startTime=millis(); // Reference for when this knock started.
unsigned long now;
digitalWrite(greenLED, LOW); // we blink the LED for a bit as a visual indicator of the knock.
if (programButtonPressed==true){
digitalWrite(redLED, LOW); // and the red one too if we're programming a new knock.
}
delay(knockFadeTime/2); // wait for this peak to fade before we listen to the next one.
digitalWrite(greenLED, HIGH);
delay(knockFadeTime/2);
if (programButtonPressed==true){
digitalWrite(redLED, HIGH);
}
do {
//listen for the next knock or wait for it to timeout.
knockSensorValue = analogRead(knockSensor);
if (knockSensorValue >=threshold){ //got another knock...
//record the delay time.
// Serial.println("knock.");
now=millis();
knockReadings[currentKnockNumber] = now-startTime;
currentKnockNumber ++; //increment the counter
startTime=now;
// and reset our timer for the next knock
digitalWrite(greenLED, LOW);
if (programButtonPressed==true){
digitalWrite(redLED, LOW); // and the red one too if we're programming a new knock.
}
delay(knockFadeTime/2); // again, a little delay to let the knock decay.
digitalWrite(greenLED, HIGH);
delay(knockFadeTime/2);
if (programButtonPressed==true){
digitalWrite(redLED, HIGH);
}
}
now=millis();
//did we timeout or run out of knocks?
} while ((now-startTime < knockComplete) && (currentKnockNumber < maximumKnocks));
//we've got our knock recorded, lets see if it's valid
if (programButtonPressed==false){ // only if we're not in progrmaing mode.
if (validateKnock() == true){
toggleLatch();
} else {
// Serial.println("Secret knock failed.");
digitalWrite(greenLED, LOW); // We didn't unlock, so blink the red LED as visual feedback.
for (i=0;i<4;i++){
digitalWrite(redLED, HIGH);
delay(100);
digitalWrite(redLED, LOW);
delay(100);
}
digitalWrite(greenLED, HIGH);
}
} else { // if we're in programming mode we still validate the knock, we just don't do anything with the lock
validateKnock();
// and we blink the green and red alternately to show that program is complete.
// Serial.println("New lock stored.");
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
for (i=0;i<3;i++){
delay(100);
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, LOW);
delay(100);
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
}
}
}
// Runs the motor (or whatever) to unlock the door.
void toggleLatch(){
lockServo.attach(lockMotor, 550, 2550); // attaches the servo on pin "lockMotor" to the servo object
int i=0;
if (latchPosition == locked) { // Toggle the latch to the other position
lockServo.write(unlocked);
latchPosition = unlocked;
// Serial.println("unlocked");
} else if (latchPosition == unlocked) {
lockServo.write(locked);
latchPosition = locked;
// Serial.println("locked");
}
digitalWrite(greenLED, HIGH); // And the green LED too.
delay (lockTurnTime); // Wait a bit.
lockServo.detach(); // turn off servo to save energy
// Blink the green LED a few times for more visual feedback.
for (i=0; i < 5; i++){
digitalWrite(greenLED, LOW);
delay(100);
digitalWrite(greenLED, HIGH);
delay(100);
}
}
// Sees if our knock matches the secret.
// returns true if it's a good knock, false if it's not.
// todo: break it into smaller functions for readability.
boolean validateKnock(){
int i=0;
// simplest check first: Did we get the right number of knocks?
int currentKnockCount = 0;
int secretKnockCount = 0;
int maxKnockInterval = 0; // We use this later to normalize the times.
for (i=0;i<maximumKnocks;i++){
if (knockReadings[i] > 0){
currentKnockCount++;
}
if (EEPROM.read(i) > 0){ //todo: precalculate this.
secretKnockCount++;
}
if (knockReadings[i] > maxKnockInterval){ // collect normalization data while we're looping.
maxKnockInterval = knockReadings[i];
}
}
// If we're recording a new knock, save the info and get out of here.
if (programButtonPressed==true){
for (i=0;i<maximumKnocks;i++){ // normalize the times
EEPROM.write(i, map(knockReadings[i],0, maxKnockInterval, 0, 100));
}
// And flash the lights in the recorded pattern to let us know it's been programmed.
digitalWrite(greenLED, LOW);
digitalWrite(redLED, LOW);
delay(1000);
digitalWrite(greenLED, HIGH);
digitalWrite(redLED, HIGH);
delay(50);
for (i = 0; i < maximumKnocks ; i++){
digitalWrite(greenLED, LOW);
digitalWrite(redLED, LOW);
// only turn it on if there's a delay
if (EEPROM.read(i) > 0){
delay( map(EEPROM.read(i), 0, 100, 0, maxKnockInterval)); // Expand the time back out to what it was. Roughly.
digitalWrite(greenLED, HIGH);
digitalWrite(redLED, HIGH);
}
delay(50);
}
return false; // We don't unlock the door when we are recording a new knock.
}
if (currentKnockCount != secretKnockCount){
return false;
}
/* Now we compare the relative intervals of our knocks, not the absolute time between them.
(ie: if you do the same pattern slow or fast it should still open the door.)
This makes it less picky, which while making it less secure can also make it
less of a pain to use if you're tempo is a little slow or fast.
*/
int totaltimeDifferences=0;
int timeDiff=0;
for (i=0;i<maximumKnocks;i++){ // Normalize the times
knockReadings[i]= map(knockReadings[i],0, maxKnockInterval, 0, 100);
timeDiff = abs(knockReadings[i]-EEPROM.read(i));
if (timeDiff > rejectValue){ // Individual value too far out of whack
return false;
}
totaltimeDifferences += timeDiff;
}
// It can also fail if the whole thing is too inaccurate.
if (totaltimeDifferences/secretKnockCount>averageRejectValue){
return false;
}
return true;
}
// Tests battery voltage and unlocks box if battery is getting low
void testBattery() {
//Read in three values and sort them to find the median
int batteryValue1 = analogRead(battery);
delay(10);
int batteryValue2 = analogRead(battery);
delay(10);
int batteryValue3 = analogRead(battery);
int temp; // temporary value
if (batteryValue1 > batteryValue2) {
temp = batteryValue1;
batteryValue1 = batteryValue2;
batteryValue2 = temp;
}
if (batteryValue2 > batteryValue3) {
temp = batteryValue2;
batteryValue2 = batteryValue3;
batteryValue3 = temp;
}
if (batteryValue1 > batteryValue2) {
temp = batteryValue1;
batteryValue1 = batteryValue2;
batteryValue2 = temp;
}
//batteryValue2 is now the median
float batteryVoltage;
batteryVoltage = float(batteryValue2)/1023*10;
// Emergency over-ride in case of dead batteries or if you forget the secret code
if (digitalRead(jumpStart) == HIGH) { // External battery touches LED housings
toggleLatch();
}
if (batteryVoltage <= lowBatteryThreshold) {
digitalWrite(redLED, LOW); // Conserve Power
digitalWrite(greenLED, LOW);
if (latchPosition == locked) { // Unlock box
toggleLatch();
}
while(1) {
if (digitalRead(jumpStart) == HIGH) { // External battery has contacted LED housings
toggleLatch(); // causing an over-ride that unlocks the box
// so that you can replace the batteries
}
digitalWrite(redLED, HIGH); // Flash LEDs
digitalWrite(greenLED, HIGH);
delay(250);
digitalWrite(redLED, LOW);
digitalWrite(greenLED, LOW);
delay(250);
}
}
}
Spiff
-
- Posts: 18
- Joined: Wed May 09, 2012 9:48 am
Re: More sensitive knock sensor for secret knock box
Thanks Spiff, I'll give this a look and digest it. I'm a bit of a electronics/arduino/programming noob but I think I can sort this out. I appreciate you sharing your work.
If you don't mind, I have a couple of quick questions that occur to me:
1). What is the purpose of the zener diode across the piezo buzzer is that just to eliminate possible voltage spikes that could damage the arduino with too much input voltage at pin A0?
2). Also, I was thinking about an almost identical backdoor approach and was going to put four metal feet on the bottom of the box. One foot will be wired to ground and the other will power to the arduino and set the backdoor latch open pin to HIGH (like your pin 4 "jumpstart"). I was worried about too much voltage coming in from a 9 volt battery to the "jumpstart" pin so I guess that the 5v zener diode and the resistors are there is to drop that voltage down to an acceptable level. Is that correct?
3). What kind of diode should be used between the Red LED case and the Arduino Vin?
4). Finally, is there no need for a diode basically going the other direction between the Green LED's case and ground? Nothing would happen if +9v was applied across this into ground? As I said, I'm a bit of a noob.
Finally, I'll probably add some kind of external switch to turn the box on so that battery usage is less of an issue (as a result I may ditch your use of A2 and the battery tester sequence - but it is a cool addition). The user would have to turn the box on and let the arduino power up before you get an LED indicating that the system is ready to listen for a knock. I'd like to use a momentary switch to start things and then if it didn't hear anything for x amount of time the whole system would power all the way back down. I haven't figured that out yet - but it seems like it should be doable.
Cheers,
Rex
If you don't mind, I have a couple of quick questions that occur to me:
1). What is the purpose of the zener diode across the piezo buzzer is that just to eliminate possible voltage spikes that could damage the arduino with too much input voltage at pin A0?
2). Also, I was thinking about an almost identical backdoor approach and was going to put four metal feet on the bottom of the box. One foot will be wired to ground and the other will power to the arduino and set the backdoor latch open pin to HIGH (like your pin 4 "jumpstart"). I was worried about too much voltage coming in from a 9 volt battery to the "jumpstart" pin so I guess that the 5v zener diode and the resistors are there is to drop that voltage down to an acceptable level. Is that correct?
3). What kind of diode should be used between the Red LED case and the Arduino Vin?
4). Finally, is there no need for a diode basically going the other direction between the Green LED's case and ground? Nothing would happen if +9v was applied across this into ground? As I said, I'm a bit of a noob.
Finally, I'll probably add some kind of external switch to turn the box on so that battery usage is less of an issue (as a result I may ditch your use of A2 and the battery tester sequence - but it is a cool addition). The user would have to turn the box on and let the arduino power up before you get an LED indicating that the system is ready to listen for a knock. I'd like to use a momentary switch to start things and then if it didn't hear anything for x amount of time the whole system would power all the way back down. I haven't figured that out yet - but it seems like it should be doable.
Cheers,
Rex
-
- Posts: 18
- Joined: Wed May 09, 2012 9:48 am
Re: More sensitive knock sensor for secret knock box
I might look at using one of these for my power on/off:
http://www.instructables.com/id/Using-P ... ects-to-p/
http://www.instructables.com/id/Using-P ... ects-to-p/
-
- Posts: 4
- Joined: Thu Nov 07, 2013 2:49 pm
Re: More sensitive knock sensor for secret knock box
Bit of power saving for the "Knock-lock"
I haven't yet got enough bits to 'knock' one together, but the solenoid...Power saving...
I think it'd be possible to save a bit of power.
(Oh, firstly, the darlington is shown the wrong way round on the schematic....remember, in transistors and diodes - except Zener, Impatt or Gunn - the arrow points AWAY from positive to conduct)
From the Schematic, not the Fritzing diagram, which is correct - If the Trinket's "batt+" to the 12V 'node' has a resistor inserted between (maybe 47 ohms) it, straight outta the chip, and the 'top' of the diode has a big 'friendly' electrolytic capacitor to ground connected to it...
Y'see, most of the current drawn by the solenoid is the initial inrush current. Once the solenoid is energised, then a much lower current is needed to hold it. If you stuck a, say, 1,000 microfarad capacitor there, that'd maybe give enough charge to pull the solenoid into the inductor. It'd be already charged through the 47 - ohm resistor. Once there, it needs less current, which it gets from the resistor.
A 47-ohm, ½-watt jobbie might be enough. If not, try a 22-ohm. Or try higher. Might just give a bit longer battery life.
But maybe less knocks/minute...
Just a thought.
I haven't yet got enough bits to 'knock' one together, but the solenoid...Power saving...
I think it'd be possible to save a bit of power.
(Oh, firstly, the darlington is shown the wrong way round on the schematic....remember, in transistors and diodes - except Zener, Impatt or Gunn - the arrow points AWAY from positive to conduct)
From the Schematic, not the Fritzing diagram, which is correct - If the Trinket's "batt+" to the 12V 'node' has a resistor inserted between (maybe 47 ohms) it, straight outta the chip, and the 'top' of the diode has a big 'friendly' electrolytic capacitor to ground connected to it...
Y'see, most of the current drawn by the solenoid is the initial inrush current. Once the solenoid is energised, then a much lower current is needed to hold it. If you stuck a, say, 1,000 microfarad capacitor there, that'd maybe give enough charge to pull the solenoid into the inductor. It'd be already charged through the 47 - ohm resistor. Once there, it needs less current, which it gets from the resistor.
A 47-ohm, ½-watt jobbie might be enough. If not, try a 22-ohm. Or try higher. Might just give a bit longer battery life.
But maybe less knocks/minute...
Just a thought.
Please be positive and constructive with your questions and comments.