void USARTx_init(u32 bound)
1.端口结构体设置
GPIO_InitTypeDef GPIO_InitStructure; //定义GPIO结构体
USART_InitTypeDef USART_InitStructure; //定义USART结构体
NVIC_InitTypeDef NVIC_InitStructure; //定义NVIC结构体
2.使能时钟
RCC_AHBxPeriphClockCmd(RCC_AHBxPeriph_GPIOx,ENABLE); //使能GPIO时钟 RCC_APBxPeriphClockCmd(RCC_APBxPeriph_USARTx,ENABLE); //使能USART时钟复3.USART引脚复映射
GPIO_PinAFConfig(GPIOx,GPIO_PinSourcex,GPIO_AF_USARTx); //GPIO口复映射为USART端口
4.GPIO端口配置
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_x; //选择对应引脚
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(GPIOx,&GPIO_InitStructure); //初始化
5.USART初始化设置
USART_InitStructure.USART_BaudRate = bound; //波特率设置 定义USARTx_Init(u32 bound)
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(USARTx, &USART_InitStructure); //初始化串口
USART_Cmd(USARTx, ENABLE); //使能串口
6.串口标志位清零
USART_ClearFlag(USARTx, USART_FLAG_TC);
7.开启串口中断
USART_ITConfig(USARTx, USART_IT_RXNE, ENABLE);
8.NVIC配置
NVIC_InitStructure.NVIC_IRQChannel = USARTx_IRQn; //开启USART通道
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3; //抢占优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority =3; //响应优先级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //开启
NVIC_Init(&NVIC_InitStructure); //初始化
9.串口接受数据,配置中断函数
void USARTx_IRQHandler(void)
{
u8 rec_data;
if(USART_GetITStatus(USARTx, USART_IT_RXNE) != RESET) //
{
rec_data =(u8)USART_ReceiveData(USARTx); //使用USART_ReceiveData(USARTx)读取接收到的数据
if(rec_data=='S') //设置起始位为‘S’
{
uart_byte_count=0x01;
}
else if(rec_data=='E') //终端位为‘E’
{
if(strcmp("Light_led1",(char *)receive_str)==0)
LED1=0; //设置收到数据执行操作,点灯
else if(strcmp("Close_led1",(char *)receive_str)==0)
LED1=1; //设置收到数据执行操作,关灯
for(usart_byte_count=0;usart_byte_count<32;usart_byte_count++)
receive_str[usart_byte_count]=0x00;
usart_byte_count=0;
}
else if((usart_byte_count>0)&&(usart_byte_count<=USARTx_REC_NUM))
{
receive_str[usart_byte_count-1]=rec_data;
usart_byte_count++;
}
}
}
10.串口发送数据,函数
void USARTxSendChar(u8 ch) //u8=char 发送一个字符
{
while((USARTx->SR&0x40)==0);
USARTx->DR = (u8) ch;
}
void USARTxSendChars(u8 *str, u16 strlen) //发送字符串
{
u16 k= 0 ;
do { uart6SendChar(*(str + k)); k++; }
while (k < strlen);
}