Page 1 of 1

retarget printf?

Posted: Mon Oct 30, 2017 7:34 am
by gigelu999
Hi!

Can anyone please help me with some advice to retarget printf() ? I want to interpret with the characters in order to format all output. The output of the stream should remain uart1.

Thank you.

Re: retarget printf?

Posted: Mon Oct 30, 2017 11:23 am
by ESP_igrr
The official solution should be to implement a custom VFS driver, similar to vfs_uart.c.

You can then register your driver with VFS (e.g. /dev/my_uart) and do

Code: Select all

freopen("/dev/my_uart/1", "w", stdout);
Another option, which may require smaller amount of code, but needs access to newlib internals, is to install a custom function in place of _write member of stdio FILE structure (see sys/reent.h). Newlib will call _write member to output data to the stream. You can put your own filter function into _write and then call __swrite (which is what normally is called by _write).
In pseudocode,

Code: Select all

static ssize_t (*old_swrite)(struct _reent* ptr, void* cookie, const char* buf, size_t n);

static ssize_t my_swrite(struct _reent* ptr, void* cookie, const char* buf, size_t n)
{
  // filter stuff, then call __swrite
  return (*old_swrite)(ptr, cookie, maybe_other_buf, maybe_other_size);
}

// later
old_swrite = stdout->_write;
stdout->_write = &my_swrite;