前两行是声明,如果LED没有被定义,就定义LED。
ifndef 和 endif构成括号。
二、GPIO的读取
- GPIO_ReadInputDataBit()(读入指定引脚)
GPIO\_ReadInputDataBit(GPIOB,GPIO_Pin_1);
- GPIO_ReadInputData()(读入指定IO口)
- GPIO_ReadOutputDataBit()(读入指定输出引脚状态)
- GPIO_ReadOutputData()(读入指定输出GPIO状态)
前两个读取输入,后两个读取输出的。
三、封装Key文件
了解1,2之后,可以将按键的开关模块化了。
- Key.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
void Key\_Init(void) {
RCC\_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); // Enable clock for GPIOB
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // Configure GPIO pins as input mode with pull-up resistors
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_11; // Configure GPIO pins 1 and 11
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; // Set GPIO speed to 50MHz
GPIO\_Init(GPIOB, &GPIO_InitStructure); // Initialize GPIOB with the specified configuration
}
uint8\_t Key\_GetNum(void) {
uint8\_t Key_Num = 0;
if (GPIO\_ReadInputDataBit(GPIOB, GPIO_Pin_1) == 0) { // Check if GPIO pin 1 is low
Delay\_ms(20); // Delay for debounce
while (GPIO\_ReadInputDataBit(GPIOB, GPIO_Pin_1) == 0); // Wait for GPIO pin 1 to become high again
Delay\_ms(20); // Delay for debounce
Key_Num = 1; // Set Key\_Num to 1
}
if (GPIO\_ReadInputDataBit(GPIOB, GPIO_Pin_11) == 0) { // Check if GPIO pin 11 is low
Delay\_ms(20); // Delay for debounce
while (GPIO\_ReadInputDataBit(GPIOB, GPIO_Pin_11) == 0); // Wait for GPIO pin 11 to become high again
Delay\_ms(20); // Delay for debounce
Key_Num = 2; // Set Key\_Num to 2
}
return Key_Num; // Return the value of Key\_Num
}
Delay_ms(20)软件按键消抖
- Key.h
#ifndef \_KEY\_H
#define \_KEY\_H
void Key\_Init(void); // Initialize the key
uint8\_t Key\_GetNum(void);
#endif
四、main文件
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "LED.h"
#include "Key.h"
uint8\_t KeyNum;
int main(void)
{
LED\_Init(); // Initialize the LED
Key\_Init(); // Initialize the keys
while (1)
{
KeyNum = Key\_GetNum(); // Get the number of the pressed key
if (KeyNum == 1)
{
LED1\_ON();
}
if (KeyNum == 2)
{
LED1\_OFF();
}
}
}
五、连接电路
以上,就完成了两个按键控制一个LED的工程。
最后
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。
因此收集整理了一份《2024年嵌入式&物联网开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上嵌入式&物联网开发知识点,真正体系化!
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新!!
%以上嵌入式&物联网开发知识点,真正体系化!**
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新!!