Advertisement
macca-nz

HCSR04_distance_with_LEDS_demo

Dec 17th, 2020 (edited)
89
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * Loop Logic
  3.  * When an object is closer tha 10cm led 1 is on, 7cm led 2 and 5 cm led 3
  4.  * When the object goes outside these ranges they will turn off after a 1 second delay
  5.  */
  6.  
  7. #include <HCSR04.h>
  8. const int led1 = 2;
  9. const int led2 = 3;
  10. const int led3 = 4;
  11. HCSR04 hc(5,6); //(trig pin , echo pin)
  12. unsigned long ctus  = 0;
  13. unsigned long readDelay = 10;
  14. unsigned long ctLed1  = 0;
  15. unsigned long ctLed2  = 0;
  16. unsigned long ctLed3  = 0;
  17. unsigned long ledDelay = 2000;
  18. unsigned long ctPrint = 0;
  19. unsigned long spDelay = 1000;
  20. int Close = 100;
  21. int Mid = 150;
  22. int Far = 200;
  23. int distance = 0;
  24.  
  25. void setup(){
  26.   Serial.begin(9600);
  27.   pinMode(led1, OUTPUT);
  28.   pinMode(led2, OUTPUT);
  29.   pinMode(led3, OUTPUT);
  30.   digitalWrite(led1, LOW);
  31.   digitalWrite(led2, LOW);
  32.   digitalWrite(led3, LOW);
  33. }
  34.  
  35. void readDistance(){
  36.     distance = hc.dist();
  37.     distance = distance*10;
  38. }
  39.  
  40. void loop(){
  41.   int led1State = digitalRead(led1);
  42.   int led2State = digitalRead(led2);
  43.   int led3State = digitalRead(led3);
  44.  
  45.   if((millis() - ctus) > readDelay){
  46.     readDistance();
  47.     ctus = millis();
  48.   }  
  49.  
  50.   if((millis() - ctPrint) > spDelay){
  51.     Serial.print(distance);Serial.println(" mm");
  52.     ctPrint = millis();
  53.   }
  54.  
  55.   if(distance < Far){
  56.     led1State = HIGH;
  57.   }else if(distance >= Far){
  58.     if((millis() - ctLed1) > ledDelay){
  59.       led1State = LOW;
  60.       ctLed1 = millis();
  61.     }
  62.   }
  63.  
  64.   if(distance < Mid){
  65.     led2State = HIGH;
  66.   }else if(distance >= Mid){
  67.     if((millis() - ctLed2) > ledDelay){
  68.       led2State = LOW;
  69.       ctLed2 = millis();
  70.     }
  71.   }
  72.   if(distance < Close){
  73.     led3State = HIGH;
  74.   }else if(distance >= Close){
  75.     if((millis() - ctLed3) > ledDelay){
  76.       led3State = LOW;
  77.       ctLed3 = millis();
  78.     }
  79.   }  
  80.   digitalWrite(led1, led1State);
  81.   digitalWrite(led2, led2State);
  82.   digitalWrite(led3, led3State);
  83. }
Advertisement
RAW Paste Data Copied
Advertisement