一豹障、簡(jiǎn)述
本文介紹的是一個(gè).c文件中的內(nèi)容,主要功能為STM32F101C8T6中USART1的初始化宿接、配置赘淮、中斷接收以及發(fā)送函數(shù)。
#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_usart.h"
u8 USART1_RX_Buff[4] = {0x00, 0x00, 0x00, 0x00};
u8 USART1_RX_Count = 0;
二睦霎、USART1初始化與配置
void USART1_Init(u32 bound){
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
USART_DeInit(USART1);
//USART1_TX GPIOA.9
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; //復(fù)用推挽輸出
GPIO_Init(GPIOA,&GPIO_InitStructure);
//USART1_RX GPIOA.10
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING; //浮空輸入
GPIO_Init(GPIOA,&GPIO_InitStructure);
//Usart1 NVIC 配置
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //搶占優(yōu)先級(jí)0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //子優(yōu)先級(jí)0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
//USART 初始化設(shè)置
USART_InitStructure.USART_BaudRate = bound;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_WordLength = 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);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //開(kāi)啟串口接受中斷
USART_Cmd(USART1, ENABLE); //使能串口1
}
三梢卸、中斷接收函數(shù)
void USART1_IRQHandler(){
u8 Temp;
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET){
Temp = USART_ReceiveData(USART1); //讀取接收到的數(shù)據(jù)
if(USARTx_RX_Count < 4){
USARTx_RX_Buff[USARTx_RX_Count] = Temp;
USARTx_RX_Count++;
}
}
//溢出-如果發(fā)生溢出需要先讀SR,再讀DR寄存器則可清除不斷入中斷的問(wèn)題
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) != SET){
USART_ReceiveData(USART1);
USART_ClearFlag(USART1, USART_FLAG_ORE);
}
USART_ClearFlag(USART1, USART_IT_RXNE); //一定要清除接收中斷
}
四、發(fā)送函數(shù)
void USART1_TxChar(int ch){
USART_SendData(USART1, (u8)ch);
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
void USART1_TxStr(char *pt){
while(*pt != '\0'){
USARTx_TxChar(*pt);
pt++;
}
}
void USART1_TxCharBuff(u8 buf[], u32 len){
u32 i;
for(i = 0; i < len; i++){
USARTx_TxChar(buf[i]);
}
}