Project 12 - solution for servo interference

Hi,

If you have problems with “project 12 - knock lock” it might be because of servo interference.

When I use other code to test my piezo, it shows value 0. When I use original code from book - piezo goes crazy and all the time reads something between 50-200, even without touching it. Yellow LED blinks from time to time and I hear a little sound from servo. This way box opens itself after few seconds. How to solve it?

I used myServo.detach(); after I locked box by pressing button. So code should be as below:

if(switchVal == HIGH){
locked = true;
digitalWrite(greenLed,LOW);
digitalWrite(redLed,HIGH);
myServo.write(90);
Serial.println(“The box is locked!”);
delay (500);
myServo.detach();
delay(1000);
}

I also added more delay, but it doesn’t matter I think. Just to make sure servo is off and calm ;-).

Later without servo involvment my piezo is reading sounds and after 3 knocks you just attach servo again in code as below:

if(numberOfKnocks >= 3){
locked = false;
myServo.attach(9);
myServo.write(0);

I set knock low and high value between 20 and 200, but it is individual I think.

Moreover I added condition that knock value must be at least 20, not above 0.

knockVal = analogRead(piezo);
if(numberOfKnocks < 3 && knockVal > 20){
if(checkForKnock(knockVal) == true){
numberOfKnocks++;

Another problem that somebody already mentioned in some video was that after first opening need to reset knocks:

Serial.println(“The box is unlocked!”);
numberOfKnocks = 0;

Hope it will be helpful for someone!