Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function "printf" to AVR core class "print" #5938

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions hardware/arduino/avr/cores/arduino/Print.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -264,3 +264,56 @@ size_t Print::printFloat(double number, uint8_t digits)

return n;
}

//----------------------------------------
//printf begin

#include <stdarg.h>
#include <stdio.h>

//non class function for callback from stdio.FILE steam.
//in field FILE.udata passed class->this
static int dummy_putchar(char c, FILE *stream )
{
Print* pPrint = (Print*)(stream->udata);
if(c=='\n') pPrint->print('\r');
pPrint->print(c);
return 1;
}

size_t Print::printf(const char *fmt, ...)
{
FILE oStream; //size 12 bytes on Stack
oStream.put = dummy_putchar;
oStream.flags |= __SWR;
oStream.udata = (void*) this;
//----
oStream.flags &= ~__SPGM;
//
va_list ap;
va_start( (ap), (fmt) );
size_t i = vfprintf(&oStream, fmt, ap);
va_end(ap);
return i;
}

size_t Print::printf(const __FlashStringHelper *fmt_P, ...)
{
PGM_P fmt = reinterpret_cast<PGM_P>(fmt_P);

FILE oStream; //size 12 bytes on Stack
oStream.put = dummy_putchar;
oStream.flags |= __SWR;
oStream.udata = (void*)this;
//----
oStream.flags |= __SPGM;
//
va_list ap;
va_start( (ap), (fmt_P) );
size_t i = vfprintf(&oStream, fmt, ap);
va_end(ap);
return i;
}

//printf end
//----------------------------------------
3 changes: 3 additions & 0 deletions hardware/arduino/avr/cores/arduino/Print.h
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ class Print
size_t println(double, int = 2);
size_t println(const Printable&);
size_t println(void);

size_t printf (const char *szFormat, ...);
size_t printf (const __FlashStringHelper *szFormat, ...);
};

#endif