String compare with less RAM

Hi guys,

I have a general programming question rather than one specific to arduino.
My program is using up to 75% of the SRAM available on the UNO. This is mainly due to the implementation of ASCII commands that can be sent to the arduino. I need to leave those commands as such because any user should be able to communicate with it using SCPI commands.

So here's my problem:

if( cmd.equals( "measmode" ) )

uses a lot of memory. Would be easier if I could hash cmd and the string, to compare against 2 or 3 bytes only...

Any thoughts on a way to do that easily ?

Cheers,
Norman

You shouldn't be using the String class with so little memory available. There is a significant risk of complete system failure due to heap fragmentation. You should be using char strings and the built in C string functions instead.

How are the commands being entered ?

As aarg said, you should firstly look into using the C string commands rather than the String class on the Uno, as it has so little memory.

Secondly, I suspect the majority of your memory usage is coming from your string constants - "measmode" will, by default, be stored in Flash but then copied into SRAM before being used. However, you can gain control over this process so that unnecessary copies of the strings are not kept in SRAM at all times, either using PROGMEM or F().

PROGMEM is the more flexible of the two as it allows you to store arbitrary data in Flash but you have to manage it manually. F() is a simplification specifically for strings that automates most of it, and I think would be more appropriate here, e.g. swap

if( cmd.equals( "measmode" ) )

with

if( cmd.equals( F("measmode") ) )

and BOOM your SRAM usage will plummet.

Oh :slight_smile:
It did indeed.

I will switch everything to string commands, but to be honest, the String class is so convenient...

scythist:
but to be honest, the String class is so convenient...

That's always the problem with sin :slight_smile:

...R

but to be honest, the String class is so convenient...

So is a Swiss Army knife. But, a Swiss Army knife is rarely the best tool for the job. The same applies to the rescource-wasting String class.

scythist:
Would be easier if I could hash cmd and the string, to compare against 2 or 3 bytes only...

The search phrase is "minimal perfect hash". Good luck.