Hello,
I have a project that prints to a Serial and to File (SD library), I want to know if there is a easy way to automatic print or println to both units...
Like this:
int value = 10;
Both.print("angle: ");
Both.println(value);
And the string "angle: 10" is printed to Serial and File...
I'm asking that because the code is to big of duplicated prints commands..
thanks
You write your own function that prints to both and use that.
Maybe learn more C, that is a basic.
Thanks for a useless anwser...!! If is so easy why you dont anwser with the function???
The print() function is a overloaded function (just search at print.h)
void print (char)
void print (const char[])
void print (long)
void print (unsigned long)
void print (uint8_t)
void print (long, int)
void print (double)
void print (int)
void print (unsigned int)
void println (char)
void println (long, int)
void println (long)
void println (unsigned long)
void println (int)
void println (double)
void println (uint8_t)
void println (void)
void println (unsigned int)
void println (const char[])
I dont know how to make my one function, in a simple way... I'm using the print function with int,char,long and double values...
Ok... after a feel search I found a solution. just use a #define stament
#define LOG_print(str)
Serial1.print(str);
ArquivoLOG.print(str);
#define LOG_println(str)
Serial1.println(str);
ArquivoLOG.println(str);
You asked something simple and expect a do-everything answer to match your goalpost move?
How about learn to use sprintf() and print strings to both?
I don't really like the #define, for quite a few reasons. One is it won't work in an if. For example:
if (something)
LOG_print ("Trouble brewing");
You can see from your define that this would only conditionally do the first print, and the second one would be unconditional.
You could use templates:
template <typename T> void Bothprint (T what);
template <typename T> void Bothprint (T what)
{
Serial.print (what);
Serial1.print (what);
Serial2.print (what);
}
template <typename T> void Bothprintln (T what);
template <typename T> void Bothprintln (T what)
{
Serial.println (what);
Serial1.println (what);
Serial2.println (what);
}
Now:
Bothprint ("Hi there");
Bothprintln (1234);
That will work OK, providing you only have a single argument (your #define has the same issue).
Or you can make your own class:
class BothClass : public Print
{
public:
virtual size_t write (const byte c)
{
Serial.print (c);
Serial1.println (c);
Serial2.println (c);
return 1;
} // end of Both::write
}; // end of Both
BothClass Both;
Now the "Both" instance will handle anything you can throw at "print", eg.
Both.print ("Hi there"); // string
Both.println (1234, HEX); // print in hex
Both.print (12.34, 3); // floating point to 3 decimal places