C++ STM32 编程 007 正式编写第一个程序

1、打开之前我们导入到VisualStudio的Keil工程。

2、添加我们之前提到的GPIO简化类。

3、添加一个App类,在该类完成各种控制。

4、由于我们的工程外设硬件可能需要后续添加删除,初始化代码手动修改太麻烦,而且容易出错,因此CubeMX软件修改,所以主文件我还是建议使用 main.c文件。但是如果这样做就存在一个问题:C++是C的超集,可以在C++中自由使用C的函数,但是反之就不行了,main.c调用不了C++。因此,我们还要把App类,做一个C包装,供 main.c文件调用。

注意:虽然感觉就做了这么一点点的事,却搞了这么多东西,给人的感觉很繁琐,但是代码量大,控制复杂的时候,就可以体现出这样做的好处了。

下面就是我的代码:

Register.h

#pragma once
#include "stm32f1xx_hal.h"

namespace FRAM
{
	class GPIO_Out
	{
	public:
		void Link(GPIO_TypeDef* pPort, uint16_t Pin);
		void operator =(const uint16_t & Value);
	private:
		GPIO_TypeDef* m_PORT = nullptr;
		uint16_t m_PIN = 0x0000;
	};

	class GPIO_In
	{
	public:
		void Link(GPIO_TypeDef* pPort, uint16_t Pin);
		bool operator ()();
	private:
		GPIO_TypeDef* m_PORT = nullptr;
		uint16_t m_PIN = 0x0000;
	};
};

Register.cpp

#include "Register.h"

namespace FRAM
{
	void GPIO_Out::Link(GPIO_TypeDef* pPort, uint16_t Pin)
	{
		m_PORT = pPort;
		m_PIN = Pin;
	}

	void GPIO_Out::operator=(const uint16_t & Value)
	{
		HAL_GPIO_WritePin(m_PORT, m_PIN, static_cast<GPIO_PinState>(Value));
	}


	void GPIO_In::Link(GPIO_TypeDef* pPort, uint16_t Pin)
	{
		m_PORT = pPort;
		m_PIN = Pin;
	}

	bool GPIO_In::operator()()
	{
		return (m_PORT->IDR & m_PIN) > 0;
	}
};


App.h

#pragma once
#include "Register.h"

namespace FRAM
{
	class App
	{
	public:
		void Init(GPIO_TypeDef* LedPort, uint16_t LedPin, GPIO_TypeDef* ButtonPort, uint16_t ButtonPin);
		void Run();
	private:
		GPIO_Out LED;
		GPIO_In BUTTON;
	};
};


App.cpp

#include "App.h"

namespace FRAM
{

	void App::Init(GPIO_TypeDef* LedPort, uint16_t LedPin, GPIO_TypeDef* ButtonPort, uint16_t ButtonPin)
	{
		LED.Link(LedPort, LedPin);
		BUTTON.Link(ButtonPort, ButtonPin);
	}

	void App::Run()
	{
		static uint16_t sta = 0;
		if (BUTTON())
		{
			LED = sta;
			sta = !(sta);
		}
	}

};


AppWrapper.h

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

	/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"

	void App_Init(GPIO_TypeDef* LedPort, uint16_t LedPin, GPIO_TypeDef* ButtonPort, uint16_t ButtonPin);
	void App_Run();

#ifdef __cplusplus
}
#endif

AppWrapper.cpp

#include "AppWrapper.h"
#include "Register.h"
#include "App.h"

static FRAM::App app;

void App_Init(GPIO_TypeDef* LedPort, uint16_t LedPin, GPIO_TypeDef* ButtonPort, uint16_t ButtonPin)
{
	app.Init(LedPort, LedPin, ButtonPort, ButtonPin);
}

void App_Run()
{
	app.Run();
}

main.c

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  ** This notice applies to any and all portions of this file
  * that are not between comment pairs USER CODE BEGIN and
  * USER CODE END. Other portions of this file, whether 
  * inserted by the user or by software development tools
  * are owned by their respective copyright owners.
  *
  * COPYRIGHT(c) 2018 STMicroelectronics
  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "AppWrapper.h"
/* 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);
static void MX_GPIO_Init(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();
  /* USER CODE BEGIN 2 */
  App_Init(LED_GPIO_Port, LED_Pin, BUTTON_GPIO_Port, BUTTON_Pin);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
	  App_Run();
    /* 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 CPU, AHB and APB busses clocks 
  */
  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 busses 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();
  }
  /**Enables the Clock Security System 
  */
  HAL_RCC_EnableCSS();
}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : LED_Pin */
  GPIO_InitStruct.Pin = LED_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LED_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : BUTTON_Pin */
  GPIO_InitStruct.Pin = BUTTON_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(BUTTON_GPIO_Port, &GPIO_InitStruct);

}

/* 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 */

  /* 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,
     tex: 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****/

编译成功!已经生成 .ihex文件 

猜你喜欢

转载自blog.csdn.net/a13576560181/article/details/85061658