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.

asked Mar 1, 2022 at 13:55
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.

answered Mar 1, 2022 at 14:12
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

answered Mar 1, 2022 at 14:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.