CODE not working as it should

#include <AFMotor.h>

AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);
String data = "";
String moveforward = "MF";


void setup() 
{
	//Set initial speed of the motor & stop
	motor1.setSpeed(200);
	motor1.run(RELEASE);
	motor2.setSpeed(200);
	motor2.run(RELEASE);
	motor3.setSpeed(200);
	motor3.run(RELEASE);
	motor4.setSpeed(200);
	motor4.run(RELEASE);
	Serial.begin(9600);
}

void loop() {
  if(Serial.available() > 0){
    data = Serial.readString();
    Serial.println(data);
  }
  if(data == moveforward){
	  //motor1.run(FORWARD);
	  //motor2.run(FORWARD);
	  //motor3.run(FORWARD);
	  //motor4.run(FORWARD);
	  Serial.println("forward");
	  delay(1000);
  }else {
    //motor1.run(RELEASE);
    //motor1.run(RELEASE);
    //motor1.run(RELEASE);
    //motor1.run(RELEASE);
    Serial.println("stop");
    delay(1000);
  }
  
}
  }

this should output forward when MF is put in serial but it only gives this :--

+bump

now i see

You have a new line character in data

On Uno you must not use pins 0 & 1

because it occupied by Serial.

You have the serial monitor sending a newline character, but the text comparison does not include that character. Try setting the serial monitor to no line ending.

Isn't that "channel 1" ?

Useless AI generated reply, and reply to that, deleted.

Af dc motor lib makes 1 correspond to motor out 1
Using l298n shield......... Just the coder for a project..... Prob is serial input = mf does not gib output as forward

Didnt understand

As david said, your SM is sending "mf" AND a line ending. That's evident when you echo it back, see that extra blank line in SM after "mf" ? There is a setting in serial Monitor to modify the end of line that SM adds when you press enter after typing mf. Change that to nothing, and SM will only send "mf", nothing more.

Yeah but after mf it should print forward but it is not printing that

Do you think ("MF"(plus a line ending)) might be not equal to "MF"?

To be clear, the code is working exactly as it should. A string with more than two characters can never be equal to a string with two characters.

So what should I change

you were told by three of us - change the setting in Serial Monitor to not send a line ending when you hit enter to end your entry. It's that simple. Or, if you're up for a learning experience, change your code to only evaluate the first two characters of the string ("MF"(plus a line ending)).

Another solution in the documentation Serial.readString() - Arduino Reference

ok...made a fresh code it works.....thnks
tht also worked but anyways...yeah.......um.......

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