2

I have created a code that should print out "Enter true to deactivate alarm" in the serial monitor, then store the user's answer and print "alarm off" if they enter true and "alarm on" otherwise. However, it is returning "alarm on" every time, even if I enter true. Here is my code:

String deactivate = "";
void setup() {
  Serial.println("Enter \"true\" to deactivate alarm");
}
void loop() {
  while (Serial.available() == 0){}
  deactivate = Serial.readString();
  if (deactivate.equals("true")) 
  {
    Serial.println("alarm off");
  }
  else
  {
    Serial.println("alarm on");
  }
}

Any help here would be greatly appreciated, I'm new to Arduino and we've been stuck on this step for weeks; I am just really at a loss trying to figure out why it isn't working.

0

2 Answers 2

1

You didn't set the Serial port:

Serial.begin(9600);

Add this in the setup function. Also check in your serial monitor if the speeds are equal.

If this still doesn't work, print the deactivate variable after assigning, and its length, and every character to see if it adds a newline character or any other unexpected character.

Then if it is a whitespace character, use a function to strip the whitespace, or change the comparison.

1

Often is the case coders will add "debugging" print statements to aid in understanding what is occurring in their code. Printing out what you received may help in understanding unexpected results.

That said, consider using Serial.readStringUntil() in place of Serial.readString(). From the linked to page:

Returns

The entire String read from the serial buffer, up to the terminator character

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.