Autonomous sensors

Hello, We have a slight problem, during autonomous, we are using the ultrasonic range finder so that the robot doesn’t bump into the perimeter, the goal perimeter or other robots but for some reason do not seem to work. How can that be fixed?

here’s the code that I am using:

task autonomous()
{
while(SensorValue(sonarSensor) > 20 || SensorValue(sonarSensor) == -1)
{
motor[robotMotor1] = -127;
motor[robotMotor2] = -127;
motor[robotMotor3] = -127;
motor[robotMotor4] = -127;

}

We’re having a similar issue. Not sure as to what the cause is yet. However if a wait command is placed before the reading the sonar sensor value, then the sensor will work. But, the wait time only seems to work with a value greater than 50 ms.

Could you perhaps include the rest of your code, and explain exactly how it is behaving? My first guess would be that you are not setting the motors to a power of 0 after this while loop, but without the rest of the code, I’m left to making guesses.

I looks like the robot doesn’t know what to do when the sonar is less than 20 or not equal to -1. So I’m going to guess the robot just stops and does nothing else the rest of autonomous.

If I understand correctly you need…
While(1)
{
Drive forward
If(sonar < 20 && sonar != -1)
{
Back up or what you want it to do
}
}

to LegoMindstormsmaniac, that’s the entire code, there is no more code in autonomous mode after this.
to esmith, maybe. I will try your suggestion after the weekend.

Thank you guys for the replies and suggestions anyway

Okay so describe the behavior you are seeing when you run this code. What doesn’t work? Is it that the motors never stop? If so I would suggest putting a StopAllMotors(); between the close bracket for the while loop and the close bracket of task autonomous.

If you live watch the values by running the ROBOTC debugger does the value of the sonar sensor ever change? If not then check the order of the wires being plugged and check it matches Motor and Sensor Setup.

So when the autonomous code is run, the robot gets close to the field perimeter but doesn’t stop and collides with the perimeter. I am not sure, but if i do remember correctly, the ultrasonic sensor value does change when it detects something.

Okay then I would suggest adding
StopAllMotors()
after the while loop ends to ensure motors actually stop and not just end the while loop when the distance is less than 20.

Sure, I will try your suggestion too, Thank you very much

I’m doing something similar and this is how I have it working on my bot.

task autonomous()
{
while(true)
{
if(encoder < desired distance travelled)
{
if(sonar < 10 inches)
{
//robot goes forwards
}
else if( sonar < 5 inches)
{
//robot goes backwards
}
else
{
//robot stops
}
}
else
{
//robot does whatever you want after its driven as far as you want
wait(1000000) //Keeps while loop from repeating
}//Closed if else statement
}//closed while loop
}//closed autonomous