一、簡述
本文介紹的是一個.c文件中的內容,主要功能為STM32F101C8T6中USART1的初始化、配置、中斷接收以及發送函數。
#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; //復用推挽輸出
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; //搶占優先級0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //子優先級0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
//USART 初始化設置
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); //開啟串口接受中斷
USART_Cmd(USART1, ENABLE); //使能串口1
}
三、中斷接收函數
void USART1_IRQHandler(){
u8 Temp;
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET){
Temp = USART_ReceiveData(USART1); //讀取接收到的數據
if(USARTx_RX_Count < 4){
USARTx_RX_Buff[USARTx_RX_Count] = Temp;
USARTx_RX_Count++;
}
}
//溢出-如果發生溢出需要先讀SR,再讀DR寄存器則可清除不斷入中斷的問題
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) != SET){
USART_ReceiveData(USART1);
USART_ClearFlag(USART1, USART_FLAG_ORE);
}
USART_ClearFlag(USART1, USART_IT_RXNE); //一定要清除接收中斷
}
四、發送函數
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 != ' 主站蜘蛛池模板: 金川县| 瓦房店市| 延川县| 德格县| 日土县| 德保县| 阜宁县| 高要市| 明水县| 郓城县| 萨迦县| 天祝| 巫山县| 剑阁县| 澳门| 溧水县| 深圳市| 仁寿县| 濮阳市| 衡山县| 陆河县| 万宁市| 保靖县| 峨眉山市| 兴宁市| 西藏| 房山区| 元朗区| 南溪县| 林州市| 颍上县| 平遥县| 罗江县| 枣庄市| 闵行区| 泊头市| 苗栗县| 阳东县| 家居| 武鸣县| 含山县|