Hello,
I am getting desperate with the string functions.
I receive from a device the following string “00 FF 00 01 2C” in HEX (<\0>ÿ<\0><1>,) in ASCII.
I have to react to this message.
If, for testing, I only receive 01 2C, it is recognised. But the complete line is not.
The character string that I receive cannot be changed because it is fixed in the firmware.
Here is the programme part:
int counter = 0;
char linebuf[30];
char finden[] = {0x00, 0xFF, 0x00, 0x01, 0x2C};
//char finden[] = {0x01, 0x2C};
if (Serial.available()) {//2
delay(10); // Warte auf das Eintreffen aller Zeichen vom seriellen Monitor
memset(linebuf, 0, sizeof(linebuf)); // Zeilenpuffer löschen
counter = 0; // Zähler auf Null
while (Serial.available()) {//3
linebuf[counter] = Serial.read(); // Zeichen in den Zeilenpuffer einfügen
if (counter < sizeof(linebuf) - 1) counter++; // Zeichenzähler erhöhen
}//3
//Test 00 FF 00 01 2C
if (strstr(linebuf, finden) == linebuf) {
Serial.print("gefunden");
}else{
Serial.print("nicht gefunden");
}
//Test
}
In the “linebuf”, other commands are searched for, which works without any problems because only ASCII characters greater than 30 occur there.
I assume that if “strstr” reads 0x00, it doesn’t work.
What can I do there?
you could make your own strstr.
something like this maybe…
int my_strstr(const char *haystack, int haystack_len, const char *needle, int needle_len)
{
int i = 0;
while (i < haystack_len)
{
if (haystack[i] == *needle)
{
if (!strncmp(haystack + i, needle, needle_len))
return i;
}
i++;
}
return -1;
}
void setup() {
Serial.begin(115200);
int counter = 0;
char linebuf[30];
char finden_1[] = {0x00, 0xFF, 0x00, 0x01, 0x2C};
char finden[] = {0x01, 0x2C};
//Test 00 FF 00 01 2C
Serial.println(my_strstr(finden_1, 5, finden, 2)); // returns the position on 'finden' in finden_1
//Test
}
void loop() {
}
the other option is to check each element of the received array for a match.
hope that helps
Hello
Thanks for the answer.
I have managed it with “memcmp”.
Here I compare the 2 memory areas directly. So the content doesn’t matter. It only has to match.
int pos = memcmp ( linebuf, finden, sizeof(finden) );
if (pos == 0) {//3
startStringComplete = true;
Serial.print("gefunden");
}else{
Serial.print("Fehler!"); //Fehler bei pos<0; pos>0
}
You cannot use strstr to test for a sequence of characters that contain nulls (0x00) because the null indicates the end of the char array you are passing to the strstr function.
I receive from a device the following string “00 FF 00 01 2C” in HEX (<\0>ÿ<\0><1>,) in ASCII.
That does not make sense - from your code it appears the received data is in binary, not ASCII. “00” in ASCII is 0x30 0x30, not 0x00 as you have in the finden array.