Advertisement
Guest User

USsensorDCMotor

a guest
Jun 25th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #define trig 7
  2. #define echo 8
  3. #define enaPin 9
  4. #define motor1 10
  5. #define motor2 11
  6. #define redLed 5
  7.  
  8. long distance, duration;
  9.  
  10. void setup() {
  11.   pinMode(trig, OUTPUT);
  12.   pinMode(echo, INPUT);
  13.   pinMode(enaPin, OUTPUT);
  14.   pinMode(motor1, OUTPUT);
  15.   pinMode(motor2, OUTPUT);
  16.   pinMode(redLed, OUTPUT);
  17.   Serial.begin(9600);
  18. }
  19.  
  20. void loop() {
  21.   digitalWrite(trig, LOW);
  22.   delayMicroseconds(2);
  23.   digitalWrite(trig, HIGH);
  24.   delayMicroseconds(10);
  25.   digitalWrite(trig, LOW);
  26.  
  27.   duration = pulseIn(echo, HIGH);
  28.   distance = duration / 29 / 2;
  29.  
  30.   if (distance > 50) {
  31.     analogWrite(enaPin, 250);
  32.     digitalWrite(motor1, HIGH);
  33.     digitalWrite(motor2, LOW);
  34.     digitalWrite(redLed, LOW);
  35.   }
  36.   else {
  37.     digitalWrite(redLed, HIGH);
  38.     for (int Speed = 250; Speed >= 0; Speed = Speed - 10) {
  39.       analogWrite(enaPin, Speed);
  40.       digitalWrite(motor1, HIGH);
  41.       digitalWrite(motor2, LOW);
  42.     }
  43.   }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement