Skip to content

Commit dab8c61

Browse files
committed
Add printf to print class
1 parent e1eb8de commit dab8c61

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

api/Print.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,34 @@ size_t Print::println(const Printable& x)
233233
return n;
234234
}
235235

236+
static int16_t printf_putchar(char c, FILE *fp)
237+
{
238+
((class Print *)(fdev_get_udata(fp)))->write((uint8_t)c);
239+
return 0;
240+
}
241+
242+
int16_t Print::printf(const char *format, ...)
243+
{
244+
FILE f;
245+
va_list ap;
246+
247+
fdev_setup_stream(&f, printf_putchar, NULL, _FDEV_SETUP_WRITE);
248+
fdev_set_udata(&f, this);
249+
va_start(ap, format);
250+
return vfprintf(&f, format, ap);
251+
}
252+
253+
int16_t Print::printf(const __FlashStringHelper *format, ...)
254+
{
255+
FILE f;
256+
va_list ap;
257+
258+
fdev_setup_stream(&f, printf_putchar, NULL, _FDEV_SETUP_WRITE);
259+
fdev_set_udata(&f, this);
260+
va_start(ap, format);
261+
return vfprintf_P(&f, (const char *)format, ap);
262+
}
263+
236264
// Private Methods /////////////////////////////////////////////////////////////
237265

238266
size_t Print::printNumber(unsigned long n, uint8_t base)

api/Print.h

+4-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
#include <inttypes.h>
2222
#include <stdio.h> // for size_t
23-
23+
#include <stdarg.h>
2424
#include "String.h"
2525
#include "Printable.h"
2626

@@ -82,5 +82,8 @@ class Print
8282
size_t println(double, int = 2);
8383
size_t println(const Printable&);
8484
size_t println(void);
85+
86+
int16_t printf(const char *format, ...);
87+
int16_t printf(const __FlashStringHelper *format, ...);
8588
};
8689

0 commit comments

Comments
 (0)