Hi everyone,
I am new in Arduino. I bought the starter kit and I am trying to do the projects which are in the book of starter kit.
I have problem with piezo. I cannot undesrtand what is going on!!
I am on project 12 (if know the book) . You knock the piezo 3 times and then a servo motor is moving.
Anyway, when I knock on the piezo once, then in the serial monitor I see 2 knocks!!!
#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 nunberOfKnocks =0;
void setup()
{
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()
{
if (locked == false)
{
switchVal=digitalRead(switchPin);
if (switchVal == HIGH)
{
nunberOfKnocks=0;
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 (nunberOfKnocks <3 && knockVal >0)
{
if(checkForKnock(knockVal)==true)
{
nunberOfKnocks++;
}
Serial.print(3-nunberOfKnocks);
Serial.println(" more knocks to go");
}
if (nunberOfKnocks >=3)
{
locked=false;
myServo.write(0);
delay(20);
digitalWrite(greenLed, HIGH);
digitalWrite(redLed, LOW);
Serial.println("the box is unlocked");
}
}
}
boolean checkForKnock(int value)
{
Serial.print("In function: value=");
Serial.println(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 kncock value");
Serial.println (value);
return false;
}
}
Can anyone explain me why this happening??? ?