Appending/Concatenating two data streams to the Serial monitor


I have two data streams coming in from two separate hardwares: the pixy camera as well as the Sharp IR sensor. The Pixy camera outputs data in this format:

Detected 2:
block 0: sig: 1 x: 55 y: 133 width: 92 height: 76

Of course, the data from the IR sensor is numeric in its own sequence and I would like to input it after ‘height’ in the above code. For example I have hacked together this code:

#include <SPI.h>
#include <Pixy.h>
#include <SharpIR.h>

// This is the main Pixy object
Pixy pixy;
SharpIR sensor(GP2YA41SK0F, A0);

void setup()


void loop() {
  // Sharp IR Sensor next two lines//
  int distance = sensor.getDistance();
  Serial.println(distance); //I want this to be concatenated to the end of each block line
  static int i = 0;
  int j;
  uint16_t blocks;
  char buf[32];

  // grab blocks!
  blocks = pixy.getBlocks();

  // If there are detect blocks, print them!
  if (blocks) {


    // print blocks every fifty frames
    if (i % 50 == 0)
      sprintf(buf, "Detected %d:\n", blocks);
      Serial.print(buf + distance); //this is not working
      for (j = 0; j < blocks; j++) {

        sprintf(buf, "  block %d: ", j);
        Serial.println(); //this serial print is necessary to print out the data to Grasshopper

Depicted above, I have attempted to add the IR Distance output into the ‘buf’ Serial.print.
This is clearly not working since the buf is formatted (I think) only for the blocks. Furthermore, there is a loop dedicated to iterated through the ‘blocks’ array. I suppose, it should be added below?

Anyway help would be appreciated. Thanks

sprintf() can include more than one data item, but make sure that the target array is big enough to hold the resulting string.

      Serial.print(buf + distance); //this is not working

Well, how would you expect to add an array of chars to an integer? Add the length to the integer? Add the values of all the chars and then add the integer? I know many languages use the '+' operator as a string concatenation, but C doesn't.

Try this...


This will do something. It will print the two things with no space between them. You may wish to add further serial.print()'s to add some more context and make it readable.

@ UKHeliBob - thank you for the advice about sprintf taking more arguments. This makes sense. @ MorganS - I understand now that C++ cannot join strings the same as other languages.

In the end I was advised by a professor to use this code:

       sprintf(buf, "  block %d: ", j);
       sprintf(buf, " dis: %d ", distance);

It seems to work well. Thank you again as your comments helped me understand the code.

What I had in mind was to use 2 parameters in the [u]same[/u] sprintf() call