1

Hello everyone I write my code and have some troubles. When I write on in my serial monitor my buzzer condition wasn't changed. Can you help me realize the reason. I wrote code with int type and it works with Serial.parseInt() function properly.

String ask="Please enter buzzer condition";
int buzzerPin=2;
String state;
void setup() {
 pinMode(buzzerPin,OUTPUT);
 Serial.begin(115200);
}
void loop() {
 Serial.println(ask);
 state=Serial.readString();
 Serial.println(state);
 while(Serial.available()==0){
 
 }
 if(state=="on"){
 digitalWrite(buzzerPin,HIGH);
 }
 if(state=="off"){
 digitalWrite(buzzerPin,LOW);
}
}
chrisl
16.6k2 gold badges18 silver badges27 bronze badges
asked Apr 27, 2021 at 9:39
2
  • 2
    What line ending have you selected in the Serial Monitor? And why do you wait for more data to arrive after you read a string from Serial? Commented Apr 27, 2021 at 9:44
  • @chrisl thank you you really help me I find my mistake Commented Apr 27, 2021 at 10:06

1 Answer 1

1

You need to use Serial.readStringUntil('\n') instead of Serial.readString if you use the Arduino IDE's serial monitor (where a \n is added as termination character when you press enter). Also remove that while(Serial.available()==0). It will wait as long as there are any bytes in the serial buffer and as you don't Serial.read() within the loop, the buffer will not be emptied. So, if anything is received while Serial.println(state) is called or if you send two termination characters, the program will be stuck in that loop.

answered Apr 27, 2021 at 14:49

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.