编辑
2025-03-02
嵌入式
00

为GPIO单独创建一个类: GPIO.h

C++
#pragma once #ifndef __GPIO_H__ #define __GPIO_H__ #ifdef __cplusplus extern "C" { #endif #include "main.h" #include "delay.h" /* USER CODE BEGIN Includes */ #include <stdint.h> void MX_GPIO_Init(void); #ifdef __cplusplus } class GPIO { public: GPIO_TypeDef *GPIOx; // 4字节 uint16_t Pin; // 2字节 // 默认填充2字节 GPIO(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin, uint32_t Mode, uint32_t Pull, uint32_t Speed); GPIO() = delete; // 禁用默认构造函数 void set(); void reset(); void toggle(); bool read() const; void operator=(bool bit); }; #endif #endif /*__ GPIO_H__ */

GPIO.cpp

C++
#include "gpio.h" void MX_GPIO_Init(void) { __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); } /* USER CODE BEGIN 2 */ GPIO::GPIO(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin, uint32_t Mode, uint32_t Pull, uint32_t Speed) : GPIOx(GPIOx), Pin(GPIO_Pin) { // 启用对应的GPIO时钟 if (GPIOx == GPIOA) { __HAL_RCC_GPIOA_CLK_ENABLE(); } else if (GPIOx == GPIOB) { __HAL_RCC_GPIOB_CLK_ENABLE(); } else if (GPIOx == GPIOC) { __HAL_RCC_GPIOC_CLK_ENABLE(); } // 可根据需要扩展其他端口 GPIO_InitTypeDef GPIO_InitStruct = {0}; GPIO_InitStruct.Pin = GPIO_Pin; GPIO_InitStruct.Mode = Mode; GPIO_InitStruct.Pull = Pull; GPIO_InitStruct.Speed = Speed; HAL_GPIO_Init(GPIOx, &GPIO_InitStruct); } void GPIO::set() { HAL_GPIO_WritePin(GPIOx, Pin, GPIO_PIN_SET); } void GPIO::reset() { HAL_GPIO_WritePin(GPIOx, Pin, GPIO_PIN_RESET); } void GPIO::toggle() { HAL_GPIO_TogglePin(GPIOx, Pin); } bool GPIO::read() const { return HAL_GPIO_ReadPin(GPIOx, Pin) == GPIO_PIN_SET; } void GPIO::operator=(bool bit) { HAL_GPIO_WritePin(GPIOx, Pin, bit ? GPIO_PIN_SET : GPIO_PIN_RESET); }

类对象按内存大小排列,使内存对齐。

本文作者:古月流新

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!