在大家使用keil或是iar開發(fā)stm32等arm芯片的時(shí)候,想來(lái)最不陌生的就是使用print通過(guò)串口輸出一些數(shù)據(jù),用來(lái)調(diào)試或是其他作用。但是要明確的是由于keil iar gcc 他們使用的標(biāo)準(zhǔn)C語(yǔ)言庫(kù)雖然都遵循一個(gè)標(biāo)準(zhǔn),但他們底層的函數(shù)實(shí)現(xiàn)方式都是不同的,那么在GCC中我們能否像在keil中一樣重映射print的輸出流到串口上呢?答案是肯定的。
keil中的重映射方式及原理
/*
* libc_printf.c
*
* Created on: Dec 26, 2015
* Author: Yang
*
* 使用標(biāo)準(zhǔn)C庫(kù)時(shí),重映射printf等輸出函數(shù)的文件
* 添加在工程內(nèi)即可生效(切勿選擇semihost功能)
*/
#include //include "stm32f10x.h" #pragma import(__use_no_semihosting) //標(biāo)準(zhǔn)庫(kù)需要的支持函數(shù) struct __FILE { int handle; }; FILE __stdout; //定義_sys_exit()以避免使用半主機(jī)模式 _sys_exit(int x) { x = x; } //重映射fputc函數(shù),此函數(shù)為多個(gè)輸出函數(shù)的基礎(chǔ)函數(shù) int fputc(int ch, FILE *f) { while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET); USART_SendData(USART1, (uint8_t) ch); return ch; } 在keil中的C庫(kù)中,printf、scanf等輸入輸出流函數(shù)是通過(guò)fputc、fgetc來(lái)實(shí)現(xiàn)最底層操作的,所以我們只需要在我們的工程中重定義這兩個(gè)函數(shù)的功能就可以實(shí)現(xiàn)printf、scanf等流函數(shù)的重映射。 GNU下的C流函數(shù)重映射方式 我們來(lái)看看前幾篇中提供的樣例工程中的usart_stdio例程中的代碼片段: #include #include #include /* * To implement the STDIO functions you need to create * the _read and _write functions and hook them to the * USART you are using. This example also has a buffered * read function for basic line editing. */ int _write(int fd, char *ptr, int len); int _read(int fd, char *ptr, int len); void get_buffered_line(void); /* * This is a pretty classic ring buffer for characters */ #define BUFLEN 127 static uint16_t start_ndx; static uint16_t end_ndx; static char buf[BUFLEN + 1]; #define buf_len ((end_ndx - start_ndx) % BUFLEN) static inline int inc_ndx(int n) { return ((n + 1) % BUFLEN); } static inline int dec_ndx(int n) { return (((n + BUFLEN) - 1) % BUFLEN); } /* back up the cursor one space */ static inline void back_up(void) { end_ndx = dec_ndx(end_ndx); usart_send_blocking(USART1, '
主站蜘蛛池模板:
蕲春县|
松桃|
汶上县|
永吉县|
定结县|
元谋县|
桂平市|
中宁县|
伊通|
卓尼县|
安平县|
昌图县|
黔南|
大邑县|
金坛市|
时尚|
什邡市|
安吉县|
梅州市|
鞍山市|
马关县|
崇仁县|
文登市|
河北省|
康乐县|
金溪县|
包头市|
江川县|
和平县|
读书|
云南省|
贡山|
平远县|
通道|
金坛市|
石棉县|
阜南县|
沽源县|
保靖县|
康乐县|
寿阳县|