原理:PD2为使能端,高电平使能。使能的时候,给PC8-PC15高电平即可点亮LED。
CUBE里将这些端口设置为GPIO输出模式,将PC8-15初始电平设置为高电平(这样一上电就不会亮),PD2默认低电平,不用管,然后生成代码即可,如下图:
生成的工程文件里新建一个bsp文件夹,后续新建的其他文件都放进这个文件夹,记得把这个文件的路径添加进头文件路径。
封装代码如下:
led.c
#include "led.h"
void Led(uint8_t addr,uint8_t enable)
{
static uint16_t temp = 0x0000;
static uint16_t temp_old = 0xffff;
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_All, GPIO_PIN_SET);
if(enable)
temp |= 0x0100 << addr;
else
temp &= ~(0x0100 << addr);
if(temp != temp_old)
{
HAL_GPIO_WritePin(GPIOC, temp, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_RESET);
temp_old = temp;
}
}
led.h
#ifndef __led_h
#define __led_h
#include "main.h"
void Led(uint8_t addr,uint8_t enable);
#endif
主函数里记得加上led的头文件:#include "led.h"
如需点亮LD7,主函数while(1)里添加:
Led(6,1);
如需熄灭LD7,主函数while(1)里添加:
Led(6,0);