Help on serial print formatting

Hello

Im trying to send values to PC in the format

PxxxxRyyyyTzzzz

where xxxx, yyyy, zzzz should b 4 digit no.s. and P R Z are ASCII characters

i use

serial.print("P");
serial.print(p);
serial.print("R");
serial.print(r);
serial.print("T");
serial.print(t);

where integers p, r and t correspond to xxxx,yyyy,zzzz repectively

no. of digits of p, r , t vary from 1 to 4

how to stuff is with zeros and print viz. if p is 54, it must be printed as 0054 ?

is it possible print such a format above using single serial.print statement?

please help out

Thanks in advance

is it possible print such a format above using single serial.print statement?

No, it is not.

You can use sprintf to format a string, and then print that string.

int x = 14;
int y = 126;
int z = 1007;

char tbs[16];

sprintf(tbs, "P%4dR%4dT%4d", x, y, z);

This will result in tbs containing:

P 14R 126T1007

which you can then send using:

Serial.print(tbs);

thanks for ur reply. while using sprintf
i get error: sprintf is not declared in this scope

Add this to the sketch:

#include <stdio.h> // for function sprintf

it works :slight_smile: thanks :slight_smile:

By the way, if you want to pad the number with zeros instead of spaces, change the %4d to %04d in your sprintf format.

Regards,

-Mike

thanks mike :slight_smile: