目录
这个实验向我们演示,不同的串口使用printf函数来输出对应的信息。默认printf()函数使用usart1,剩下usart2~4分别使用USART2_printf(),USART3_printf(),USART4_printf()输出信息。
项目地址:GitHub
新建工程
1、新建芯片工程"g071c8/g071rb",打开SWD调试接口、HSE
2、 设置时钟树,HCLK=64MHz
3、 查看数据手册,看那些引脚可以用作usart1、usart2、usart3、usart4。把这些引脚设置成TX,RX
USART1:PA10,PA9。USART2:PA2,PA3。USART3:PB10,PB11。USART4:PA0,PA1
4、启用USART外设,参数按照自己的实际来填。模式设为Asynchronous,115200,8bit,None,1
5、 项目管理填好信息。生成代码"GENERATE CODE"
6、使用MDK打开工程,debug选项中勾上“Reset and Run”
代码部分
1、usart.h中添加如下代码
#include <stdarg.h>
/* USER CODE BEGIN Prototypes */
void USART4_printf(char *fmt,...); //重写usart4的printf函数
void USART3_printf(char *fmt,...);
void USART2_printf(char *fmt,...);
/* USER CODE END Prototypes */
2、usart.c添加如下代码
/* USER CODE BEGIN 0 */
#include <stdio.h>
#include <string.h>
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/**
* @brief Retargets the C library printf function to the USART.
* @param None
* @retval None
*/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
#define USART_TXBUFF_SIZE 256 //定义串口发送缓冲区大小 256字节
__align(8) char usart_txBuff[USART_TXBUFF_SIZE]; //字节对齐缓冲区
//usart4的printf()
void USART4_printf(char *fmt,...)
{
uint32_t i,length;
va_list ap;
va_start(ap,fmt);
vsprintf(usart_txBuff,fmt,ap);
va_end(ap);
length=strlen((const char*)usart_txBuff);
while((USART4->ISR&0x40)==0);
for(i=0;i<length;i++)
{
USART4->TDR=usart_txBuff[i];
while((USART4->ISR&0x40)==0);
}
}
//usart3的printf()
void USART3_printf(char *fmt,...)
{
uint32_t i,length;
va_list ap;
va_start(ap,fmt);
vsprintf(usart_txBuff,fmt,ap);
va_end(ap);
length=strlen((const char*)usart_txBuff);
while((USART3->ISR&0x40)==0);
for(i=0;i<length;i++)
{
USART3->TDR=usart_txBuff[i];
while((USART3->ISR&0x40)==0);
}
}
//usart2的printf()
void USART2_printf(char *fmt,...)
{
uint32_t i,length;
va_list ap;
va_start(ap,fmt);
vsprintf(usart_txBuff,fmt,ap);
va_end(ap);
length=strlen((const char*)usart_txBuff);
while((USART2->ISR&0x40)==0);
for(i=0;i<length;i++)
{
USART2->TDR=usart_txBuff[i];
while((USART2->ISR&0x40)==0);
}
}
/* USER CODE END 0 */
3、main.c中添加如下代码
/* USER CODE BEGIN Includes */
#include <stdio.h>
/* USER CODE END Includes */
int main(void)
{
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_Delay(1000);
USART4_printf("This is the signal from serial port 4.\r\n");
USART3_printf("This is the signal from serial port 3.\r\n");
USART2_printf("This is the signal from serial port 2.\r\n");
printf("This is the signal from serial port 1.\r\n");
}
/* USER CODE END 3 */
}
4、最后编译,烧录固件,串口输出如图