I am working on a project in which i have made a robot powered by 4 Johnson DC motors (300 rpm) and controlled by Arduino UNO R3. Now in my project I'd used ultrasonic sensor (hc - sr04) for detecting obstacles. What i want is that as soon as my an obstacle is detected robot should turn by 180° but what actually happening is that sometimes robot takes turn very late (though I'd kept range of sensor approximately 50cms) and sometimes it just collides with obstacle.

As I'm new to Arduino i just wanna know that is ultrasonic sensor fast enough to sense obstacle and signals arduino about it before it gets close enough ?

here's my code

    int sense()
    {
         analogWrite(trigPin, 0);
     // instead of digitalWrite(trigPin,LOW);
         delayMicroseconds(2); 
    
    /* as I'd used my digital pins for  motors and all i have to use pwm pin for  trigger pin of sensors i guess it doesn't make any difference*/
    
         analogWrite(trigPin, 255);
      // instead of digitalWrite(trigPin, HIGH);
         delayMicroseconds(10); 
    
         analogWrite(trigPin, 0);
         duration = pulseIn(echoPin, HIGH);
    
         distance = duration/58.2;
    
          if (distance > maximumRange)
              return 0;
          else
              return 1;
    }