stm32f407单片机:串口通信

1.串口初始化
2.串口发送
3.串口接收

//串口初始化
USART_init(void)
{
	USART_InitTypeDef USART_InitStructure;
	GPIO_InitTypeDef GPIO_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;

	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);       //使能GPIOA时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);		//使能USART1时钟

	//连接GPIO引脚到串口
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);
   
    //GPIO 初始化 
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
   
    //配置 Tx 引脚为复用功能
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 ;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
   
    //配置 Rx 引脚为复用功能
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
   
    USART_InitStructure.USART_BaudRate = 2500;//波特率设置
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长(数据位+校验位):8 
	USART_InitStructure.USART_StopBits = USART_StopBits_1;//停止位: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 模式控制:同时使能接收和发送 
	USART_Init(USART1, &USART_InitStructure);//完成 USART 初始化配置 

	//中断配置
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//中断分组
	NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;//配置 USART1 为中断源 
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;//抢断优先级为 1 
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;//子优先级为 1 
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;//使能中断 
	NVIC_Init(&NVIC_InitStructure);

	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//使能串口接收中断 
	USART_Cmd(USART1, ENABLE);//使能串口
}
//串口发送
void SendData(void)
{
	USART_SendData(USART1,ADC_value);//发送16位的数据
    while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);//等待发送完成
}

//串口接收
void USART1_IRQHandler(void)
{
  if (USART_GetITStatus(USART1,USART_IT_RXNE)!=RESET) 
  {
    data = USART_ReceiveData( USART1 );
  }
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值