CPP 248
Ultra_sonic stop at 30 and closer Mohamadi Guest on 11th November 2023 01:22:04 PM
  1. #define motor1 5
  2. #define motor2 6
  3.  
  4. int ultra_sonic(int trigger, int echo){
  5.   digitalWrite(trigger, LOW);
  6.   delayMicroseconds(2);
  7.   digitalWrite(trigger, HIGH);
  8.   delayMicroseconds(10);
  9.   digitalWrite(trigger, LOW);
  10.   int duration = pulseIn(echo, HIGH, 50000);
  11.   int distance = duration * 0.034 / 2;
  12.   return distance;
  13. }
  14.  
  15. void setup() {
  16.   Serial.begin(9600);
  17.   pinMode(9, OUTPUT);
  18.   pinMode(10, INPUT);
  19.   pinMode(3, OUTPUT);
  20.   pinMode(5, OUTPUT);
  21. }
  22.  
  23. void loop(){
  24.   int distance = ultra_sonic(9, 10);
  25.   if (distance > 30){
  26.     for (int i = 0; i<=255; i++){
  27.       analogWrite(motor2, i);
  28.       digitalWrite(motor1, 0);
  29.       if(distance < 30){
  30.           break;
  31.       }
  32.       delay(10);
  33.       distance = ultra_sonic(9, 10);
  34.       Serial.print("distance1: ");
  35.       Serial.println(distance);
  36.       while(i == 255){
  37.         digitalWrite(motor2, HIGH);
  38.         digitalWrite(motor1, LOW);
  39.         distance = ultra_sonic(9, 10);
  40.         if(distance < 30){
  41.           break;
  42.         }
  43.         Serial.print("distance: ");
  44.         Serial.println(distance);
  45.       }
  46.     }
  47.   }
  48.   else{
  49.     analogWrite(motor1, 0);
  50.     analogWrite(motor2, 0);
  51.   }
  52. }

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.