stm32F407 连接 对射式红外对管 样例

本次样例,是利用 Led 灯来作为红外对管的显示,串口打印作为协助

stm32F407开发板上有两个led灯,DS0和DS1

所以需要编写的代码涉及:led.h、led.c、hong.c、hong.h、main.c (串口代码已集成)                 

直接上代码:

led.h

#ifndef __LED_H
#define __LED_H
void LED_Init();
#endif

hong.h

#ifndef __HONG_H
#define __HONG_H
void Hong_Init();
#endif

led.c

#include "stm32f4xx.h"
#include "led.h"
void LED_Init()
{
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF,ENABLE);
	GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_10 | GPIO_Pin_9;
	GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_OUT;
	GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOF,&GPIO_InitStructure);
	GPIO_SetBits(GPIOF,GPIO_Pin_9 | GPIO_Pin_10);
}

hong.c

#include "hong.h"
#include "stm32f4xx.h"
void Hong_Init()
{
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE,ENABLE);
	GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_0;
	GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_IN;
	GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOE,&GPIO_InitStructure);
}

main.c 

#include "stm32f4xx.h"
#include "led.h"
#include "usart.h"
#include "delay.h"
#include "hong.h"
int main()
{
	uint8_t data ;//存放IO读到的电平
	delay_init(168);
	uart_init(115200);
	LED_Init();
	Hong_Init();  //红外对管的OUT引脚接口初始化
	GPIO_SetBits(GPIOF,GPIO_Pin_9|GPIO_Pin_10);//两个led灯初始化为亮
	while(1)
	{
		data = GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_0); //读取低电平
		if(0 < data)  //红外对管无遮挡时高电平,有遮挡时为低电平
		{
			GPIO_ResetBits(GPIOF,GPIO_Pin_9);
			GPIO_SetBits(GPIOF,GPIO_Pin_10);
			delay_ms(1000);
			printf("data = 1 \n");  //利用串口协助打印,观看程序执行效果
		}
		else
		{
			GPIO_ResetBits(GPIOF,GPIO_Pin_10);
			GPIO_SetBits(GPIOF,GPIO_Pin_9);
			delay_ms(1000);
			printf("data = 0. \n");
		}
	}
}

 

你可能感兴趣的:(STM32)