Shortening code help.
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Shortening code help.

by theonlyski on Fri Nov 30, 2012 5:29 pm

Hey guys, looking for a more efficient way to do this.

Code: Select all | TOGGLE FULL SIZE
void SerialOut(){   
  Serial.print("PSI: ");
  Serial.print("    ");
  Serial.print("PumpTemp ");
  Serial.print("    ");
  Serial.print("PumpMode: ");
  Serial.print("    ");
  Serial.print("RadarMode: ");
  Serial.print("    ");
  Serial.print("HornMode: ");

I tried:

Code: Select all | TOGGLE FULL SIZE
  String space = "    ";
  String output = "";
  output = output + "PSI: " + PSI + space + "PumpTemp: " + PumpTemp + space + "PumpMode: " + PumpMode + space + "RadarMode: " + RadarMode + space + "HornMode: " + HornMode;

Which works, 32 times... then the board locks up and has to be reset.

I know there is a random issue with the values not being defined first, but it's weird that it worked 32 times exactly then dies.

Here I was troubleshooting the new sensor when I hadn't thought about all the code that I had changed! :oops:

Also, if anyone needs an easy to use PSI sensor, I just picked one up off ebay for $30 that works like a champ. Linear output and all! :D

Posts: 9
Joined: Sun Apr 15, 2012 12:01 am

Re: Shortening code help.

by adafruit_support_mike on Sun Dec 02, 2012 1:20 am

I had to spend five minutes looking at that to understand how it would work at all.. ;-)

In C, strings are arrays of characters, so 'adding' strings with the '+' operator would actually add the pointer values for each string. It's possible to use that constructively, but not like this.

A little digging reminded me that the Arduino environment also defines String objects, which can be concatenated with '+'. At a guess, your code is allocating new String objects every time you call the function, and by the 32nd time you get a memory overflow.

What you want is the 'printf' function described on this page: http://arduino.cc/playground/Main/Printf

With that, your code would look like so:
Code: Select all | TOGGLE FULL SIZE
    "PSI: %d  PumpTemp: %d  PumpMode: %d ...\n",
    PSI, PumpTemp, PumpMode, ...
When you void a product warranty, you give up your right to sue the manufacturer if something goes wrong and accept full responsibility for whatever happens next. And then you truly own the product.

Posts: 44191
Joined: Thu Feb 11, 2010 2:51 pm

Please be positive and constructive with your questions and comments.