写一个STM32单片机控制8个LED灯的包含属性、对象、状态、延时、控制封装结构。要给出最优的封装的全部代码,而且只能使用STM32标准库,不能使用HAL库或者LL库
时间: 2024-06-12 16:03:28 浏览: 93
寄存器GPIO学习之按键操作点灯(记录个人学习)
属性:
- 灯的编号(0-7)
- 灯的状态(开/关)
对象:
- LED灯
状态:
- 亮
- 灭
延时:
- 控制LED灯亮灭的延时时间
控制封装结构:
```c
#include "stm32f10x.h"
#include "stdio.h"
#define LED_GPIO GPIOA
#define LED_GPIO_CLK RCC_APB2Periph_GPIOA
typedef struct {
uint8_t led_num; // 灯的编号,0-7
GPIO_TypeDef* gpio; // 灯所在的GPIO
uint16_t gpio_pin; // 灯所在的GPIO的引脚
uint8_t state; // 灯的状态,0-灭,1-亮
} LED;
void LED_Init(LED* led) {
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(LED_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = led->gpio_pin;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(led->gpio, &GPIO_InitStructure);
LED_OFF(led);
}
void LED_ON(LED* led) {
led->state = 1;
GPIO_SetBits(led->gpio, led->gpio_pin);
}
void LED_OFF(LED* led) {
led->state = 0;
GPIO_ResetBits(led->gpio, led->gpio_pin);
}
void LED_Toggle(LED* led) {
if (led->state == 0) {
LED_ON(led);
} else {
LED_OFF(led);
}
}
void delay_ms(uint32_t ms) {
volatile uint32_t nCount;
RCC_ClocksTypeDef RCC_Clocks;
RCC_GetClocksFreq(&RCC_Clocks);
nCount = (RCC_Clocks.HCLK_Frequency / 10000) * ms;
for (; nCount != 0; nCount--);
}
int main(void) {
LED leds[8] = {
{0, LED_GPIO, GPIO_Pin_0, 0},
{1, LED_GPIO, GPIO_Pin_1, 0},
{2, LED_GPIO, GPIO_Pin_2, 0},
{3, LED_GPIO, GPIO_Pin_3, 0},
{4, LED_GPIO, GPIO_Pin_4, 0},
{5, LED_GPIO, GPIO_Pin_5, 0},
{6, LED_GPIO, GPIO_Pin_6, 0},
{7, LED_GPIO, GPIO_Pin_7, 0},
};
for (int i = 0; i < 8; i++) {
LED_Init(&leds[i]);
}
while (1) {
for (int i = 0; i < 8; i++) {
LED_ON(&leds[i]);
delay_ms(1000);
LED_OFF(&leds[i]);
}
}
}
```
阅读全文