Shortening code help.

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
theonlyski
 
Posts: 9
Joined: Sun Apr 15, 2012 12:01 am

Shortening code help.

Post by theonlyski »

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

Code: Select all

void SerialOut(){   
  Serial.print("PSI: ");
  Serial.print(PSI);
  Serial.print("    ");
  Serial.print("PumpTemp ");
  Serial.print(PumpTemp);
  Serial.print("    ");
  Serial.print("PumpMode: ");
  Serial.print(PumpMode);
  Serial.print("    ");
  Serial.print("RadarMode: ");
  Serial.print(RadarMode);  
  Serial.print("    ");
  Serial.print("HornMode: ");
  Serial.println(HornMode);
}
I tried:

Code: Select all

SerialOut(){
  String space = "    ";
  String output = "";
  output = output + "PSI: " + PSI + space + "PumpTemp: " + PumpTemp + space + "PumpMode: " + PumpMode + space + "RadarMode: " + RadarMode + space + "HornMode: " + HornMode;
  Serial.println(output);
}
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

User avatar
adafruit_support_mike
 
Posts: 67446
Joined: Thu Feb 11, 2010 2:51 pm

Re: Shortening code help.

Post by adafruit_support_mike »

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

printf(
    "PSI: %d  PumpTemp: %d  PumpMode: %d ...\n",
    PSI, PumpTemp, PumpMode, ...
);

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”