Thursday, October 7, 2010

How To Do Big Strings in Arduino

Arduino makes it pretty easy to store & use character strings, but those strings compete with your variables, so you can’t do as much. Here’s how to put big strings into read-only program memory and use them.

Lots of sketches can have big strings in them. Maybe you’ve built a little command-line interface or you’re storing small web pages (for net-connected Arduinos). Normally you do something like this:

char hellostr[] = "hello world"
"

hello world

erial.println( hellostr );
""; // and then sometime later
S

The problem with this is that “hellostr” is stored in RAM along with your variables. The ATmega chip in Arduino only has 1kB of RAM. If your code is getting complex, and you’re using big strings, and lots of libraries, you may start having mysterious problems. Arduino can’t warn you if your sketch starts using too much RAM.

Instead, you can use PROGMEM, or PROGram MEMory, to store your strings. That is, the flash ROM memory that your code lives in. Using PROGMEM strings can be tricky, but here’s a little function called “printProgStr()” to make it almost as easy.

const char hellostr[] PROGMEM = "..."; // notice added 'const' and 'PROGMEM'
// given a PROGMEM string, use Serial.print() to send it out
) return; while((c = pgm_read_byte(str
void printProgStr(const prog_char str[]) { char c; if(!st
r++))) Serial.print(c,BYTE); } // and then at some point

printProgStr( hellostr );

If you have another use for the string that isn’t “Serial.print()”, just create your own function and put whatever per-character handling function in there instead.

Related Posts Plugin for WordPress, Blogger...
Disclaimer: All the information in this blog is just gathered from different sites in the web and placed here and I am not the owner for these content

Popular Projects

Followers

My Blog List

Give Support

Give Support
Encourage me Through Comments & by Following