Motor perminitly reverse when sensor triped

My robot has ir sensors around the out side of him. I want to make it so that when the ir sensor is triped the motors will reverse perminitly. I know how to make it so when the ir sensor is triped the motors reverse but after my robot moves away from the object the robot starts going forward again.

So imagian my robot moving foward then it detects an object then I want it to moved backwards untill the back sensor is triped.

Thanks -Nick

Greetings,

I was rummaging through old messages and found yours. This is a good question, so I thought I would tackle it even though it is really old.

The basic principle is to introduce a "state" variable that controls the motor. In your case it could be called direction. If it is HIGH, then go forward. If it is LOW, then go backward. Then just have the sensor change the state. Here is some simple code:

loop() {
    // Check sensors
    if (digitalRead(1) == HIGH) {
        direction = 0;
    } else if (digitalRead(2) == HIGH {
        direction = 1;
    }

    // Drive motor
    if (direction == 1) {
        digitalWrite(3, HIGH);
    } else {
        digitalWrite(3, LOW);
    }
}

It's easy to extend this example to motor sensors and more motors.

Regards, David