safwan092

Project - 3286

Feb 24th, 2021
1,032
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #define echoPin 7 // Echo Pin
  2. #define trigPin 6 // Trigger Pin
  3. #define motorPin 8 // Motor Pin
  4.  
  5. long duration, distance;
  6.  
  7. void setup()
  8. {
  9.   Serial.begin(9600);
  10.   pinMode(motorPin, OUTPUT);
  11.   pinMode(trigPin, OUTPUT);
  12.   pinMode(echoPin, INPUT);
  13.   digitalWrite(motorPin, LOW);
  14. }
  15.  
  16. void loop()
  17. {
  18.   US();
  19. }
  20.  
  21. void US() {
  22.   digitalWrite(trigPin, LOW);
  23.   delayMicroseconds(2);
  24.   digitalWrite(trigPin, HIGH);
  25.   delayMicroseconds(10);
  26.   digitalWrite(trigPin, LOW);
  27.   duration = pulseIn(echoPin, HIGH);
  28.   distance = duration / 58.2;
  29.   Serial.println(distance);
  30.   if (distance < 100 && distance > 50) {
  31.     //move motor
  32.     digitalWrite(motorPin, HIGH);
  33.     delay(500);
  34.     digitalWrite(motorPin, LOW);
  35.     delay(500);
  36.   }
  37.   else if (distance < 50) {
  38.     //stop motor
  39.     digitalWrite(motorPin, HIGH);
  40.     delay(300);
  41.     digitalWrite(motorPin, LOW);
  42.     delay(100);
  43.     digitalWrite(motorPin, HIGH);
  44.     delay(300);
  45.     digitalWrite(motorPin, LOW);
  46.     delay(300);
  47.   }
  48.   else {
  49.     digitalWrite(motorPin, LOW);
  50.   }
  51.   delay(50);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment