關(guān)于STM32中 printf 與 scanf 的重定向問題在此我僅對(duì)不使用 "USE MircoLIB" 的情況做整理(針對(duì)Keil RVMDK開發(fā)環(huán)境)。
① :首先需要在 usart.h 中包含 “stdio.h” 頭文件
② :在 usart.c 中,加入如下代碼塊,以此避免使用半主機(jī)模式,并重定向 printf 和scanf 函數(shù);
- #if 1
- #pragma import (__use_no_semihosting_swi)
- /*標(biāo)準(zhǔn)庫需要的支持函數(shù),use_no_semihosting_swi以避免使用半主機(jī)模式*/
- struct __FILE
- {
- int handle;
- };
-
- FILE __stdout;
- FILE __stdin;
- /*重定向Printf函數(shù)*/
- int fputc(int ch,FILE *f)
- {
- return (SendChar(ch));
- }
- /*重定向Scanf函數(shù)*/
- int fgetc(FILE *f)
- {
- return (SendChar(GetKey()));
- /*調(diào)用scanf()在串口中輸入數(shù)據(jù)時(shí),必須以空格結(jié)束,否則無法完成發(fā)送*/
- }
-
- void _ttywrch(int ch)
- {
- SendChar(ch);
- }
-
- int _ferror(FILE *f) {
- /* Your implementation of ferror */
- return EOF;
- }
-
- //定義_sys_exit()以避免使用半主機(jī)模式
- void _sys_exit(int return_code){
- //x = x;
- label:goto label;
- }
-
- #endif
③ :在 usart.c 中添加SendChar()與GetKey()函數(shù)
- int SendChar(int ch)
- {
- while(!(USART1->SR & USART_FLAG_TXE));
- USART1->DR = (ch & 0x1FF);
-
- return ch;
- }
-
- int GetKey(void)
- {
- while(!(USART1->SR & USART_FLAG_RXNE));
- return ((int)(USART1->DR & 0X1FF));
- }
完成以上三步,即可實(shí)現(xiàn)printf()函數(shù)與scanf()的串口重定向,將標(biāo)準(zhǔn)輸入輸出流的來源或去向改為串口。
關(guān)于第二步所使用的避免使用半主機(jī)模式的代碼,其實(shí)Kei已經(jīng)為我們寫好了一個(gè)Retarget.c文件,在Keil/ARM/Startup目錄下.
另外本文針對(duì)的開發(fā)環(huán)境為Keil RVMDK,本人在Emblocks開源開發(fā)工具中實(shí)驗(yàn)時(shí),本方法是無法實(shí)現(xiàn)printf和Scanf的重定向的,以及在開源工具下如何"Use microLIB"的問題都有待進(jìn)一步探討。
|