1.注意,有些光敏传感器的可调电阻需要手动调节

当代码烧录完成,发现蜂鸣器一直响。就需要调节可调电阻,旋转可调电阻中间位置,

光敏传感器有两个指示灯,微调介于闪两个灯或者闪一个灯的情况。手遮住和手拿开可以看到,蜂鸣器响和停,说明调节完成。

2.实现代码

buzzer.c

#include "stm32f10x.h"                  // Device header
void Buzzer_init(void){
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
	GPIO_InitTypeDef GPIO_Structure;
	GPIO_Structure.GPIO_Mode=GPIO_Mode_Out_PP;
	GPIO_Structure.GPIO_Pin=GPIO_Pin_12;
	GPIO_Structure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_Structure);

	GPIO_SetBits(GPIOB,GPIO_Pin_12);
}

void Buzzer_on(void){
	GPIO_ResetBits(GPIOB,GPIO_Pin_12);
}
void Buzzer_off(void){
	GPIO_SetBits(GPIOB,GPIO_Pin_12);
}

buzzer.h

#ifndef __BUZZER_H
#define __BUZZER_H
void Buzzer_init(void);
void Buzzer_on(void);
void Buzzer_off(void);

#endif

lightsensor.c

GPIO_Structure.GPIO_Mode=GPIO_Mode_IPU;注意GPIO的模式
#include "stm32f10x.h"                  // Device header
void  Lightsensor_init(void){
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
	GPIO_InitTypeDef  GPIO_Structure;
	GPIO_Structure.GPIO_Mode=GPIO_Mode_IPU;
	GPIO_Structure.GPIO_Pin=GPIO_Pin_13;
	GPIO_Structure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_Structure);
}
uint8_t Lightsensor_getNum(void){
	return GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_13);
}

lightsensor.h

#ifndef __LIGHTSENSOR_H
#define __LIGHTSENSOR_H
#include "stm32f10x.h"                  // Device header

void Lightsensor_init(void);
uint8_t Lightsensor_getNum(void);

#endif

main.c

#include "stm32f10x.h"                  // Device header
#include "Delay.h"
#include "buzzer.h"
#include "lightsensor.h"


int main(void){

	Buzzer_init();
	Lightsensor_init();
	while(1){
		if(Lightsensor_getNum()==1){
			Buzzer_on();
		}else
		{
			Buzzer_off();
		}
	}

}

修仙一途,道阻且长,共勉!

Logo

智能硬件社区聚焦AI智能硬件技术生态,汇聚嵌入式AI、物联网硬件开发者,打造交流分享平台,同步全国赛事资讯、开展 OPC 核心人才招募,助力技术落地与开发者成长。

更多推荐