Go Down

Topic: Zero Padding or Leading Zeros (Read 3 times) previous topic - next topic

liudr


printf("%03d", number);

If you need to send it to both the serial port and a LCD, use sprintf() to print it to a string, then print that string to both outputs.


That's my choice any day of the week but I didn't know how much OP wants to learn a C function ;)

I visit this site every time I forget how to use all the nice features of sprintf:

http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

If you do "%3d" then you get space padding to the left.

JRMN

Thanks for the link liudr.  Is sprintf library dependant, I didn't get a chance to test it out last night?

liudr

With sprintf in the blink example code, it compiles just fine without using any library. I think the library is already included by arduino by default.

jraskell


With sprintf in the blink example code, it compiles just fine without using any library. I think the library is already included by arduino by default.

That is correct, though in a somewhat circuitous manner.

main.cpp include WProgram.h (the sketch you create is automatically merged with main.cpp by the Arduino IDE)
WProgram includes from the AVR Libc library:
http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html
http://www.nongnu.org/avr-libc/user-manual/group__avr__string.html
http://www.nongnu.org/avr-libc/user-manual/group__avr__math.html

But also includes from the 'Arduino library', among other things, HardwareSerial.h
HardwareSerial.h includes Stream.h
Stream.h includes Print.h
And Print.h includes http://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html, which provides the various versions of printf.

It's all rather academic from the perspective of being able to use sprintf(), but it never hurts to have an understanding of what's going on beneath the covers, and I think it's always useful to know that the variety of C library functions in those modules are available for your usage within Arduino sketches by default.

liudr

That is pretty complicated :smiley-eek-blue:. I can certain appreciate a breakdown of what happens and hope the OP gets it too.

I have been including stdio.h but I'll remove it now that a version of it is already included.

Go Up