Advertisement
Guest User

hcroo

a guest
Mar 21st, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #define trigPin  9
  2. #define echoPin 10
  3.  
  4. #define ledGreen 3
  5. #define ledRed 8
  6.  
  7. #define alarm 11
  8.  
  9.  
  10. int range = 5;
  11.  
  12. void setup() {
  13.  
  14.   Serial.begin(9600);
  15.  
  16.  
  17.   pinMode(trigPin, OUTPUT);
  18.   pinMode(echoPin, INPUT);
  19.  
  20.   pinMode(ledGreen, OUTPUT);
  21.   pinMode(ledRed, OUTPUT);
  22.  
  23.   digitalWrite(ledGreen, HIGH);
  24.   digitalWrite(ledRed, LOW);
  25.  
  26. }
  27. void loop()
  28. {
  29.  
  30.  
  31.  
  32.   long duration, inches, cm;
  33.  
  34.  
  35.   digitalWrite(trigPin, LOW);
  36.   delayMicroseconds(2);
  37.   digitalWrite(trigPin, HIGH);
  38.   delayMicroseconds(5);
  39.   digitalWrite(trigPin, LOW);
  40.  
  41.  
  42.   duration = pulseIn(echoPin, HIGH);
  43.  
  44.  
  45.   inches = microsecondsToInches(duration);
  46.   cm = microsecondsToCentimeters(duration);
  47.  
  48.   Serial.print(inches);
  49.   Serial.print("in, ");
  50.   Serial.print(cm);
  51.   Serial.print("cm");
  52.   Serial.println();
  53.  
  54.   if(inches < 5) {
  55.     Serial.println("not");
  56.     digitalWrite(ledGreen, LOW);
  57.     digitalWrite(ledRed, HIGH);
  58.     tone(alarm, 2000);
  59.     delay(50);
  60.   } else {
  61.     Serial.println("OK");
  62.      digitalWrite(ledGreen, HIGH);
  63.      digitalWrite(ledRed, LOW);
  64.      noTone(alarm);
  65.      delay(50);
  66.   }  
  67.  
  68.  
  69.  
  70.  
  71.   delay(200);
  72. }
  73.  
  74. long microsecondsToInches(long microseconds)
  75. {
  76.  
  77.   return microseconds / 74 / 2;
  78. }
  79.  
  80. long microsecondsToCentimeters(long microseconds)
  81. {
  82.  
  83.   return microseconds / 29 / 2;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement