Shortening code help.

by theonlyski on Fri Nov 30, 2012 4: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(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 | TOGGLE FULL SIZE
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
theonlyski
 
Posts: 3
Joined: Sat Apr 14, 2012 11:01 pm

Re: Shortening code help.

by adafruit_support_mike on Sun Dec 02, 2012 12: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
printf(
    "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.
User avatar
adafruit_support_mike
 
Posts: 8621
Joined: Thu Feb 11, 2010 1:51 pm



cron