写一个stm322个按键控制灯,第一个按键控制灯交替闪烁熄灭,第二个按键控制俩个灯同时亮灭,需要有led.c和led.h,key.c和key.h,芯片基于stm32F103R6,led灯的端口号PA6
时间: 2025-01-19 17:15:54 浏览: 67
好的,下面是一个基于STM32F103R6的示例代码,包含led.c、led.h、key.c和key.h文件。这个示例代码实现了两个按键控制LED灯的功能:
1. 第一个按键控制一个LED灯交替闪烁和熄灭。
2. 第二个按键控制两个LED灯同时亮灭。
首先,创建led.h文件:
```c
// led.h
#ifndef LED_H
#define LED_H
#include "stm32f10x.h"
void LED_Init(void);
void LED_On(void);
void LED_Off(void);
void LED_Toggle(void);
#endif
```
接下来,创建led.c文件:
```c
// led.c
#include "led.h"
#define LED_PIN GPIO_Pin_6
#define LED_GPIO_PORT GPIOA
#define LED_GPIO_CLK RCC_APB2Periph_GPIOA
void LED_Init(void) {
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(LED_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_GPIO_PORT, &GPIO_InitStructure);
GPIO_SetBits(LED_GPIO_PORT, LED_PIN);
}
void LED_On(void) {
GPIO_ResetBits(LED_GPIO_PORT, LED_PIN);
}
void LED_Off(void) {
GPIO_SetBits(LED_GPIO_PORT, LED_PIN);
}
void LED_Toggle(void) {
GPIO_WriteBit(LED_GPIO_PORT, LED_PIN, (BitAction)(1 - GPIO_ReadOutputDataBit(LED_GPIO_PORT, LED_PIN)));
}
```
然后,创建key.h文件:
```c
// key.h
#ifndef KEY_H
#define KEY_H
#include "stm32f10x.h"
void KEY_Init(void);
uint8_t KEY_GetState(uint8_t key);
#endif
```
接下来,创建key.c文件:
```c
// key.c
#include "key.h"
#define KEY1_PIN GPIO_Pin_0
#define KEY1_GPIO_PORT GPIOA
#define KEY1_GPIO_CLK RCC_APB2Periph_GPIOA
#define KEY2_PIN GPIO_Pin_1
#define KEY2_GPIO_PORT GPIOA
#define KEY2_GPIO_CLK RCC_APB2Periph_GPIOA
void KEY_Init(void) {
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(KEY1_GPIO_CLK | KEY2_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = KEY1_PIN | KEY2_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
uint8_t KEY_GetState(uint8_t key) {
if (key == 1) {
return GPIO_ReadInputDataBit(KEY1_GPIO_PORT, KEY1_PIN);
} else if (key == 2) {
return GPIO_ReadInputDataBit(KEY2_GPIO_PORT, KEY2_PIN);
}
return 1;
}
```
最后,在主函数中实现按键控制LED灯的功能:
```c
// main.c
#include "stm32f10x.h"
#include "led.h"
#include "key.h"
int main(void) {
uint8_t key1State, key2State;
LED_Init();
KEY_Init();
while (1) {
key1State = KEY_GetState(1);
key2State = KEY_GetState(2);
if (key1State == 0) {
LED_Toggle();
while (KEY_GetState(1) == 0); // 等待按键释放
}
if (key2State == 0) {
LED_On();
while (KEY_GetState(2) == 0); // 等待按键释放
LED_Off();
}
}
}
```
阅读全文
相关推荐


















