Simple programming problem

Hello guys, here´s the case… I have a simple project. A cc motor must rotate clockwise, anti-clockwise or stop based on the reads I get from 2 LDR´s.
I made the following part of the code:

void loop() {
valor1 = analogRead(analogin1);
valor2 = analogRead(analogin2);
dif = valor1 - valor2;
Serial.print(valor1);
Serial.print(" ; “);
Serial.print(valor2);
Serial.print(” ; ");
Serial.println(dif);
if(dif > 40){
// put motor in forward motion
digitalWrite(motor1APin, LOW); // set leg 1 of the H-bridge low
digitalWrite(motor2APin, HIGH); // set leg 2 of the H-bridge high
// control the speed 0- 255
speed_value_motor1 = 160;
analogWrite(speedPin, speed_value_motor1); // output speed as
// PWM value
}
else if(dif < 40){
// put motor in backward motion
digitalWrite(motor1APin, HIGH); // set leg 1 of the H-bridge low
digitalWrite(motor2APin, LOW); // set leg 2 of the H-bridge high
// control the speed 0- 255
speed_value_motor1 = 160;
analogWrite(speedPin, speed_value_motor1); // output speed as
// PWM value
}
else{
// stop the motor
digitalWrite(motor1APin, LOW); // set leg 1 of the H-bridge low
digitalWrite(motor2APin, LOW); // set leg 2 of the H-bridge high
// control the speed 0- 255
speed_value_motor1 = 0;
analogWrite(speedPin, speed_value_motor1); // output speed as
// PWM value
}
}

It works partially! The motor changes the direction if a LDR receives more light or the other. But when the difference between the reads of the LDR´s is less than 40, the motor just don´t stop! What am I doing wrong?
Hope you understood everything I said here =P

Thanks all!

First of all, please put your code in the # brackets - it becomes much easier to read that way.

Secondly, your code doesn’t do what you think it does…:

if ( diff > 40 ) go forward
else if ( diff < 40 ) go backward
else if ( diff == 40 ) stop

If you want it to stop if the difference is less than 40, you should change your else if to say so - right now it will only stop if both values are exactly equal.

Of course, you should probably use the abs() function on the difference if you want this to work in both directions - otherwise this will only work if the LDR on analogin1 is greater than the LDR on analogin2.

Indeed. This might work better:

dif = abs(valor1 - valor2);
if(dif <= 40)
  //stop the motor
else if (valor1>Valor2)
  //Run forwards
else
  //Run backwards

Thanks!! The last suggestion worked perfectly here! =D

Thanks a lot to you guys!