STM32CubeIDE学习记录(按键点灯工程)

博主使用的开发板以及相关外设连接如下:




芯片型号为:STM32F103RCT6

新建STM32CubeIDE项目

image



配置完成后会生成相应的文件并进入如下界面:

  • 使用外部晶振时钟
    image

配置相关GPIO口

(LED:PA8,PD2;KEY:PC5, PA15, PA0)

LED配置(GPIO_OutPut):


image

KEY配置(GPIO_Input):


image

并在User Label框中进行重命名,方便理解与编程。

时钟信号配置


image
image

构建项目

image
点击即可生成相应代码。

工作目录


编辑程序

分别添加文件:led.h, led.c, key.h, key.c
led.h

#include "stm32f1xx.h"
#include "main.h"

void LED0_INV();
void LED1_INV();
void LED_INIT();

led.c

#include "led.h"

void LED0_INV(){
	HAL_GPIO_TogglePin(LED0_GPIO_Port, LED0_Pin);
}

void LED1_INV(){
	HAL_GPIO_TogglePin(LED1_GPIO_Port, LED1_Pin);
}

void LED_INIT(){
	HAL_GPIO_WritePin(LED0_GPIO_Port, LED0_Pin, GPIO_PIN_SET);
	HAL_Delay(500);
	HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_SET);
	HAL_Delay(500);
}

key.h

#include "stm32f1xx.h"
#include "main.h"

#define KEY0        HAL_GPIO_ReadPin(KEY0_GPIO_Port,KEY0_Pin)
#define KEY1        HAL_GPIO_ReadPin(KEY1_GPIO_Port,KEY1_Pin)
#define WK_UP       HAL_GPIO_ReadPin(KEY_INIT_GPIO_Port,KEY_INIT_Pin)

#define KEY0_PRES 	1
#define KEY1_PRES	2
#define WKUP_PRES   3


uint8_t KEY_Scan(uint8_t mode);

key.c

#include "key.h"

//Mode 0: Support continuous pressing, Mode 1: Do not support continuous pressing
//return 0: no pressing

uint8_t KEY_Scan(uint8_t mode)
{
	static uint8_t key_up=1;
	if(mode)key_up=1;
    if(key_up&&(KEY0==0||KEY1==0||WK_UP==1))
	{
		HAL_Delay(10);
		key_up=0;
        if(KEY0==0)       return KEY0_PRES;
        else if(KEY1==0)  return KEY1_PRES;
        else if(WK_UP==1) return WKUP_PRES;
    }else if(KEY0==1&&KEY1==1&&WK_UP==0)key_up=1;
	return 0;
}

在main函数中添加如下代码:

  /* USER CODE BEGIN 2 */
	uint8_t key=0;
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		key=KEY_Scan(0);
		switch(key)
		{
			case KEY0_PRES:
				LED0_INV();
				break;
			case KEY1_PRES:
				LED1_INV();
				break;
			case WKUP_PRES:
				LED_INIT();
				break;
			default:
				HAL_Delay(10);
		}
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */

生成hex文件


点击编译即可生成
image

posted @ 2022-06-23 18:35  litecdows  阅读(222)  评论(0编辑  收藏  举报