需求: 用旋转编码器实现计数num1变量+1,当数字到达10后,清0,并触发外部定时中断使num2变量+1
原理图设计: 编写: 旋转编码器使num_1变量计数+1 ①实现初始化显示屏,确保能显示数据 然后编写外部中断
②添加新的.c.h文件,在new.c文件中初始化中断(GPIO,AFIO,EXTI,NVIC)
③外部中断的意思是,当引脚电平发生变化后,就停止当前程序的执行,执行中断程序 所以,这里需要 1.配置GPIO的引脚 2.配置完引脚后,需要配置AFIO中断引脚选择 开启AFIO时钟
3.将使用的GPIO连接EXIT 看这里
该函数:@brief Selects the GPIO pin used as EXTI Line.
4.此时已连接到了中断位,那么就需要配置EXTI结构体
5.配置NVIC,选择优先级 自此,中断配置就配置完成了,选择写中断函数
④中断函数编写 记得用完后去除标志位
整体代码(AddNum.c)看下
#include "stm32f10x.h"
int16_t Encoder_Count;
void AddNum_Init(void){
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource0);
EXTI_InitTypeDef EXTI_InitStruct;
EXTI_InitStruct.EXTI_Line = EXTI_Line0;
EXTI_InitStruct.EXTI_LineCmd = ENABLE;
EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_Init(&EXTI_InitStruct);
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStruct);
}
int16_t Encoder_Get(void){
int16_t Temp;
Temp = Encoder_Count;
Encoder_Count = 0;
return Temp;
}
void EXTI0_IRQHandler(void){
if(EXTI_GetITStatus(EXTI_Line0) == SET){
if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1) == 0)
{
if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0) == 0)
{
Encoder_Count++;
}
}
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
|