Problem to control the exact position of dc encoder motor

Hi..

I am controlling the Encoder DC motor position in the range of (90,180,270,360).

  • I am taking the value of motor and it is stored in COUNTER.
  • By redwing the value of COUNTER I am stop the motor speed with help of PWM pin.
  • It working good in 90 position.

**But it not working for other position. **

Can you please help me with my code? I attach a copy below.

Board : Arduino Mega
DC motor with magnetic encoder
Motor driver : MD10C R3

#define outputA 2
 #define outputB 3
int pwm = 11;
 int counter = 0; 
 int aState;
 int aLastState; 
 

 void setup() { 
   pinMode (outputA,INPUT);
   pinMode (outputB,INPUT);
   
   Serial.begin (9600);
   // Reads the initial state of the outputA
   aLastState = digitalRead(outputA);
   delay(2000);   
 } 

 void loop() { 

  
   aState = digitalRead(outputA); // Reads the "current" state of the outputA
   // If the previous and the current state of the outputA are different, that means a Pulse has occured
   if (aState != aLastState){     
     // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
     if (digitalRead(outputB) != aState) { 
       counter ++;
     } else {
       counter --;
     }
     
     Serial.print("Position: ");
     Serial.println(counter);
      delay(20);

     
   } 
   aLastState = aState; // Updates the previous state of the outputA with the current state 
if(counter == 0 ) // on the motor speed 
{
analogWrite(pwm,30);
  }
 if (counter == 90 ) //  to stop  motor speed 
{
analogWrite(pwm,0);
}
if(counter == 91 )// on the motor speed 
{
{
analogWrite(pwm,30);
  }
 if (counter == 180 )//  to stop  motor speed 
{
analogWrite(pwm,0);

}
if(counter == 181 )// on the motor speed 
{
analogWrite(pwm,30);
  }
 if (counter == 270 )//  to stop  motor speed 
{
analogWrite(pwm,0);

}
f(counter == 271)// on the motor speed 
{
analogWrite(pwm,30);
  }
 if (counter == 360 )//  to stop  motor speed 

{
analogWrite(pwm,0);

}
 }

I assume that the encoder, and hence the value of counter is controlled by motor rotation

If you stop the motor when counter equals 90 how is counter ever going to get any larger ?