Skip to content

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

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

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
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
Next Next commit
Add "printf()"
This "printf" realization not use "sprintf" and buffers in RAM.  
If it is not used, the compiler does not add any extra code.
Exelent for AVR.
  • Loading branch information
u48 authored Feb 1, 2017
commit b1371c21ce69c50ae5cd0fedcf3c1c7cb4bd2c3c
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
//----------------------------------------