使用C语言实现LED依次点亮 2022.09.13

 实验效果:

使用C语言实现LED依次点亮 2022.09.13_第1张图片

 使用C语言实现LED依次点亮 2022.09.13_第2张图片

使用C语言实现LED依次点亮 2022.09.13_第3张图片

gpio.h:

#ifndef __GPIO__H__
#define __GPIO__H__ 

//1.RCC寄存器封装,宏定义
#define RCC_AHB4_ENSETR (*(volatile unsigned int *)0x50000A28)

//2.GPIO寄存器封装,用结构体封装
typedef struct
{
	volatile unsigned int MODER;
	volatile unsigned int OTYPER;
	volatile unsigned int OSPEEDR;
	volatile unsigned int PUPDR;
	volatile unsigned int IDR;
	volatile unsigned int ODR;
}gpio_t;

//宏定义GPIOE
#define GPIOE ((gpio_t*)0x50006000)
#define GPIOF ((gpio_t*)0x50007000)

//LED1初始化
void LED1_init();

//LED1点亮
void LED1_on();

//LED1熄灭
void LED1_off();


//LED2初始化
void LED2_init();

//LED2点亮
void LED2_on();

//LED2熄灭
void LED2_off();

//LED3初始化
void LED3_init();

//LED3点亮
void LED3_on();

//LED3熄灭
void LED3_off();


#endif

gpio.c:

#include "gpio.h"

//LED1初始化
void LED1_init()
{
	//设置时钟使能
	RCC_AHB4_ENSETR |= (0x1 << 4);
	//设置PE10为输出模式
	GPIOE->MODER &= (~(0x3 << 20));
	GPIOE->MODER |= (0x1 << 20);
	//设置为推挽输出
	GPIOE->OTYPER &= (~(0x1 << 10));
	//设置为低速模式
	GPIOE->OSPEEDR &= (~(0x3 << 20));
	//设置为禁止上下拉
	GPIOE->PUPDR &= (~(0x3 << 20));
}

//LED1点亮
void LED1_on()
{
	//设置输出高电频
	GPIOE->ODR |= (0x1 << 10);
}

//LED1熄灭
void LED1_off()
{
	//输出低电平
	GPIOE->ODR &= (~(0x1 << 10));
}

//LED2初始化
void LED2_init()
{
	//设置时钟使能
	RCC_AHB4_ENSETR |= (0x1 << 5);
	//设置PE10为输出模式
	GPIOF->MODER &= (~(0x3 << 20));
	GPIOF->MODER |= (0x1 << 20);
	//设置为推挽输出
	GPIOF->OTYPER &= (~(0x1 << 10));
	//设置为低速模式
	GPIOF->OSPEEDR &= (~(0x3 << 20));
	//设置为禁止上下拉
	GPIOF->PUPDR &= (~(0x3 << 20));
}

//LED2点亮
void LED2_on()
{
	//设置输出高电频
	GPIOF->ODR |= (0x1 << 10);
}

//LED2熄灭
void LED2_off()
{
	//输出低电平
	GPIOF->ODR &= (~(0x1 << 10));
}


//LED3初始化
void LED3_init()
{
	//设置时钟使能
	RCC_AHB4_ENSETR |= (0x1 << 4);
	//设置PE10为输出模式
	GPIOE->MODER &= (~(0x3 << 16));
	GPIOE->MODER |= (0x1 << 16);
	//设置为推挽输出
	GPIOE->OTYPER &= (~(0x1 << 8));
	//设置为低速模式
	GPIOE->OSPEEDR &= (~(0x3 << 16));
	//设置为禁止上下拉
	GPIOE->PUPDR &= (~(0x3 << 16));
}

//LED3点亮
void LED3_on()
{
	//设置输出高电频
	GPIOE->ODR |= (0x1 << 8);
}

//LED3熄灭
void LED3_off()
{
	//输出低电平
	GPIOE->ODR &= (~(0x1 << 8));
}

 main.c:

#include "gpio.h"
extern void printf(const char *fmt, ...);
void delay_ms(int ms)
{
	int i,j;
	for(i = 0; i < ms;i++)
		for (j = 0; j < 1800; j++);
}


int main()
{
	LED1_init();
	LED2_init();
	LED3_init();
	while(1)
	{
		LED1_on();
		delay_ms(650);
		LED1_off();
		delay_ms(650);
		LED2_on();
		delay_ms(650);
		LED2_off();
		delay_ms(650);
		LED3_on();
		delay_ms(650);
		LED3_off();
		delay_ms(650);

	}
	return 0;
}

你可能感兴趣的:(c语言,单片机,开发语言)