cancel
Showing results for 
Search instead for 
Did you mean: 

Redirect printf() to COM port

PRobe
Associate II

A simple question.

I have loaded & run the NUCLEO-F401RE \Projects\STM32F401RE-Nucleo\Examples\UART\UART_Printf example.

The project sends printf() to COM.

I have cut and paste the __io_putchar(int ch) code into my own project.

__io_putchar() does not get called & so no output.

I can output ok using HAL_UART_Transmit() but would rather capture printf().

The example code contains the comment 'With GCC, small printf (option LD Linker->Libraries->Small printf   set to 'Yes') calls __io_putchar()' so I guess I have to change a project option or two.

I cannot find the option or anything similar however.

4 REPLIES 4
S.Ma
Principal

Why not build your own printf_usb function not to rely on specifics? This way you can even customize the escape codes... Got custon printf for text lcd, serial, usb, modem etc... One printf won t be enough over time.

Daniel Glasser
Associate III

My experience with "newlib-nano" is that what you really want to do is to provide "_write_r()" and/or "write()" following the defined interfaces.

/* Get newlib's definition of "reent" */
#include <reent.h>
#include "main.h"
 
/* newlib nano provides a stub version of "_write_r()" that does nothing.  The stub has a
 * weak binding, so defining the function in your own files will override the stub.
 */
_ssize_t _write_r(struct _reent *ptr, /* Don't worry about what's in this for the simple case */
                  int fd, /* ignored */
                  const void* buf, /* the data to be sent out the UART */
                  size_t      cnt) /* the number of bytes to be sent */
{
   /* Replace "huart3" with the pointer to the UART or USART instance you are using
   * in your project
   */
   HAL_UART_Transmit(&huart3, (uint8_t*)buf, cnt, 1000);
 
   return (_ssize_t)cnt;
}

This version does not handle inserting a "\r" before "\n"; that would be better done in "write()" for the general case, but I leave that up to you if you want it.

PRobe
Associate II

Thanks, that works fine.

Piranha
Chief II
int _write(int fd, const void *buf, size_t count);

You can use this simpler version and not include reent.h.