STM32_F1xx-MDK+CubeMX+vsCode 基础使用

一、安装教程(转载)

【stm32学习笔记】Keil5+stm32cubemx安装使用教程(准备步骤)_keil cube-优快云博客文章浏览阅读1.4w次,点赞39次,收藏133次。目录(一)keil5+mdk(1)keil是什么?(2)keil5的安装(3)keil5的破解(mdk)本片文章将主要介绍keil5和cube的安装流程(一)keil5+mdk(1)keil是什么?通俗的来说keil就是用来写代码的,不管是写什么代码肯定都需要一个IDE比如说理工专业的基础课一般都会有C语言或者python等课程,可能用过Code::Blocks,Eclipse,Visual Studio等软件,keil与他们类似,只是它同时集成了编译、烧录等一系列功能,同时具有一些自己特有的标识_keil cubehttps://blog.youkuaiyun.com/weijie_wang/article/details/120756019https://blog.youkuaiyun.com/weijie_wang/article/details/120756019https://blog.youkuaiyun.com/weijie_wang/article/details/120756019

抛弃keil?VScode开发stm32完整教程_哔哩哔哩_bilibili

VSCode+Keil5+STM32CubeMX开发环境搭建,一步不跳,一刀不剪,奶奶都能学会版。主要是配置插件Keil assistant,介绍相关使用方法。_哔哩哔哩_bilibili

二、建立工程

(一)、选择开发板

(二)、常规MX配置

更换烧录调试设置(必须配置!!!否则会锁板子)

启用外部高速晶振

在右边那一竖列随便输一个72,然后回车如下

再次回车得到如下

更改".c",".h"配置文件的生成(大工程必备)

精简工程,减少编译时间

设置工程路径和名称,并生成

(三)、常规MDK配置

pack包离线下载(转载)

Keil MDK5.38 STM32全系列 最新PACK包离线包高速网盘下载分享收藏(持续更新...)_keil pack 大全-优快云博客

工程编译,ST-Link烧录前配置

可以使用最新的版本(非必要)

代码优化等级(非必要)

烧录配置(必选) 

确认退出

MDK中文配置(转载)

Keil中文显示设置_keil uvision5怎么改成中文版-优快云博客

MDK格式化配置(转载)

Keil5-MDK的格式化代码工具及添加快捷方式_keil5格式化代码-优快云博客

踩坑记录

慎用MicroLIB(精简的嵌入式C语言标准库内容,阉割了部分功能)

三、工程结构

2024_8_13

(一)、书写结构(个人)

参考文章:

STM32CubeIDE的初始main.c里都是什么_user code begin pfp什么意思-优快云博客

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

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

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
 USER CODE BEGIN Header (添加头部注释或代码)

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */

Private includes(用户私有头文件定义)
 /* Private includes ----------------------------------------------------------*/
 /* USER CODE BEGIN Includes */

/* USER CODE END Includes */
Private typedef(用户私有类型定义)

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

Private define(用户私有宏定义)

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

Private macro(宏指令?)

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

Private variables(用户私有变量定义)

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

Private function prototypes(用户私有函数原型)
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */
Private user code(用户主要逻辑代码书写区域)

/* Private user code ---------------------------------------------------------*/

(二)、驱动记录

1、串口重定向(转载)

STM32F1系列HAL库配置串口通信(2)——串口重定向以及log信息格式输出_hal 重定向-优快云博客

【STM32】HAL库 STM32CubeMX教程四—UART串口通信详解「建议收藏」-腾讯云开发者社区-腾讯云 (tencent.com)

普通串口使用(堵塞发送,接收) 

 重定向配置: 

#include<stdio.h>
char ch;
int fputc(int ch,FILE *f)
{
    //采用轮询方式发送1字节数据,超时时间设置为无限等待
    HAL_UART_Transmit(&huart1,(uint8_t *)&ch,1,HAL_MAX_DELAY);
    return ch;
}

int fgetc(FILE *f)
{
    uint8_t ch;
    // 采用轮询方式接收 1字节数据,超时时间设置为无限等待
    HAL_UART_Receive( &huart1,(uint8_t*)&ch,1, HAL_MAX_DELAY );
    return ch;
}

使用例1:

        ch=getchar();
        putchar(ch);

使用例2:

printf("Hello\n");			
HAL_Delay(1000);

2、模拟USB口通讯(转载)

还不快放弃串口通信!投怀于USB吧 ୧⍢⃝୨

 发送函数

while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    CDC_Transmit_FS("Hello",6);
    HAL_Delay(500);
    HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_13);
  }

中断接收并串口回传


static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
  /* USER CODE BEGIN 6 */
  CDC_Transmit_FS(Buf, *Len);
  USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
  USBD_CDC_ReceivePacket(&hUsbDeviceFS);
  return (USBD_OK);
  /* USER CODE END 6 */
}

这一句是新加的,用于在接收到数据的时候回传 

3、串口中断接收

