接线图
按键按下,旋转编码器输出低电平
Encoder.c
#include "stm32f10x.h" // Device header
int16_t Encoder_Count;
void Encoder_init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); // 开启APB2Periph外设GPIOB时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); // 开启APB2Periph外设AFIO时钟
// 配置GPIO
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);
// 配置EXTI
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource0); // 配置中断GPIOB、pin0
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource1); // 配置中断GPIOB、pin1
EXTI_InitTypeDef EXTI_InitStructure; // 配置EXTI_InitStructure参数
EXTI_InitStructure.EXTI_Line = EXTI_Line0 | EXTI_Line1; // 线14
EXTI_InitStructure.EXTI_LineCmd = ENABLE; // 开启
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; // 中断模式
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; // 下降沿触发
EXTI_Init(&EXTI_InitStructure);
// 配置NVIC
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); // 设置2位响应优先级2位抢占
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel= EXTI0_IRQn; // 设置0
NVIC_InitStruct.NVIC_IRQChannelCmd= ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority= 1; //设置抢占Preemption和响应优先级为1
NVIC_InitStruct.NVIC_IRQChannelSubPriority= 1;
NVIC_Init(&NVIC_InitStruct);
NVIC_InitStruct.NVIC_IRQChannel= EXTI1_IRQn; // 设置1
NVIC_InitStruct.NVIC_IRQChannelCmd= ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority= 1; //设置抢占Preemption和响应优先级为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) // 当pin0中断时,判断Pin1是否为低电平 默认低电平触发
{
Encoder_Count --;
}
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
void EXTI1_IRQHandler(void)
{
if(EXTI_GetITStatus(EXTI_Line1) == SET)
{
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_0) == 0) // 当pin1中断时,判断Pin0是否为低电平
{
Encoder_Count ++;
}
EXTI_ClearITPendingBit(EXTI_Line1);
}
}
Encoder.h
#ifndef __ENCODER_H
#define __ENCODER_H
void Encoder_init(void);
int16_t Encoder_Get(void);
#endif
main.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "Encoder.h"
int16_t Num;
int main(void)
{
OLED_Init();
Encoder_init();
OLED_ShowString(1,3,"Num:"); // 字符串用双引号括起来
while(1)
{
Num += Encoder_Get();
OLED_ShowSignedNum(1,7,Num,5);
}
}