Silly Arduino question

Your source for all things Atmel.

Moderator: phalanx

Post Reply
krazy
Posts: 45
Joined: Tue Dec 09, 2008 12:27 pm

Silly Arduino question

Post by krazy » Sat Jan 16, 2010 2:33 pm

If this is my code:

Code: Select all

int sensorPin = 0;
int sensorValue = 5;

void setup(){
  Serial.begin(9600);
  Serial.println("Program is go.");
}

void loop(){
  // read the analog pin
  Serial.print("A/D value: ");
  Serial.print(sensorValue);
  Serial.print("\n");
  delay(325);
}
How do I concatenate the "A/D Value: " and integer datatype into one
Serial.println(XXXXXXX);
statement?

Brush me up, plz? It's been a while. :)

OrlandoArias
Posts: 23
Joined: Sun Jan 10, 2010 1:22 pm
Location: The Wired 2.0

Post by OrlandoArias » Sat Jan 16, 2010 7:09 pm

The way the serial class is coded, no such method exists. If you look over at the stuff declared in HardwareSerial.h you will see what variations of Serial.print() are available. You may add your own method and recompile the library, but I find it to be pointless. In fact, I find that most of the Serial.print() overloads are pointless, it should be left to the user to implement that functionality if needed.

prkarls
Posts: 4
Joined: Sat Jan 16, 2010 9:22 pm

Post by prkarls » Sun Jan 17, 2010 8:57 am

To save one line of code you could change:

Code: Select all

  Serial.print("A/D value: ");
  Serial.print(sensorValue);
  Serial.print("\n");
to

Code: Select all

  Serial.print("A/D value: ");
  Serial.println(sensorValue);
Otherwise as for as I know there is no way to concatenate:
print("A/D Value: %i", sensorValue)
supported currently.

OrlandoArias
Posts: 23
Joined: Sun Jan 10, 2010 1:22 pm
Location: The Wired 2.0

Post by OrlandoArias » Sun Jan 17, 2010 12:19 pm

It makes no difference after you compile the code one way or another. If you look at how the Print class is coded, you will see that calling println() calls print() twice, which means when you compile the code it will have the same number of opcodes and binary size will not change. Notice also that \n is just a NEWLINE character, you must also append a carriage return \r if you wish to fall into a new line AND start at the first text column again.

Edit:
Actually, no, it makes the binary size bigger if you do that
your method:
call println(value)
setup function
call print(value)
setup function
print
return
call println()
setup function
call print('\n')
setup function
print
return
call print('\r')
setup function
print
return
return

His current method
call print(value)
setup function
print
return
call print('\n')
setup function
print
return
// stuff that he should have that is missing:
call print('\r')
setup function
print
return

You can see which method is far more efficient, if you use objdump and compare the resulting binaries, you will clearly see what I mean. Note that shorter code does not always mean smaller/faster binary.

Post Reply