这段代码是初始化 LED 的函数。其中,LED 的引脚通过宏定义的方式定义在另一个头文件中,这里通过编译器的条件编译指令 #ifdef#endif,判断是否定义了这些宏,如果定义了,就调用 GPIO_SetOutput 函数,将引脚设置为输出模式。这里使用了宏定义的方式,可以方便地添加或删除 LED 引脚的定义,提高了代码的可维护性。

#include 'stm32f10x.h'
#include 'myled.h'


void MyLED_Init(void)
{
#ifdef	LED_0_PIN
	GPIO_SetOutput(LED_0_PIN);
#endif
#ifdef	LED_1_PIN
	GPIO_SetOutput(LED_1_PIN);
#endif
#ifdef	LED_2_PIN
	GPIO_SetOutput(LED_2_PIN);
#endif
#ifdef	LED_3_PIN
	GPIO_SetOutput(LED_3_PIN);
#endif
#ifdef	LED_4_PIN
	GPIO_SetOutput(LED_4_PIN);
#endif
#ifdef	LED_5_PIN
	GPIO_SetOutput(LED_5_PIN);
#endif
#ifdef	LED_6_PIN
	GPIO_SetOutput(LED_6_PIN);
#endif
#ifdef	LED_7_PIN
	GPIO_SetOutput(LED_7_PIN);
#endif
#ifdef	LED_8_PIN
	GPIO_SetOutput(LED_8_PIN);
#endif
#ifdef	LED_9_PIN
	GPIO_SetOutput(LED_9_PIN);
#endif
#ifdef	LED_10_PIN
	GPIO_SetOutput(LED_10_PIN);
#endif
#ifdef	LED_11_PIN
	GPIO_SetOutput(LED_11_PIN);
#endif
#ifdef	LED_12_PIN
	GPIO_SetOutput(LED_12_PIN);
#endif
#ifdef	LED_13_PIN
	GPIO_SetOutput(LED_13_PIN);
#endif
#ifdef	LED_14_PIN
	GPIO_SetOutput(LED_14_PIN);
#endif
#ifdef	LED_15_PIN
	GPIO_SetOutput(LED_15_PIN);
#endif
#ifdef	LED_16_PIN
	GPIO_SetOutput(LED_16_PIN);
#endif
#ifdef	LED_17_PIN
	GPIO_SetOutput(LED_17_PIN);
#endif
#ifdef	LED_18_PIN
	GPIO_SetOutput(LED_18_PIN);
#endif
#ifdef	LED_19_PIN
	GPIO_SetOutput(LED_19_PIN);
#endif
#ifdef	LED_20_PIN
	GPIO_SetOutput(LED_20_PIN);
#endif
#ifdef	LED_21_PIN
	GPIO_SetOutput(LED_21_PIN);
#endif
#ifdef	LED_22_PIN
	GPIO_SetOutput(LED_22_PIN);
#endif
#ifdef	LED_23_PIN
	GPIO_SetOutput(LED_23_PIN);
#endif
#ifdef	LED_24_PIN
	GPIO_SetOutput(LED_24_PIN);
#endif
#ifdef	LED_25_PIN
	GPIO_SetOutput(LED_25_PIN);
#endif
#ifdef	LED_26_PIN
	GPIO_SetOutput(LED_26_PIN);
#endif
#ifdef	LED_27_PIN
	GPIO_SetOutput(LED_27_PIN);
#endif
#ifdef	LED_28_PIN
	GPIO_SetOutput(LED_28_PIN);
#endif
#ifdef	LED_29_PIN
	GPIO_SetOutput(LED_29_PIN);
#endif
#ifdef	LED_30_PIN
	GPIO_SetOutput(LED_30_PIN);
#endif
#ifdef	LED_31_PIN
	GPIO_SetOutput(LED_31_PIN);
#endif

}

通过这种方式,即使增加了新的 LED 引脚,也只需要修改头文件中的宏定义,而无需修改源代码,从而提高了代码的可维护性。

STM32F10x LED 初始化代码详解 - 提高代码可维护性

原文地址: https://www.cveoy.top/t/topic/jzAE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录