#include "OneButton.h"
OneButton button1(3, true); //initializing library for double press at pin 3

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;

const int buttonPin = 3; // the pin that the pushbutton is connected to
const int vibPin = 7; // the pin that the vibrator is connected to

int buttonState = 0; // variable for reading the pushbutton status
int x = 0; // variable for storing the last pushbutton status
int y = 0;

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  pinMode(buttonPin, INPUT_PULLUP); // set the pushbutton pin as input
  pinMode(vibPin, OUTPUT); // set the vibrator pin as output

  button1.attachDoubleClick(doubleclick1);

  Serial.begin(9600); // Starts the serial communication
}


void loop() {


  ////measuring distance using sonar sensor
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
  Serial.println(y);

  button1.tick(); //for double press

  ////condition for activating vibration motor
  if (distance < 30){
      // read the current state of the pushbutton
      buttonState = digitalRead(buttonPin);

      // toggle the led for single press and double press
    if (buttonState == HIGH && x == 1 && y == 1){
      digitalWrite(vibPin, HIGH);
      x = 1;
    }
    else if (buttonState == LOW && x == 0 && y == 1) {
        digitalWrite(vibPin, LOW);
      }
      // save the current button state for the next iteration
      x = 0;

    delay(50);
  }
  else{
  digitalWrite(vibPin,LOW);
  x = 1;
  }
}


void doubleclick1() {

if(y == 0){
  y = 1;
}
else if(y == 1){
  y = 0;
}

}
