STM32串行口中断(0918)

串口通讯(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");
	}
}

在串口助手处打开所对应串口,即可接收到所打印的字符串。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值