简体   繁体   中英

Trouble Reading from Serial.readstring() arduino UNO

The objective is to enter "on" and "off" in COM port and switch the Pin 13. No matter what I do. It won't switch on or off. Need help. I tried to see if the string I entered is "on". It prints "on" but when I check for the result it shows its different. What is wrong?

String SData;
String SData1;
 void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(13,OUTPUT);
digitalWrite(13,HIGH);
delay(5000);
digitalWrite(13,LOW);
delay(1000); 
 }

 void loop() {
// put your main code here, to run repeatedly:
while(Serial.available()==0)
{

}
SData=Serial.readString();
SData1="on";
if(SData==SData1)
Serial.print("Same");
else
{
Serial.print("Different");
// Serial.print(SerialData-SerialData1);
Serial.print(".");
}
if(SData=="on")
  {
  digitalWrite(13,HIGH);

  Serial.println("LED ON");
  delay(2000);
  }
Serial.println(SData);
if(SData=="off")
 {
  digitalWrite(13,LOW);
  Serial.println("LED OFF");
  delay(2000);
 }
SData="";
}

Do not use string, use char array instead. I can suggest a function where you can set a delimiter to terminate the string or timeout when terminator character provided.

bool read_string_until (char *data, 
                        const unsigned int length, 
                        const unsigned long timeout_period, 
                        const char terminator) {

  unsigned int index = 0;
  unsigned long start_time = millis();

  while (index < length) {
    /* check if time is up */
    if (millis() - start_time >= timeout_period) {
       return false;  // no data in timeout period
    }

    /* if data, add to buffer */     
    if (Serial.available() > 0) {
      char r = Serial.read();
      if (r == terminator) {
        data [index] = 0;  // terminating null byte
        DBG_MSG("Command complete");
        return true;
      }
        data [index++] = r;
    }  
  }  
  return false;  // filled up without terminator
}


void loop() { 

  if(Serial.available()) {
    char msg[64] = {0};

    /* Capture the incoming message */
    if (read_string_until(msg, sizeof(msg), 500, '!')) 
    {
      DBG_MSG_VAL("Rx: ", msg, "");
    }
  }
}

May be you can later use these oncomming messages as command for further parsing, using

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM