Home > OS >  How do I clear a c variable after use to use it again?
How do I clear a c variable after use to use it again?

Time:02-10

If I send a message over serial the first time it receves the right code it works but after that it stops working.

    const unsigned int MAX_MESSAGE_LENGTH = 32;
    const char EMPTY[1] = {'\0'};
    
    void setup() {
      Serial.begin(9600);//bPS
    }

    String readserial(){
      char message[MAX_MESSAGE_LENGTH];
      static unsigned int message_pos = 0;
      while (Serial.available() > 0 ){
    
        char inbyte = Serial.read();
        if(inbyte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1)){
          message[message_pos] = inbyte;
          message_pos  = 1;
        } else {
          message[message_pos] = '\0';
          //Serial.println(message);
          return message;
        }
      }
      return EMPTY;
    }
    
    void loop() {
      static String message;
      message = readserial();
    
      if(message == "Hi"){
        Serial.println("Hello");
      }else{
        //Serial.println(message);
      }
    }

the output shows hello only if I say Hi first if I put anything else it just doesn't work. I have tried looking for an answer elsewhere but I am stuck.

CodePudding user response:

I assume you want to start a new string upon encountering a newline character. That being the case you just need to reset message_pos back to 0 in the else.

if(inbyte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1)){
    message[message_pos] = inbyte;
    message_pos  = 1;
} else {
    message[message_pos] = '\0';
    message_pos = 0;  // <<---- THIS LINE ADDED
    return message;
}

CodePudding user response:

Your message length message_posisn't being reset to zero. Whatever value it has, the value will be "kept" because you have declared it as static. If you remove the statickeyword, message_pos will be reset to zero every time you call readserial().

You can also, as pointed out, set message_posto zero as you return the string.

However, because you don't actually use (or need) message_pos as static I suggest you simply remove the keyword.

  • Related