#include "LiquidCrystal.h"
#include <string.h>
int PIN_TRIG = 9;
int PIN_ECHO = 10;
LiquidCrystal lcd(2,3,4,5,6,7);
double duration;
double distance;
double threshold = 10;
int counter = 0;
const int tiltPin = 11; // tilt sensor pin is connected to pin 2
int tiltState; // the current reading from the sensor
int lastTiltState = HIGH; // the previous reading from the sensor
unsigned long time = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 20;
int ballcounter = 0; //counts amount of times ball have closed circuit
int tiltcounter = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
lcd.begin(16,2);
//Setting up ballss
pinMode(tiltPin, INPUT); // Set sensor pin as an INPUT pin
digitalWrite(tiltPin, HIGH); // turn on the built in pull-up resistor
// read the state of the tilt sensor
while (ballcounter <= 4){
// read the state of the tilt sensor
tiltState = digitalRead(tiltPin);
// If the sensor really tilted?
if (tiltState != lastTiltState) {
// reset the debouncing timer
time = millis();
tiltcounter++;
}
if ((tiltcounter >= 1) & ((millis() - time) > debounceDelay)) {
ballcounter++;
tiltcounter = 0;
}
// Save the last tiltState so we keep a running tally
lastTiltState = tiltState;
}
}
void loop(){
// Start a new measurement:
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// Read the result:
duration = pulseIn(PIN_ECHO, HIGH);
distance = duration * 0.034 / 2;
lcd.setCursor(0,0);
lcd.print("Dist: ");
lcd.print(distance);
lcd.print("cm ");
delay(300);
if(distance<=threshold){
//run function here
}
}