STM32-串口中断编程实验
2026/6/8 15:20:11 网站建设 项目流程

通过单片机上的串口将单片机与电脑连接在一起,通过电脑上的串口调试助手向单片机内发送数据,改变板载LED的闪烁频率

#include "stm32f10x.h"
#include "delay.h"

uint32_t blinkInterval = 1000;//闪灯间隔,变量,1000只是初值

void APP_OnBoard_LED(void);
void APP_USART1_Init(void);

int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

APP_OnBoard_LED();
APP_USART1_Init();

while(1)
{
GPIO_WriteBit(GPIOC, GPIO_Pin_13, Bit_RESET);//亮
Delay(blinkInterval);//延迟
GPIO_WriteBit(GPIOC, GPIO_Pin_13, Bit_SET);//灭
Delay(blinkInterval);//延迟
}
}

//编写中断响应函数
void USART1_IRQHandler(void){
if(USART_GetFlagStatus(USART1, USART_FLAG_RXNE)== SET){//确保中断是由RXNE标志位触发的
uint8_t dataRCVD = USART_ReceiveData(USART1);
if(dataRCVD == '0'){
blinkInterval = 1000;
}
else if(dataRCVD == '1'){
blinkInterval = 200;
}
else if(dataRCVD == '2'){
blinkInterval = 50;
}
}
}

//初始化串口
void APP_USART1_Init(void){

//#1.引脚初始化

GPIO_InitTypeDef GPIO_InitStruct;

//Tx引脚 PA9 AF_PP
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz;

GPIO_Init(GPIOA, &GPIO_InitStruct);

//Rx引脚 PA10 IPU
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;

GPIO_Init(GPIOA, &GPIO_InitStruct);

//#2.串口初始化

USART_InitTypeDef USART_InitStruct;

RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

USART_InitStruct.USART_BaudRate = 115200;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;

USART_Init(USART1, &USART_InitStruct);

//闭合总开关
USART_Cmd(USART1, ENABLE);

//#3.配置中断
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);

//#4.配置NVIC

NVIC_InitTypeDef NVIC_InitStruct;

NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;//中断的名称,见顶部头文件stm32f10x.h
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;//抢占优先级
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;//子优先级
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;//闭合中断开关

NVIC_Init(&NVIC_InitStruct);

}

//初始化LED引脚 PC13 通用开漏
void APP_OnBoard_LED(void){

RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;

GPIO_InitStruct.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_OD;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz;

GPIO_Init(GPIOC, &GPIO_InitStruct);
}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询