Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int time1 = 0;
- int time2 = 0;
- int distance1 = 0;
- int distance2 = 0;
- int threshold = 10;
- int counter = 0;
- const int timeout = 3000;
- bool flag1 = false;
- bool flag2 = false;
- void loop(){
- // get distances
- distance1 = getDistance(1);
- distance2 = getDistance(2);
- // check if distance from first sensor crosses threshold
- if(distance1 < threshold){
- // if so, record the time
- time1 = millis();
- // and set the triggered flag to true
- flag1 = true;
- }
- // check if distance from second sensor crosses threshold
- if(distance2 < threshold){
- // if so, record the time
- time2 = millis();
- // and set the triggered flag to true
- flag2 = true;
- }
- // if BOTH triggered flags are true
- if(flag1 && flag2){
- // find the time between trigger events
- int difference = time1 - time2;
- // if the difference is positive, someone's going in, so increment counter
- if(difference > 0){
- counter++;
- }
- // otherwise subtract
- else{
- counter--;
- }
- // clear all the flags
- clearFlags();
- }
- // if ONE sensor is triggered
- if(flag1 || flag2){
- // determine if one or the other has not been triggered for the timeout period
- if(millis()-time1 > timeout || millis()-time2 > timeout){
- // if longer than timeout, clear flags
- clearFlags();
- }
- }
- }
- float clearFlags(){
- time1 = 0;
- time2 = 0;
- flag1 = 0;
- flag2 = 0;
- }
- float getDistance (int whichSensor){
- int _trigPin;
- int _echoPin;
- if (whichSensor == 1){
- _trigPin = 4;
- _echoPin = 5;
- }
- if (whichSensor == 2){
- _trigPin = 2;
- _echoPin = 3;
- }
- digitalWrite(_trigPin, LOW);
- delay(2);
- digitalWrite(_trigPin, HIGH);
- delay(10);
- digitalWrite(_trigPin, LOW);
- int duration = pulseIn(_echoPin, HIGH);
- double distance = (duration/2) *0.000344;
- return distance;
- }
Add Comment
Please, Sign In to add comment