接线图
原理图:
CountSensor.c
cpp
#include "stm32f10x.h" // Device header
uint16_t CountSensor_Count;
void CountSensor_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_14;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
// 配置EXTI
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource14); // 配置中断GPIOB、pin14
EXTI_InitTypeDef EXTI_InitStructure; // 配置EXTI_InitStructure参数
EXTI_InitStructure.EXTI_Line = EXTI_Line14; // 线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= EXTI15_10_IRQn; // 设置15-10
NVIC_InitStruct.NVIC_IRQChannelCmd= ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority= 1; //设置抢占Preemption和响应优先级为1
NVIC_InitStruct.NVIC_IRQChannelSubPriority= 1;
NVIC_Init(&NVIC_InitStruct);
}
uint16_t CountSensor_Get(void)
{
return CountSensor_Count;
}
void EXTI15_10_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line14) == SET)// 10-15都能进来,判断是否是14进入,取值SET、RESET
{
CountSensor_Count ++; // 每执行一次中断计数加一
EXTI_ClearITPendingBit(EXTI_Line14); // 每次中断结束后,清除标志位,要不会卡死
}
}
CountSensor.h
cpp
#ifndef __COUNTSENSOR_H
#define __COUNTSENSOR_H
void CountSensor_Init(void);
// 中断函数不需要导入,会自动执行
uint16_t CountSensor_Get(void);
#endif
main.c
cpp
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "CountSensor.h"
int main(void)
{
OLED_Init();
CountSensor_Init();
OLED_ShowString(1,1,"Count:"); // 字符串用双引号括起来
//OLED_ShowString(1,3," "); //清除某一部分
while(1)
{
OLED_ShowNum(1,7,CountSensor_Get(),3);
}
}
效果图