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 printf to print class #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
28 changes: 28 additions & 0 deletions api/Print.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,34 @@ size_t Print::println(const Printable& x)
return n;
}

static int16_t printf_putchar(char c, FILE *fp)
{
((class Print *)(fdev_get_udata(fp)))->write((uint8_t)c);
return 0;
}

int16_t Print::printf(const char *format, ...)
{
FILE f;
va_list ap;

fdev_setup_stream(&f, printf_putchar, NULL, _FDEV_SETUP_WRITE);
fdev_set_udata(&f, this);
va_start(ap, format);
return vfprintf(&f, format, ap);
}

int16_t Print::printf(const __FlashStringHelper *format, ...)
{
FILE f;
va_list ap;

fdev_setup_stream(&f, printf_putchar, NULL, _FDEV_SETUP_WRITE);
fdev_set_udata(&f, this);
va_start(ap, format);
return vfprintf_P(&f, (const char *)format, ap);
}

// Private Methods /////////////////////////////////////////////////////////////

size_t Print::printNumber(unsigned long n, uint8_t base)
Expand Down
5 changes: 4 additions & 1 deletion api/Print.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

#include <inttypes.h>
#include <stdio.h> // for size_t

#include <stdarg.h>
#include "String.h"
#include "Printable.h"

Expand Down Expand Up @@ -82,5 +82,8 @@ class Print
size_t println(double, int = 2);
size_t println(const Printable&);
size_t println(void);

int16_t printf(const char *format, ...);
int16_t printf(const __FlashStringHelper *format, ...);
};