新手上路
- 积分
- 22
- 金钱
- 22
- 注册时间
- 2019-7-19
- 在线时间
- 4 小时
|
4金钱
#include "usart3.h"
void uart3_init(u32 bound)
{
//GPIO端口设置
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD,ENABLE); //使能USART1,GPIOA时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);
GPIO_PinAFConfig(GPIOD,GPIO_PinSource8,GPIO_AF_USART3); //GPIOA9复用为USART1
GPIO_PinAFConfig(GPIOD,GPIO_PinSource9,GPIO_AF_USART3);
USART_DeInit(USART3); //复位串口1
//USART3_TX PB.10
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8|GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//复用功能
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉
GPIO_Init(GPIOD,&GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = bound;//一般设置为9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式
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(USART3, &USART_InitStructure); //初始化串口
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);//开启中断
USART_Cmd(USART3, ENABLE); //使能串口
}
u16 dis;
float distance;
u8 Res;
u8 buff[10];
u16 check=0;
void USART3_IRQHandler(void) //串口1中断服务程序
{
static u8 counter=0;
static _Bool find_head=0;
if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET) //接收中断(接收到的数据必须是0x0d 0x0a结尾)
{
Res =USART_ReceiveData(USART3); //读取接收到的数据
if(Res!=0xff&&find_head==0)
{
return;
}
else if(Res==0xff)
{
find_head=1;
}
if(find_head==1)
{
buff[counter]=Res;
counter++;
if(counter>3)
{
check=0xff+buff[1]+buff[2];
check&=0x00ff;
if(buff[3]!=(u8)check)
{
counter=0;
find_head=0;
return;
}
else
{
dis=buff[1]<<8|buff[2];
distance=dis;
if(distance>=2000) distance=2000;
find_head=0;
counter=0;
}
}
}
}
}
|
|