From dab8c6144c646f6179ab32fff83c28e04bde3314 Mon Sep 17 00:00:00 2001 From: MCUdude Date: Thu, 28 Feb 2019 17:54:03 +0100 Subject: [PATCH] Add printf to print class --- api/Print.cpp | 28 ++++++++++++++++++++++++++++ api/Print.h | 5 ++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/api/Print.cpp b/api/Print.cpp index 4f0016c4..bef414a6 100644 --- a/api/Print.cpp +++ b/api/Print.cpp @@ -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) diff --git a/api/Print.h b/api/Print.h index 6a06bad6..5355cbc1 100644 --- a/api/Print.h +++ b/api/Print.h @@ -20,7 +20,7 @@ #include #include // for size_t - +#include #include "String.h" #include "Printable.h" @@ -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, ...); };