how to make printf() work

Given that everyone uses Serial.print() I thought that printf didn't work on the arduino platform. I didn't think it was supported due to lack of flash, but I came across a post saying that sprintf did work. There is no reason why sprintf should work and printf wouldn't, so I tested it out. I added this function:

int my_putc( char c, FILE *t) {
  Serial.write( c );
}

and this line to the setup() function

  fdevopen( &myputc, 0);

and it works great! no more stupid huge blocks of Serial.print() commands. For a short writeup, check out my blog at reza.net (this site doesn't let me post a link without having a post without a link, even though i have nothing else to post about). click on the blog link and it should be easy to find.

-reza

Let me try posting the link here:

Use

Serial.print()

command for printf()

I'm pretty sure you can't do printf syntax with print. For example

serial.print("value %04u %s", x, str)

I haven't tried but I don't think that works

Works like a charm, but questions arise:

  • Speed ?
  • Size esp RAM ?

If I now switch from Serial to NewSoftSerial (which is not quite uncommon) I don't need to change my code. If I use printf() I have to !

Now I use sprintf with a global buffer (64 bytes) that is reused again and again, and I can easily change between Serial and NSS.

It should be just as easy to reuse, all you have to do is change the my_putc() function to use whatever serial output you want (other than Serial.write()). It also gives you the flexibility to assign STDOUT to one serial interface and STDERR to another if you are using an mega-arduino (let me know if you want an example on how to do this).

sprintf() uses the same underlying code so your not saving any flash space, just doing it manually. In my test, it added 2k to the compiled size of the application. Test your code w/ and w/o the sprintf and see how much larger the code becomes.

Reza

change the my_putc() function

Yes, that's true, I overlooked that one. :-[ :wink: