The extendable, not a stream but behaves like a stream, Arduino printing convenience library.
Concept for this library is simple. If you want to write your Arduino print statements using less code and in one line using modern C++ practices, you install this library. :)
This library has a hard dependency on Arduino as it is written to specifically to use Arduino Serial printing methods. It is confirmed working for Arduino MKR 1010 WiFi, but probably needs some very simple tweaking to work on other boards. Help is appreciated in that department.
- Arduino Framework
- I wrote the project using VS Code with the following extensions.
- The repository includes an automatically generated intellisense configuration.
- The project builds using the Arduino Framework, so either the Arduino IDE or the Arduino CLI are required. See the Arduino VS Code extension documentation on how to configure the framework and perform a basic build.
There is a basic example here.
It wraps all of the Arduino Serial Print functions with <<
overloads so you can Print like you would using the OStringStream STL construct in modern C++.
OPrintStream<> print(USBDevice);
print << bin << "Testing... " << 1 << " " << 2 << endl;
You can declare an extern
instance of the class that you can reference in each of your compilation units, just as you would normally refer to Arduino's Serial
.
Extending the class to be able to print your own classes or structs is also pretty simple. You can either:
- Have your object extend the Arduino
Printable
class and implement thevirtual size_t printTo(Print& p);
method. In this case you would not have to extend OPrintStream. - If you want to print an object that you do not own, say boost::string_view, you can extend OPrintStream using the Curiously Recurring Template Pattern to specify your class as the overload return type. Example:
// "Copyright 2021 Francisco Aguilera"
#ifndef INCLUDE_LOGGER_HPP_
#define INCLUDE_LOGGER_HPP_
#include <USB/USBAPI.h>
#include <oprintstream.hpp>
#include <boost_1_76_0.h>
#include <boost/utility/string_view.hpp>
namespace falven {
namespace ad {
class Logger : public OPrintStream<Logger> {
public:
Logger(USBDeviceClass &usb) : OPrintStream(usb) {}
~Logger() override = default;
...
/**
* @brief Prints the string referenced by the provided boost::string_view.
*
* @param arg The boost::stringview to print.
* @return OPrintStream& Returns the OPrintStream reference for
* continuation.
*/
OPrintStream &operator<<(const boost::string_view &arg) {
print(arg.data());
return *this;
}
// Bring our base class operator overloads into scope.
using OPrintStream<Logger>::operator<<;
};
} // namespace ad
} // namespace falven
#endif // INCLUDE_LOGGER_HPP_