I am getting fan motor rpm as 3200. But if I get the data as 50, I should get the value like 0050. How can I do this?
I can do it like checking the value for single digit(0-9), double digit (10-99), and triple digit (100-999) and four digit(1000-9999). I need to fix digit size and send it through serial. Is there any other way for this?
2 Answers 2
You can use the C function sprintf
:
char text[5];
sprintf(text, "%04d", number);
Serial.println(text);
The leading 0 in 04d will add zero's for the length (4) is met, so 1 will become 0001, 10 will become 0010, 100 will become 0100 and 1000 will stay 1000.
-
1this is what i expected... thank you very much for your comment..Girinath Periyasamy– Girinath Periyasamy2019年09月11日 14:42:33 +00:00Commented Sep 11, 2019 at 14:42
-
Why char text[5]; ? Why 5 is entered?? Why not 4 or 3?Girinath Periyasamy– Girinath Periyasamy2019年09月27日 06:38:45 +00:00Commented Sep 27, 2019 at 6:38
Three if statements look a bit simplistic, but are much better in code size than sprintf
, if that's the only usage for sprintf.
if (number < 1000) Serial.write('0');
if (number < 100) Serial.write('0');
if (number < 10) Serial.write('0');
Serial.println(number);
Saves about 1.5kB Flash, compiled with Arduino 1.8.9 for an Uno
-
1if (number < 10) { Serial.print("000"); } else if (number < 100) { Serial.print("00"); } else if (number < 1000) { Serial.print('0'); } This saves another 200 bytes.Michel Keijzers– Michel Keijzers2019年09月11日 13:30:25 +00:00Commented Sep 11, 2019 at 13:30