AceUtils  0.2.1
Useful Arduino utilties which are too small for separate libraries.
printfTo.h
1 /*
2  * MIT License
3  * Copyright (c) 2018 Brian T. Park
4  */
5 
6 /*
7  * Implement a printfTo() that accept formatting strings like printf() and
8  * prints the result to the given `Print` object. This is intended to be used
9  * on platforms whose `Print` does not provide a `Print.printf()` function, for
10  * example, the original Arduino UNO or Nano. I finally got tired of writing
11  * multiple lines of SERIAL_PORT_MONITOR.print() for debugging.
12  *
13  * NOTE: These *must* be implemented as inline function to allow the compiler
14  * to remove unused functions from the binary. For some reason, on AVR, ESP8266
15  * and ESP32 compilers, link-time-optimization does not seem to work well. If
16  * these functions are defined in a .cpp file, they are included in the binary,
17  * even if they are not reference at all by anything. This causes the binary to
18  * be about 700 (AVR) to 1000 (ESP32) bytes larger in flash memory.
19  *
20  * Being inlined here means that <Arduino.h> must be included here, which can
21  * cause some problems in files that try to clobber macros defined in
22  * <Arduino.h>.
23  */
24 
25 #ifndef PRINT_UTILS_PRINTF_TO_H
26 #define PRINT_UTILS_PRINTF_TO_H
27 
28 #include <stdarg.h>
29 #include <Arduino.h>
30 
31 namespace print_utils {
32 
34 static const int BUF_SIZE = 192;
35 
37 inline void vprintfTo(Print& printer, const char *fmt, va_list args) {
38  char buf[BUF_SIZE];
39  vsnprintf(buf, BUF_SIZE, fmt, args);
40  printer.print(buf);
41 }
42 
49 inline void printfTo(Print& printer, const char* fmt, ...) {
50  va_list args;
51  va_start(args, fmt);
52  vprintfTo(printer, fmt, args);
53  va_end(args);
54 }
55 
56 }
57 
58 #endif