串口通讯(Serial Communication)是一种设备间非常常用的串行通讯方式。
异步通讯中没有时钟信号,只有起始位,数据位,奇偶校验位,停止位。
异步通讯中我们使用了USART(通用同步异步收发器)。
TX:发送数据输出引脚。
RX:接收数据输入引脚。
目的:在串口调试助手上显示文字。
需要进行一系列配置和初始化,并且重定向printf函数中的fputc。
GPIO初始化:
void init_uart_gpio(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// USART Tx GPIO
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// USART Rx GPIO
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
初始化串口配置:
void init_uart1(void)
{
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No ;
USART_InitStructure.USART_HardwareFlowControl =USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
}
初始化串口中断(使串口接收中断,打开工作时钟)
void init_uart_it(void)
{
USART_Cmd(USART1, ENABLE);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
}
初始化总中断:
void init_uart_nvic(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
重定向fputc:
void Usart_SendByte( USART_TypeDef * pUSARTx, uint8_t ch)
{
USART_SendData(pUSARTx,ch);
while (USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET);
}
int fputc(int ch, FILE *f)
{
Usart_SendByte(USART1,ch);
return ch;
}
需配置在禁主机模式下:
#pragma import(__use_no_semihosting) //
void _sys_exit(int x)
{
x = x;
}
struct __FILE //
{
int handle;
最后是主函数:
void delay()
{
int i,j;
for(i=0;i<100;i++){
for(j=0;j<100;j++){
}
}
}
int main()
{
init_uart();
while(1){
delay();
printf("chanhhbin\n");
}
}
在串口助手处打开所对应串口,即可接收到所打印的字符串。