江科大stm32学习笔记8——光敏传感器控制蜂鸣器

接线:

 光敏传感器上的AO不接。

接好线后上电,可以看到光敏传感器上亮了两个灯,如果只亮一个,可以尝试加大环境光照或者拿螺丝刀拧上面的蓝色方块。用手遮住前面的电阻只亮一个灯。

代码:

复制粘贴3-4的工程文件,改名为“3-5 光敏传感器控制蜂鸣器”,打开keil,在“Hardware”文件夹里新建“Buzzer.c”、“Buzzer.h”、“LightSensor.c”、“LightSensor.h”四个文件,并输入如下代码:

Buzzer.c:

#include "stm32f10x.h"                  // Device header

void Buzzer_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_InitStructure);
	
	GPIO_ResetBits(GPIOB,GPIO_Pin_12);
}

void Buzzer_ON(void)
{
	GPIO_ResetBits(GPIOB,GPIO_Pin_12);
}

void Buzzer_OFF(void)
{
	GPIO_SetBits(GPIOB,GPIO_Pin_12);
}

void Buzzer_Turn(void)
{
	if(GPIO_ReadOutputDataBit(GPIOB,GPIO_Pin_12) == 0)
	{
		GPIO_SetBits(GPIOB,GPIO_Pin_12);
	}
	else
	{
		GPIO_ResetBits(GPIOB,GPIO_Pin_12);
	}
}

Buzzer.h:

#ifndef __BUZZER_H
#define __BUZZER_H

void Buzzer_Init(void);
void Buzzer_ON(void);
void Buzzer_OFF(void);
void Buzzer_Turn(void);

#endif

 LightSensor.c:

#include "stm32f10x.h"                  // Device header

void LightSensor_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_InitStructure);
}

uint8_t LightSensor_Get(void)
{
	return GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_13);
}

LightSensor.h:

#ifndef __LIGHTSENSOR_H
#define __LIGHTSENSOR_H

void LightSensor_Init(void);
uint8_t LightSensor_Get(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_Get() == 1)
		{
			Buzzer_ON();
		}
		else
		{
			Buzzer_OFF();
		}
	}
}

编译运行成功后,即可通过遮住光敏电阻来控制蜂鸣器。

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-31 07:46:02       91 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-31 07:46:02       97 阅读
  3. 在Django里面运行非项目文件

    2024-01-31 07:46:02       78 阅读
  4. Python语言-面向对象

    2024-01-31 07:46:02       88 阅读

热门阅读

  1. vue2与vue3部分面试题

    2024-01-31 07:46:02       40 阅读
  2. Dubbo的集群容错策略剖析

    2024-01-31 07:46:02       55 阅读
  3. qt学习:多媒体Multimedia摄像头

    2024-01-31 07:46:02       57 阅读
  4. 在 C# 中 checked 和 unchecked 关键字

    2024-01-31 07:46:02       49 阅读
  5. MyBatis-Plus同款ES ORM框架

    2024-01-31 07:46:02       57 阅读
  6. 面试问答总结之ElasticSearch

    2024-01-31 07:46:02       69 阅读