Skip to main content
PRobe
Associate III
January 11, 2019
Question

Redirect printf() to COM port

  • January 11, 2019
  • 4 replies
  • 1589 views

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.

This topic has been closed for replies.

4 replies

S.Ma
Principal
January 11, 2019

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
January 11, 2019

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
PRobeAuthor
Associate III
January 14, 2019

Thanks, that works fine.

Piranha
Principal III
January 15, 2019
int _write(int fd, const void *buf, size_t count);

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