CPP 265
Ultra_sonic different speeds mohamadi no soft start Guest on 11th November 2023 01:20:13 PM
  1. #define trig 9
  2. #define ech 10
  3. #define motor1 5
  4. #define motor2 6
  5.  
  6. int duration = 0;
  7. int distance = 0;
  8. // int current_speed = 0;
  9. // int max_speed = 0;
  10. int ultra_sonic(int trigger, int echo){
  11.   while(1){
  12.     digitalWrite(trigger, LOW);
  13.     delayMicroseconds(2);
  14.     digitalWrite(trigger, HIGH);
  15.     delayMicroseconds(10);
  16.     digitalWrite(trigger, LOW);
  17.     duration = pulseIn(echo, HIGH, 50000);
  18.     distance = duration * 0.034 / 2;
  19.     if (distance!=0){
  20.       return distance;
  21.     }
  22.   }
  23. }
  24. void setup() {
  25.   pinMode(trig,OUTPUT);
  26.   pinMode(ech,INPUT);
  27.   pinMode(motor1, OUTPUT);
  28.   pinMode(motor2, OUTPUT);
  29.   Serial.begin(9600);
  30.  
  31. }
  32.  
  33. void loop() {
  34.   int distance = ultra_sonic(trig,ech);
  35.   Serial.println(distance);
  36.   if (distance > 40){
  37.     analogWrite(motor1, 255);
  38.     digitalWrite(motor2, LOW);
  39.     distance = ultra_sonic(trig, ech);
  40.   }
  41.   else if (distance > 35 && distance < 40){
  42.     analogWrite(motor1, 125);
  43.     analogWrite(motor2, 0);
  44.     distance = ultra_sonic(trig, ech);
  45.   }
  46.   else if (distance > 30 && distance < 35){
  47.     analogWrite(motor1, 63);
  48.     analogWrite(motor2, 0);
  49.     distance = ultra_sonic(trig, ech);
  50.   }
  51.   else if (distance < 30 && distance > 20){
  52.     digitalWrite(motor1, 0);
  53.     analogWrite(motor2, 0);
  54.     distance = ultra_sonic(trig, ech);
  55.   }
  56.   else if (distance < 20){
  57.     digitalWrite(motor1, 0);
  58.     digitalWrite(motor2, 1);
  59.   }
  60. }

Hightechrobo bin is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.