/*
* Sources:
* https://arduinogetstarted.com/tutorials/arduino-button-toggle-led
* https://arduinogetstarted.com/tutorials/arduino-button-servo-motor
* https://roboticadiy.com/how-to-use-buzzer-with-ultrasonic-sensor/
* https://www.arduino.cc/reference/en/libraries/ezbutton/
*/
// include the libraries used
#include <ezButton.h>
#include <Servo.h>
// define constants
const int BUTTON_PINoff = 2; // the number of the pushbutton pin
const int BUZZER_PIN = 4; // the number of the Buzzer pin
const int BUTTON_PIN = 7; // the number of the pushbutton pin
const int LED_PIN = 8; // the number of the LED pin
const int SERVO_PIN = 9; // the number of the Servo pin
const int ECHO_PIN = 12; // the number of the Echo pin
const int TRIG_PIN = 13; // the number of the Trig pin
/// SERVO
Servo servo; // create servo object
int pos = 0; // define initial position of servo
/// BUTTON
ezButton button(BUTTON_PIN); // create ezButton object that attach to pin 7;
ezButton buttonOff(BUTTON_PINoff); // create ezButton object that attach to pin 7;
// define variables
int ledState = LOW; // the current state of LED
int angle = 90; // the current state of Servo
long duration, distance; // variables for simple distance function
/// INITIALIZATION
void setup() {
Serial.begin(9600); // initialize serial
pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode
button.setDebounceTime(10); // set debounce time to 50 milliseconds
buttonOff.setDebounceTime(10); // set debounce time to 50 milliseconds
servo.attach(SERVO_PIN); // attach servo to pin 9
pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode
pinMode(ECHO_PIN , INPUT); // set arduino pin to input mode
}
/// MAIN LOOP
void loop() {
button.loop(); // MUST call the loop() function first
if(button.isPressed())
{
// LED - turn on
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
Serial.println("The light is on");
// SERVO - open the gate
angle = 0;
servo.write(angle);
Serial.println("The gate is open");
// Buzzer loop - print outside so only once
Serial.println("The buzzer is on");
while(true)
{
// setup of the input frequency
digitalWrite(TRIG_PIN, HIGH);
//delayMicroseconds(50);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH); // definition of the output
distance = (duration/2) / 29.1; // function for the distance - decision parameter
if (distance < 200 && distance > 10)
{
tone(BUZZER_PIN,500,distance/20);
//millis(distance/2);
Serial.println(distance/2);
}
else if(distance <=10)
{
tone(BUZZER_PIN,500,distance/6);
//millis(10);
}
// no buzzer tone at 390+
else
{
noTone(BUZZER_PIN);
}
buttonOff.loop();
if(buttonOff.isPressed()) // if the second button is pushed, the while loop stops
break;
}
//Turn off the LED, the buzzer and close the gate
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
Serial.println("The light is off");
angle = 90;
servo.write(angle);
Serial.println("The gate is closed");
noTone(BUZZER_PIN);
Serial.println("The buzzer is off");
}
}