sonar as limitswitch?

hello, i am trying to use a sonar sensor to stop movement forward if items are less than 5 inches from the sensor, but not prevent backwards movement. right now, the drive control is on a single analog stick. here is the code:

motor[port1] = (vexRT[Ch1] + vexRT[Ch2])/2;
motor[port10] = (vexRT[Ch1] - vexRT[Ch2])/2;

however i want to add something similar to the way a limit switch code works, as shown by this code:

int motorValue = 0;

  // Get joystick
  motorValue = vexRT[Ch4];

  // Limit to down movement if limit switch is hit
  // limit switch is setup as touch sensor so pressed is 1
  if( SensorValue[dgtl12] == 1 ) {
    // are we going up ?
    if( motorValue > 0 ) {
      motorValue = 0;

is there a way to set a 5 inch distance to the sonar so that if it goes less than 5 inches the robot cant move forward, however not preventing it from going backwards?

If your second example is working for you with a limit switch, then you can simply replace this line from your existing code:

if( SensorValue[dgtl12] == 1 )

with this code:

if(SensorValue[limitSensor] <= fEndTrigger)

Where limitSensor is your ultrasonic sensor, and fEndTrigger is the value you want to stop at.

Roughly what @jrp62 said, but you’ll have to do a little more than that to get what you want to do to work. This is both because you want to be able to move, just not forward, and because you are using arcade control. Here’s a quick sketch. You’ll want to choose an appropriate value for minimumDistance and replace ultrasonicPort with the appropriate port.

#define minimumDistance 10

int leftDrive = 0;
int rightDrive = 0;

   leftDrive = (vexRT[Ch1] + vexRT[Ch2])/2;
   rightDrive = (vexRT[Ch1] - vexRT[Ch2])/2;
   if(leftDrive > 0 && SensorValue[ultrasonicPort] < minimumDistance) {
      leftDrive = 0;
   if(rightDrive > 0 && SensorValue[ultrasonicPort] < minimumDistance) {
      rightDrive = 0;
   motor[port1] = leftDrive;
   motor[port10] = rightDrive;

thank you, i got it to work. im just trying to now play around with distance. the reason i set it like this was so i could have it stop moving forward when it needs to grab something without knocking the object down