Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare __FlashStringHelper* with char* on Arduino?

I have a board that outputs lines of text to serial. I need to compare these lines of text with ones I know. Essentially, I'd like to do strcmp(thestring,F("knownstring")), however there doesn't seem to be a version of strcmp that takes the FlashStringHelper* type. There is strcmp_P that uses const PROGMEM char *, but that appears to be a different thing entirely. Someone on an Arduino forum thread I saw suggested writing one by going through the flash-string with progmem_read_byte (b, i), but that function doesn't actually exist and the nearest equivalent (pgm_read_byte(b+i)) doesn't seem to work with FlashStringHelper* - I get errors like error: invalid use of incomplete type 'class __FlashStringHelper' and error: forward declaration of 'class __FlashStringHelper', which imply I've done something seriously wrong! I'm nearly at a point of giving up and putting the strings in RAM instead, but the arduino doesn't have much of that so I want to avoid that if possible. Can anyone help?

like image 789
DHeadshot Avatar asked Oct 22 '25 05:10

DHeadshot


1 Answers

The __FlashStringHelper is just special data type used for determining correct overloaded function/method for Flash strings.

Anyway you can't use strcmp as it's for comparing two strings in RAM, but in the include <avr/pgmspace.h> there is its variant strcmp_P for comparing const char * placed in RAM with const char * placed in FLASH memory (in this order).

So you can use either:

strcmp_P(thestring, (const char*)F("knownstring"));
// or better:
strcmp_P(thestring, PSTR("knownstring"));

The F macro is basically: (__FlashStringHelper *)PSTR("...") so it's little bit redundant to cast it back to the const char* in the first case.

like image 72
KIIV Avatar answered Oct 23 '25 21:10

KIIV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!