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 50cm) and sometimes it just collides with obstacles.
As I'm new to Arduino I just want to know if an ultrasonic sensor is fast enough to sense obstacles and signal the 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;
}