Using an Ultrasonic sensor to stop hitting walls

I need some help coding a robot to accelerate, move forward and stop before hitting a wall at any distance/time.
The thing I have trouble coding is having the robot stop at any distance (while still accelerating and moving forward.) I am using an ultrasonic sensor alongside using two motors.

You know if you share the code you wrote, people will be able to help you more.

2 Likes

Normally these 2 situations cannot co-exist at the same time :stuck_out_tongue:
you can’t stop and still continue to move at the same time.

I presume you are referring to the robot current status is accelerating/moving forward and then when it reaches certain distance from the wall, you want the robot to stop moving?

Without seeing your code and the specifics of what you want to achieve, it is very doable to have the robot to stop moving once it is certain distance away from the wall.

But a few things to take note of or for your considerations:

  1. ultrasonic is not known to be the fastest responding sensor around. there will always be a lag - time taken for the sound wave to transmit out and hit the wall and then the receiver picking up the reflected wave.
    So you will need to factor lag time involved, i.e. don’t expect the robot to stop immediately. by the time the sensor picked up the reflected wave, the robot would have moved already slightly further.

  2. if the robot is accelerating, then it takes time for the robot to come to a standstill as well, unless you are cutting the power completely but at the risk of the robot’s inertia causing the robot to lurch forward.

  3. what sort of stopping distance from the wall are you looking at? while theortically the transmitted wave can travel quite a fair of distance, but in practice, you will always need to factor in energy loss, objects getting in the way, etc

4 Likes

The code is something similar to this. However, I want to change the code, so the robot stops before hitting a wall at any point and not just a specific distance, like 5cm.

Void accelerate
{
int speed = 0;

Motor[LeftMotor] = speed;
Motor[RightMotor] = speed;

speed +=20

Void forward
{
int speed = 127;

Motor[LeftMotor] = speed;
Motor[RightMotor] = speed;
}
Void decelerate
{
int speed = 127;

Motor[LeftMotor] = speed;
Motor[RightMotor] = speed;

speed -=20
}
Task Main()
{
While(SensorValue[sonarSensor] < 5

accelerate()
forward()
decelerate()
}