Skip to main content
skon.1
Associate III
August 5, 2020
Question

"StringOut" works while "printf" doesn't.

Hello,

I'm working with the NUCLEO-F722ZE EVB on STM32CubeIDE.

In my code I tried to make the "printf" function work.

I used the procedure described in this video:

https://www.youtube.com/watch?v=9ntZ3dwGsMk

It basically involves adding this code (the full code is below) :

#include <stdio.h>
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit ( & huart3 , (uint8_t *)&ch , 1 , 0xFFFF ) ;
 return ch ;
}

To prove that the UART peripheral works - I try to print Hello World using 2 methods. As follows:

StringOut ( "Hello World with StringOut\n\r" ) ;
printf ( "Hello World with printf" ) ;

But when I run the code only "Hello World with StringOut" gets printed on the screen. The printf function doens't do anything.

Help me fix the printf function.

This is the full code:

#include "main.h"
#include <stdio.h>
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
 
void StringOut ( char * s )
{
 HAL_UART_Transmit ( & huart3 , ( void * ) s , strlen ( s ) , 1000 ) ;
}
 
int main(void)
{
 HAL_Init();
 SystemClock_Config();
 MX_USART3_UART_Init();
 
 while (1)
 {
 StringOut ( "Hello World with StringOut\n\r" ) ; // Prints successfully 
 printf ( "Hello World with printf" ) ; // Nothing happens. The code just proceeds ahead. 
 }
}
 
PUTCHAR_PROTOTYPE
{
 HAL_UART_Transmit ( & huart3 , (uint8_t *)&ch , 1 , 0xFFFF ) ;
 return ch ;
}

This topic has been closed for replies.

5 replies

TDK
August 6, 2020

Does printf call PUTCHAR_PROTOTYPE? If you put a breakpoint there, does it get hit?

"If you feel a post has answered your question, please click ""Accept as Solution""."
skon.1
skon.1Author
Associate III
August 6, 2020

When I put a breakpoint on the "printf" line and press F6 (step into) it doesn't go anywhere (same as if I would press F5).

So I guess the answer to your question is "NO" ?

DPant.1
Associate
August 6, 2020

Try this:

int _write(int32_t file, uint8_t *ptr, int32_t len)
{
	HAL_StatusTypeDef res = HAL_UART_Transmit(&huart3, ptr, len, 1000);
	switch (res) {
		case HAL_OK:
			break;
		// HAL_ERROR, HAL_BUSY, HAL_TIMEOUT
		default:
			while(1) {};
			break;
	}
	return len;
}

KnarfB
Super User
August 6, 2020

The video uses another IDE and another compiler. For STM32CubeIDE (using gcc) check the generated syscalls.c file. printf will eventually call _write which in turn calls __io_putchar. You have to override (define) either of those functions. E.g. in your main.c as suggested by @DPant.1.