Encoder limit not stopping motor

Hello everyone!
I've been working on a project which involves the use of a GUI and control of an Arduino device. The control of the device has to be in real time so I'm sending a continuous stream of commands through the Serial port to the Arduino.
I'm using a Pololu micro motor and magnetic encoder to control the device and I want to impose a limit for the motor so that if the encoder of the motor reaches a certain value the motor stops.

Controlling the motor has been successful so far, but I cannot make the motor stop once the encoder reaches a certain value. Even if the encoder counts waayy above the limit value, the motor will still run.

I will post the code below:

void checkForCommand(){
  if(Serial.available()){
    do{    //Read serial input buffer data byte by byte for any received commands
      receivedCommand = (char)Serial.read();
    }while(Serial.available());
  }
  
  if(receivedCommand == '1'){
    dataR=(char)Serial.read();
    if(dataR=='F'){
      while(dataR!='H' && motor1Count <= 15000){
        digitalWrite(motor1pin1, LOW);
        digitalWrite(motor1pin2, HIGH);
        dataR=(char)Serial.read();  
      }
    }
    else if(dataR == 'B'){
      while(dataR!='H' && motor1Count >= 6){
        digitalWrite(motor1pin1, HIGH);
        digitalWrite(motor1pin2, LOW);
        dataR=(char)Serial.read();
      }
    }
  }
}

Why is my code not taking into account the value of the encoder?

because it's a snippet (Snippets R Us!) and nowhere in the code you shared you are polling an encoder... (is motor1Count incremented in some way? is it a volatile byte size variable that is updated in an ISR??)

also the way you read the Serial input is bogus

Please post ALL your code.

This code will continue to read from the Serial buffer while there is data available. It will only exit once there is no more... at that point receivedCommand will just contain the last character received.

The serial input basics tutorial shows robust non-blocking ways to read and parse serial input data.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.