Serial.print 4 Columns of Data, Right-aligned for each Column

Hi,

I want to Serial.print rows of 4 Results, aligned as follows, at the end of a Sketch so that the Sensors are regularly analogRead:

0.0 10 1 0
20.0 2543521 8 1
954.2 100 10 0
8.5 52541 9 1

Tab starts everything to the left:

0.0 10 1 0
20.0 2543521 8 1
954.2 100 10 0
8.5 52541 9 1

Having read that Strings use a lot of memory & not being able to find a Topic with this layout, I thought about filling an arrayResults[4, 7, 20], representing [Column n°, Digits (not including decimal point which will always be in the same position), Max n° of rows of Results] with individual Digits from each Result.

However, I cannot work out how to populate the array with the Results. I could Serial.print the Results in Comma-Separated-Values format then Ctrl-c from the Serial Monitor & Ctrl-v into a spreadsheet and write a macro. As I am using a RaspberryPi B+, as I cannot make my Mega 2560 work with Windows 8.1, I am getting nowhere.

Any help much appreciated, Walter

What type of variables are in each column ? It looks like floats, longs, bytes and bytes. Is that right ?

walter1957:
Any help much appreciated, Walter

Float variables can be formatted to a fixed length with the dtostrf function from the AVR LIBC.

All the rest such like byte, int, long, string and so on can be formatted using sprintf or snprintf from the AVR LIBC strings library functions.

Floats & Longs yes but I assumed the 3rd & 4th columns would be integers.

For some reason in the original Post the columns are not correctly lined up so that the least/righthand digit of each column are lined up correctly. In Preview, after preparing the Post, they were.

Thanks jurs for your suggestions. I will look at that later on.

You may be able to do the whole thing using dtostrf()

void setup()
{
  Serial.begin(115200);
  formatNumber(954.2, 10, 2);
  formatNumber(100, 10, 0);
  formatNumber(10, 10, 0);
  formatNumber(0, 10, 0);
  Serial.println();
  formatNumber(20.0, 10, 2);
  formatNumber(2543521, 10, 0);
  formatNumber(8, 10, 0);
  formatNumber(1, 10, 0);
  Serial.println();
  
}

void loop()
{
}

void formatNumber(float input, byte columns, byte places)
{
  char buffer[20];
  dtostrf(input, columns, places, buffer);
  Serial.print(buffer);
}
1 Like