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

Added printf() to Print class #509

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
30 changes: 30 additions & 0 deletions cores/arduino/Print.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,36 @@ size_t Print::write(const uint8_t *buffer, size_t size)
return n;
}

size_t Print::printf(const char *format, ...)
{
char loc_buf[64];
char * temp = loc_buf;
va_list arg;
va_list copy;
va_start(arg, format);
va_copy(copy, arg);
int len = vsnprintf(temp, sizeof(loc_buf), format, copy);
va_end(copy);
if(len < 0) {
va_end(arg);
return 0;
};
if((unsigned)len >= sizeof(loc_buf)){
temp = (char*) malloc(len+1);
if(temp == NULL) {
va_end(arg);
return 0;
}
len = vsnprintf(temp, len+1, format, arg);
}
va_end(arg);
len = write((uint8_t*)temp, len);
if(temp != loc_buf){
free(temp);
}
return len;
}

size_t Print::print(const __FlashStringHelper *ifsh)
{
PGM_P p = reinterpret_cast<PGM_P>(ifsh);
Expand Down
2 changes: 2 additions & 0 deletions cores/arduino/Print.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ class Print
size_t write(const char *buffer, size_t size) {
return write((const uint8_t *)buffer, size);
}

size_t printf(const char * format, ...) __attribute__ ((format (printf, 2, 3)));

// default to zero, meaning "a single write may block"
// should be overridden by subclasses with buffering
Expand Down