westfw:
There was a recent discussion on AVRfreaks, the upshot of which was that the FDEV_SETUP_STREAM macro uses features that don't work in C++ (but work fine in C.)http://www.avrfreaks.net/forum/stdio-setup-printf-and-pulling-my-hair-out
Well, that's interesting. The "lowercase" version (that takes 4 parameters) works fine. In fact, I made a little library that HardwareSerial calls to automatically provide me stdin/out/err for the serial port. And, it sets up the proper one (for example, If, on a MEGA, I do "Serial1.begin()", it correctly associates Serial1 to the stdin/out streams.
Stdinout.cpp
#include <Stdinout.h>
// connect stdio to stream
void STDINOUT::open (Stream &str)
{
if (_std_init) {
close ();
}
_stream_pointer = &str;
fdev_setup_stream (&_fp, _putchar, _getchar, _FDEV_SETUP_RW);
stdin = stdout = stderr = &_fp;
_std_init = true;
}
void STDINOUT::close (void)
{
if (_std_init) {
_stream_pointer->flush ();
fdev_close ();
_stream_pointer = NULL;
_std_init = false;
}
}
// Function that printf and related will use to print
int STDINOUT::_putchar (char c, FILE *stream)
{
if (_stream_pointer) {
if (c == '\n') { // \n sends crlf
_putchar ((char) '\r', stream);
}
return (_stream_pointer->write (c));
} else {
return 0;
}
}
// Function that scanf and related will use to read
int STDINOUT::_getchar (FILE *stream)
{
if (_stream_pointer) {
while (!(_stream_pointer->available ()));
return (_stream_pointer->read ());
} else {
return 0;
}
}
// end of stdinout.cpp
Stdinout.h
#ifndef STD_IN_OUT_H
#define STD_IN_OUT_H
#include <Stream.h>
static Stream *_stream_pointer;
class STDINOUT
{
public:
void open (Stream &);
void close (void);
private:
FILE _fp;
static int _putchar (char, FILE *);
static int _getchar (FILE *);
int _std_init = false;
};
#endif
// end of Stdinout.h
Then, in HardwareSerial, at the end of both begin() functions, I have this:
STDIO.open (*this); // connect stdin/out/err to current serial stream
...and at the end of end():
STDIO.close (); // flush, close and disconnect std streams
Lastly, what I didn't show is that there's a [b]static STDINOUT STDIO;[/b]
in the HardwareSerial.h file.
It works like a charm