光敏传感器模块和LED接线
LED负极接B12,正极接VCC
光敏传感模块一DO端接B13,GND接GND,VCC接VCC,AO不接。
如图:
主程序代码:main.c
#include "stm32f10x.h"
#include "Delay.h" //delay函数所在头文件
#include "LED.h"
#include "LightSensor.h"int main(void)
{ LED_Init(); //初始化LEDLED_OFF(); //默认LED灭LightSensor_Init(); //初始化光敏传感器while(1){if(get_LightSensorNum() == 1) //黑暗时LED亮{LED_ON();}else{LED_OFF();}}
}
LED.h和LED.c
LED.h
#ifndef __LED_H
#define __LED_Hvoid LED_Init(void);
void LED_ON(void);
void LED_OFF(void);#endif
LED.c
#include "stm32f10x.h"void LED_Init(void)
{RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //设置时钟GPIO_InitTypeDef GPIOInitStruct;GPIOInitStruct.GPIO_Mode = GPIO_Mode_Out_PP; //推挽模式GPIOInitStruct.GPIO_Pin = GPIO_Pin_12; //B12GPIOInitStruct.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOB, &GPIOInitStruct);GPIO_SetBits(GPIOB, GPIO_Pin_12); // 不亮}void LED_ON(void)
{GPIO_ResetBits(GPIOB, GPIO_Pin_12); // 亮
}void LED_OFF(void)
{GPIO_SetBits(GPIOB, GPIO_Pin_12); // 不亮
}
LightSensor.h和LightSensorc
LightSensor.h
#ifndef __LIGHTSENSOR_H
#define __LIGHTSENSOR_Hvoid LightSensor_Init(void);
unsigned char get_LightSensorNum(void);#endif
LightSensor.c
#include "stm32f10x.h"
#include "Delay.h" //初始化LightSensor
void LightSensor_Init(void)
{RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //设置时钟GPIO_InitTypeDef GPIOInitStruct;GPIOInitStruct.GPIO_Mode = GPIO_Mode_IPU; //上拉模式GPIOInitStruct.GPIO_Pin = GPIO_Pin_13; //B13GPIOInitStruct.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOB, &GPIOInitStruct);
}//获取传感器结果
uint8_t get_LightSensorNum(void)
{return GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_13);
}