#include <Servo.h>
#define SENSOR_PIN 2 // Arduino pin connected to sound sensor's pin
#define SERVO_PIN 9 // Arduino pin connected to servo motor's pin
#define TIME_PERIOD 10000 // in milliseconds
Servo servo; // create servo object to control a servo
// variables will change:
int lastSoundState; // the previous state of sound sensor
int currentSoundState; // the current state of sound sensor
void setup() {
Serial.begin(9600); // initialize serial
pinMode(SENSOR_PIN, INPUT); // set arduino pin to input mode
servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object
servo.write(0);
currentSoundState = digitalRead(SENSOR_PIN);
}
void loop() {
lastSoundState = currentSoundState; // save the last state
currentSoundState = digitalRead(SENSOR_PIN); // read new state
if (lastSoundState == HIGH && currentSoundState == LOW) { // state change: HIGH -> LOW
Serial.println("The sound has been detected");
servo.write(180); // control servo motor to 180 degree
delay(TIME_PERIOD);
servo.write(0); // control servo motor to 0 degree
}
}