Simple Edge Detection Robot Code Issues

Here's the code.

And the problem is that, the sensors are not detecting the edge and stop.

All I want it to do is move forward, detect an edge, pause, and reverse back and re-detect the edge on the other side. That's all.

It can move forward, but once the sensor passes over the edge, it STILL wants to move forward.

PS. A motor shield is attached to the Arduino. It is the same one as shown on the website http://arduino.cc/en/Main/ArduinoMotorShield

The sensors are the Sharp IR Sensors.

// These constants won't change:
int IRsensorF = 0;     // pin that the FRONT sensor is attached to
int IRsensorB = 1;     // pin that the REAR sensor is attached to
int propulsion = 9;    // pin for motor
int dir = 12;          // pin for direction

// Defining front and back
int front = 0;
int back = 1;

// Sensor's definition
//#define BAUDRATE 9600
//#define IRsensorF 0 //analog pin for reading the IR sensor
//#define WAIT 300 //milliseconds to delay
int val = 0;       // variable to store the value coming from the sensor

void setup() {
  // set the Motor as outputs and the IR as input:
  pinMode (propulsion, OUTPUT);
  pinMode (IRsensorF, INPUT);
  pinMode (IRsensorB, INPUT);
  // set direction of Motor as output
  pinMode (dir, OUTPUT);
}

void loop() {
  // while the front sensor reading is high, propel:
  while (analogRead(IRsensorF) >= 450) {
    forward(); 
  }
  // stopping motor when sensor reading is low
  analogWrite(propulsion, 0); 
  
  // giving delay after detecting edge
  delay(10000); // 10 seconds

  // while the back sensor reading is high, propel:
  while (analogRead(IRsensorB) >= 450) {
   backward(); 
  }
  // stopping motor when sensor reading is low
  analogWrite(propulsion, 0); 
}

void forward() {
  // turn on motor forward
  analogWrite(propulsion, 255); 
  digitalWrite(dir, front);
  }

void backward() {
  // turn on motor backward
  analogWrite(propulsion, 255); 
  digitalWrite(dir, back);
  }

It can move forward, but once the sensor passes over the edge, it STILL wants to move forward.

This suggests, then, that 450 is not a good threshold. Create a simple sketch that reads the two sensors, and Serial.print() the values. See what you are actually getting from the two sensors.

@PaulS

Noted. But I've tried working with 200, 300 and 350. I still get the same result.

What values do you actually get from the sensors?

If it's really close (0-5cm) , it'll be around 450-600. At around 10cm, it's roughly in the 150-170s.

But then again, even when I placed an object right in front of the sensor to simulate an edge, the robot still moves on.

One thing that concerns me in your code is that you are setting the speed before setting the direction. I'd try reversing the order of the statements in forward() and backward().

Connect your robot up to the computer serially and follow it around.

Print the sensor value on the screen every 0.2 seconds and see what is happening.