参考文章:stm32使用HAL库配置串口中断收发数据(保姆级教程)_stm32 hal库 串口收发程序-优快云博客

stm32fixx_it.c —> USART1_IRQHandler函数定义 —> 

__weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
回调函数弱定义位置

对此函数在main.c中重定义


void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1) // ???????????? USART1
    {
        if (rx_data[0] == '0') // ??????????? 0
        {
            HAL_UART_Transmit_IT(&huart1, (uint8_t*)tx_data2, strlen(tx_data2)); // ?????
            HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,GPIO_PIN_SET);
        }
        if (rx_data[0] == '1') // ??????????? 0
        {
            HAL_UART_Transmit_IT(&huart1, (uint8_t*)tx_data3, strlen(tx_data3)); // ?????
            HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,GPIO_PIN_RESET);
        }
        HAL_UART_Receive_IT(&huart1, (uint8_t*)rx_data, sizeof(rx_data)); // ???? UART ????
    }
}

在main中while前

    HAL_UART_Receive_IT(&huart1, (uint8_t*)rx_data, sizeof(rx_data)); // ???? UART ????

添加全局变量定义

char ch;
uint8_t rx_data[2];
char tx_data2[]="111";
char tx_data3[]="222";

### STM32F1 CubeMX RTC Configuration Tutorial #### Overview of the Real-Time Clock (RTC) Module on STM32F1 Series Microcontrollers The Real-Time Clock module is a crucial component for applications requiring accurate timekeeping, even when the main power supply is off. The STM32F1 series microcontroller supports an independent real-time clock that can operate from its own low-power oscillator or external sources. #### Setting Up the Project with STM32CubeMX To configure the RTC using STM32CubeMX: 1. Open STM32CubeMX and create a new project selecting the appropriate STM32F1 device. 2. In the "Pinout & Configuration" tab, locate **RCC** under System Core to enable LSE Oscillator which serves as the RTC clock source[^1]. 3. Navigate to the **RTC** section within Peripherals where one may choose between internal Low-Speed External (LSE) crystal/ceramic resonator or external 32kHz signal input via PC14/PC15 pins depending upon hardware design choices made during PCB layout phase[^2]. #### Generating Code Initialization Files After configuring parameters through graphical interface provided by STM32CubeMX tool: - Click on `Project` menu item followed by choosing `Generate Code`. - Select desired IDE/compiler environment before clicking OK button initiating code generation process automatically setting up necessary initialization routines including those related specifically towards enabling/disabling features associated directly alongside managing operations concerning peripheral devices like timers/counters etc., but also importantly here – initializing settings pertinent around running instances involving usage scenarios surrounding implementation aspects linked closely together regarding practical application cases tied back ultimately leading into how exactly these configurations affect overall behavior patterns exhibited while operating systems built based off architectures similar such as ARM Cortex-M3 found inside many variants belonging within families encompassing STMicroelectronics' line-up covering various models starting originally introduced first appearing publicly known collectively referred generally speaking about generically nowadays simply called 'STM32'. ```c /* USER CODE BEGIN RTOS_TIMERS */ /* Define following variables in order to use this API */ __IO ITStatus RCC_LSECSSFlag = RESET; uint8_t TimeSet = 0; void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc){ /* Enable Power Interface clock */ __HAL_RCC_PWR_CLK_ENABLE(); /* Allow access to Backup Domain */ PWR->CR |= PWR_CR_DBP; /* Reset Backup Domain without resetting other domains */ __HAL_RCC_BACKUPRESET_FORCE(); __HAL_RCC_BACKUPRESET_RELEASE(); if((BKP->DR1 != 0xAA) || (TimeSet == 0)){ BKP->DR1 = 0xAA; // Set Date RTC_DateTypeDef sdatestructureget; sdatestructureget.Year = 0x17; sdatestructureget.Month = RTC_MONTH_AUGUST; sdatestructureget.Date = 1; sdatestructureget.WeekDay = RTC_WEEKDAY_MONDAY; HAL_RTC_SetDate(hrtc,&sdatestructureget,FORMAT_BIN); // Set Time RTC_TimeTypeDef stimestructure; stimestructure.Hours = 0; stimestructure.Minutes = 0; stimestructure.Seconds = 0; stimestructure.TimeFormat = RTC_HOURFORMAT_24; stimestructure.DayLightSaving = RTC_DAYLIGHTSAVING_NONE ; stimestructure.StoreOperation = RTC_STOREOPERATION_RESET; HAL_RTC_SetTime(hrtc ,&stimestructure, FORMAT_BIN ); TimeSet++; } } ``` --related questions-- 1. How does changing the RTC clock source impact system performance? 2. What are common troubleshooting steps for issues encountered after configuring RTC using CubeMX? 3. Can you provide more details on integrating backup registers with RTC functionality? 4. Are there any specific considerations when designing PCB layouts for STM32 boards intended to utilize RTC functionalities?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值