Guest User

Untitled

a guest
Dec 10th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. int time1 = 0;
  2. int time2 = 0;
  3. int distance1 = 0;
  4. int distance2 = 0;
  5. int threshold = 10;
  6. int counter = 0;
  7. const int timeout = 3000;
  8. bool flag1 = false;
  9. bool flag2 = false;
  10.  
  11. void loop(){
  12.  
  13. // get distances
  14. distance1 = getDistance(1);
  15. distance2 = getDistance(2);
  16.  
  17. // check if distance from first sensor crosses threshold
  18. if(distance1 < threshold){
  19. // if so, record the time
  20. time1 = millis();
  21. // and set the triggered flag to true
  22. flag1 = true;
  23. }
  24.  
  25. // check if distance from second sensor crosses threshold
  26. if(distance2 < threshold){
  27. // if so, record the time
  28. time2 = millis();
  29. // and set the triggered flag to true
  30. flag2 = true;
  31. }
  32.  
  33. // if BOTH triggered flags are true
  34. if(flag1 && flag2){
  35. // find the time between trigger events
  36. int difference = time1 - time2;
  37. // if the difference is positive, someone's going in, so increment counter
  38. if(difference > 0){
  39. counter++;
  40. }
  41. // otherwise subtract
  42. else{
  43. counter--;
  44. }
  45. // clear all the flags
  46. clearFlags();
  47. }
  48. // if ONE sensor is triggered
  49. if(flag1 || flag2){
  50. // determine if one or the other has not been triggered for the timeout period
  51. if(millis()-time1 > timeout || millis()-time2 > timeout){
  52. // if longer than timeout, clear flags
  53. clearFlags();
  54. }
  55. }
  56.  
  57. }
  58.  
  59. float clearFlags(){
  60. time1 = 0;
  61. time2 = 0;
  62. flag1 = 0;
  63. flag2 = 0;
  64. }
  65.  
  66. float getDistance (int whichSensor){
  67.  
  68. int _trigPin;
  69. int _echoPin;
  70.  
  71. if (whichSensor == 1){
  72. _trigPin = 4;
  73. _echoPin = 5;
  74. }
  75.  
  76. if (whichSensor == 2){
  77. _trigPin = 2;
  78. _echoPin = 3;
  79. }
  80.  
  81. digitalWrite(_trigPin, LOW);
  82. delay(2);
  83. digitalWrite(_trigPin, HIGH);
  84. delay(10);
  85. digitalWrite(_trigPin, LOW);
  86.  
  87. int duration = pulseIn(_echoPin, HIGH);
  88. double distance = (duration/2) *0.000344;
  89.  
  90. return distance;
  91. }
Add Comment
Please, Sign In to add comment