Skip to content

Commit 5f62a39

Browse files
author
Bogdan Marinescu
committed
Added preliminary printf() support to RawSerial
1 parent e162e96 commit 5f62a39

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

libraries/mbed/api/RawSerial.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,16 @@ class RawSerial: public SerialBase {
7171
* @returns The char read from the serial port
7272
*/
7373
int getc();
74+
75+
/** Write a string to the serial port
76+
*
77+
* @param str The string to write
78+
*
79+
* @returns 0 if the write succeeds, EOF for error
80+
*/
81+
int puts(const char *str);
82+
83+
int printf(const char *format, ...);
7484
};
7585

7686
} // namespace mbed

libraries/mbed/common/RawSerial.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,12 @@
1515
*/
1616
#include "RawSerial.h"
1717
#include "wait_api.h"
18+
#include <cstdarg>
1819

1920
#if DEVICE_SERIAL
2021

22+
#define STRING_STACK_LIMIT 120
23+
2124
namespace mbed {
2225

2326
RawSerial::RawSerial(PinName tx, PinName rx) : SerialBase(tx, rx) {
@@ -31,6 +34,34 @@ int RawSerial::putc(int c) {
3134
return _base_putc(c);
3235
}
3336

37+
int RawSerial::puts(const char *str) {
38+
while (*str)
39+
putc(*str ++);
40+
return 0;
41+
}
42+
43+
// Experimental support for printf in RawSerial. No Stream inheritance
44+
// means we can't call printf() directly, so we use sprintf() instead.
45+
// We only call malloc() for the sprintf() buffer if the buffer
46+
// length is above a certain threshold, otherwise we use just the stack.
47+
int RawSerial::printf(const char *format, ...) {
48+
std::va_list arg;
49+
va_start(arg, format);
50+
int len = vsnprintf(NULL, 0, format, arg);
51+
if (len < STRING_STACK_LIMIT) {
52+
char temp[STRING_STACK_LIMIT];
53+
vsprintf(temp, format, arg);
54+
puts(temp);
55+
} else {
56+
char *temp = new char[len + 1];
57+
vsprintf(temp, format, arg);
58+
puts(temp);
59+
delete[] temp;
60+
}
61+
va_end(arg);
62+
return len;
63+
}
64+
3465
} // namespace mbed
3566

3667
#endif

0 commit comments

Comments
 (0)