光敏传感模块一DO端接B14,GND接GND,VCC接VCC,AO不接。
OLED:SCL接B12,SDA接B13
如图:
#include "stm32f10x.h"
#include "Delay.h" //delay函数所在头文件
#include "OLED.h"
#include "LightSensor.h"
int main(void)
{
OLED_Init();
LightSensor_Init();
while(1)
{
OLED_ShowString(1,3,"count:");
OLED_ShowNum(2,3,get_LightSensorCount(),6);
OLED_ShowString(3,3,"state:");
OLED_ShowNum(4,3,get_LightSensorNum(),6);
}
}
#include "stm32f10x.h"
#include "Delay.h"
uint16_t LightSensorCount;
uint16_t flag;
//初始化LightSensor
void LightSensor_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //设置时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); //配置AFIO中断引脚
GPIO_InitTypeDef GPIOInitStruct;
GPIOInitStruct.GPIO_Mode = GPIO_Mode_IPU; //上拉模式
GPIOInitStruct.GPIO_Pin = GPIO_Pin_14; //B14
GPIOInitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIOInitStruct);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource14); //配置AFIO中断引脚
//配置EXTI
EXTI_InitTypeDef EXTI_InitStruct;
EXTI_InitStruct.EXTI_Line=EXTI_Line14;
EXTI_InitStruct.EXTI_LineCmd=ENABLE;
EXTI_InitStruct.EXTI_Mode=EXTI_Mode_Interrupt;
EXTI_InitStruct.EXTI_Trigger=EXTI_Trigger_Falling;
EXTI_Init(&EXTI_InitStruct);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //中断分组
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel=EXTI15_10_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=1; //抢占优先级
NVIC_InitStruct.NVIC_IRQChannelSubPriority=1; //响应优先级
NVIC_Init(&NVIC_InitStruct);
flag=0;
LightSensorCount=0;
}
//获取传感器结果
uint16_t get_LightSensorCount(void)
{
return LightSensorCount;
}
uint16_t get_flag(void)
{
return flag;
}
//获取传感器结果
uint8_t get_LightSensorNum(void)
{
return GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14);
}
void EXTI15_10_IRQHandler(void)
{
if(EXTI_GetITStatus(EXTI_Line14) == SET)
{
if(get_LightSensorNum()==1)
{
Delay_ms(50);
if(get_LightSensorNum()==1)
{
LightSensorCount++;
flag=1;
}
else
{
flag=0;
}
}
EXTI_ClearITPendingBit(EXTI_Line14);
}
}
#ifndef __LIGHTSENSOR_H
#define __LIGHTSENSOR_H
void LightSensor_Init(void);
unsigned char get_LightSensorNum(void);
uint16_t get_LightSensorCount(void);
uint16_t get_flag(void);
#endif