一、接线
上电之后可以看到对射式红外传感器亮两个灯,如果此时用挡光片挡住两个黑色方块中间的部分,则只亮一个灯。
二、代码
将4-1的工程文件夹复制粘贴一份,重命名为“5-1 对射式红外传感器计次”,打开keil,右键添加“CountSensor.c”及“CountSensor.h”到“Hardware”文件夹,注意更改文件路径。
CountSensor.c:
#include "stm32f10x.h" // Device headeruint16_t CountSensor_Count;void CountSensor_Init(void)
{RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);GPIO_InitTypeDef GPIO_InitStruture;GPIO_InitStruture.GPIO_Mode = GPIO_Mode_IPU;GPIO_InitStruture.GPIO_Pin = GPIO_Pin_14;GPIO_InitStruture.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOB,&GPIO_InitStruture);GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource14);EXTI_InitTypeDef EXTI_InitStructure;EXTI_InitStructure.EXTI_Line = EXTI_Line14;EXTI_InitStructure.EXTI_LineCmd = ENABLE;EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;EXTI_Init(&EXTI_InitStructure);NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);NVIC_InitTypeDef NVIC_InitStructure;NVIC_InitStructure.NVIC_IRQChannel = EXTI15_10_IRQn;NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;NVIC_Init(&NVIC_InitStructure);
}uint16_t CountSensor_Get(void)
{return CountSensor_Count;
}void EXTI15_10_IRQHandler(void)
{if (EXTI_GetITStatus(EXTI_Line14) == SET){CountSensor_Count ++;EXTI_ClearITPendingBit(EXTI_Line14);}
}
这里我们需要开启GPIOB和AFIO的引脚,并对EXTI中断进行配置。最后这个中断函数的名称不能更改,建议在开始文件中复制粘贴过来。
CountSensor.h:
#ifndef __COUNT_SENSOR_H
#define __COUNT_SENSOR_Hvoid CountSensor_Init(void);
uint16_t CountSensor_Get(void);#endif
main.c:
#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:");while(1) { OLED_ShowNum(1,7,CountSensor_Get(),5);}
}
编译运行成功后,即可看到每遮挡一次,OLED显示的数字便会加一。
版权声明:部分图片来源于网络,仅做教学使用,如有侵权请联系本文作者。