'How do I clear a c variable after use to use it again?
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.
Solution 1:[1]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kaylum |
