I have asked a question here and now the code below makes the work that I expected (the work that I mentioned previously). Now I have another issue: if I write tmp[20]
and if the size of the input is 20 chars, the code works. However the size of the input is not known. Therefore, there can be a maxsize, but the actual size depends on the input. How can I make this code work with every length? (yes, the code works when I write 200 inside of tmp
but the size of 'message' depends on the whole array. It should be 3 chars before end and 6 chars after start).Therefore when I write 200 inside of tmp[]
and the input is shorter than 200 chars, the message returns incorrectly. I think I should use dynamic memory allocation but I could not implement it to my code.
Here is my complete code:
char tmp[20] = { 0 };
int len = sizeof(tmp) / sizeof(tmp[0]);
String pack;
String command;
String Size;
String messum;
String message;
String checksum;
int Index = 0;
bool Seen = false;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char received = Serial.read();
if (received == '!') {
Seen = true;
} else
if (received == '#') {
return strdup(tmp);
} else
if (Seen == true) {
if (Index < 2) {
//Serial.print("P");
pack = tmp[Index++] = received;
Serial.print(pack);
} else
if (Index < 4) {
//Serial.print("C");
command = tmp[Index++] = received;
Serial.print(command);
} else
if (Index < 6) {
//Serial.print("S");
Size = tmp[Index++] = received;
Serial.print(Size);
} else
if (Index < (len - 3)) {
//Serial.print("M");
message = tmp[Index++] = received;
Serial.print(message);
} else
if (Index < len) {
//Serial.print("C");
checksum = tmp[Index++] = received;
Serial.print(checksum);
}
}
}
return NULL;
//input: asdeyh134!123456789abcdefghtry#8647dfn
}