Contents

在TrueSTUDIO环境中实现STM32平台的printf

由于license的问题,keil被禁止使用了,所以只能使用开放的IDE了,那就选择Atollic的trueSTUDIO。 在keil中重定向printf到串口很简单,只需要勾选MicroLIB,以及实现putc及getc两个函数即可。但是trueSTUDIO使用的是gcc,所以这套不行。

1.选择C运行库

properties -> c/c++ build -> tool settings -> general -> newlib-nano

2.在任意工程文件内实现_read,_write函数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
int _read(int file, char *ptr, int len)
{
	int DataIdx;

	for (DataIdx = 0; DataIdx < len; DataIdx++)
	{
		*ptr++ = __io_getchar();
	}

return len;
}

int _write(int file, char *ptr, int len)
{
	int DataIdx;

	for (DataIdx = 0; DataIdx < len; DataIdx++)
	{
		__io_putchar(*ptr++);
	}
	return len;
}
int __io_getchar(void)
{
	char ch = -1;
	HAL_UART_Receive(&hlpuart1,(uint8_t*)&ch,1,1000);
	return ch;
}
int __io_putchar(int ch)
{
	while(!__HAL_UART_GET_FLAG(&hlpuart1,UART_FLAG_TC));
	hlpuart1.Instance->TDR = (uint8_t)ch;
	return ch;
}

3.由于默认的库开启了输入输出缓存,会造成printf执行完后等一会才能在串口的另一端看到东西。故要想立即看到,则在板级初始化的时候就需要关闭缓存

1
2
3
4
5
6
void initialise_monitor_handles()
{
	setvbuf(stdin,NULL,_IONBF,0);
	setvbuf(stdout,NULL,_IONBF,0);
	setvbuf(stderr,NULL,_IONBF,0);
}