rkatakam
rkatakam

Reputation: 51

Trouble programming MindstormsNXT with RobotC

I am having trouble making my robot controlling my Mindstorms NXT robot with RobotC. I want my robot to be able to move forward on a table and when reaching the end, the ultrasonic sensor, which is facing down, will determine if it is on the edge by seeing how far the ground is. When the ultrasonic sensor finds that it is on the edge, the robot will move back from the edge, turn around, and go the other way.

Here is my code:

#pragma config(Sensor, S1,     ,               sensorSONAR)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//

task main()

{

int Ultrasonic; 
Ultrasonic = SensorValue[S1];

while (true)
{
    if (Ultrasonic >10)
{
motor[motorB] = -100;
motor[motorC] = -100;
wait1Msec(2000);

motor[motorB] = 100;
wait1Msec(2000);
}
if (Ultrasonic <= 10)
{
    motor[motorB] = 50;
    motor[motorC] = 50;
    wait1Msec(5000);
}
}
}

Upvotes: 0

Views: 225

Answers (1)

Ernest3.14
Ernest3.14

Reputation: 1012

The problem with this program is that you really only read from the ultrasonic sensor once. Here's what happens when you run your program:

  1. The variable Ultrasonic is created, and the sensor value is assigned to it.
  2. The program checks the value of the ultrasonic sensor.
  3. The program does something based on what the ultrasonic sensor is read.
  4. The program does something based on what the ultrasonic sensor is read.

...

To fix this problem, all you need to do is to move the reading of the ultrasonic sensor into the while loop, so that the NXT continually checks the value of the sensor. Here's what a modified version would look like:

task main()
{
    int Ultrasonic; 

    while (true)
    {
        Ultrasonic = SensorValue[S1];
        if (Ultrasonic > 10)
        {
            // ... Do stuff here...
        }
        if (Ultrasonic <= 10)
        {
            // ... Do more stuff here...
        }
    }
}

In fact, you could make this code even "cleaner" by combining the check for the value of the ultrasonic sensor by using an "if... else..." statement. This checks one value, and then makes a decision based on whether that value is true--or else. Just replace the line if (Ultrasonic <= 10) with else.

Upvotes: 1

Related Questions