[MDK] 介绍STM32使用C和C++混合编程的方法
前言
搞单片机编程大多数还是使用MDK编程,自己对MDK这个软件也比较熟悉,在网络寻找资料时,发现有一些大佬会用c++来写单片机程序,很是高大上,于是笔者也想研究一下,于是有了这篇文章,使用stm32的内部flash进行编程,在芯片内部flash的最后一个page上进行存储一些数据。
业务场景
假设公司有一个项目是专门做智能家居的主板,这些主板上智能的功能比较多,可以语音控制某个灯,智能控制某个场景,开光空调等一系列的高级功能,现在这些主板用来供给酒店客房,酒店的这些客房都是装同一套板子,但是每个客房中一些配置又有一些不同,比如客房A比较大装有18个灯,15个按键;客房B比较小,只装有5个灯,3个按键。现在的需求则是根据客户每个房间的配置来对智能主板上进行部分编程。
步骤1基础工程
找一个基础工程,使用cubemx生成一个最基本的项目,时钟和SWD配置好就行,可以参考hal库教程。
步骤2写代码
移植现有代码
random_flash_interface.h内容
#ifndef FlashStorage_STM32_h
#define FlashStorage_STM32_h
#include "random_flash_utils.h"
class EEPROM
{
public:
EEPROM()
= default;
uint8_t Read(int _address)
{
if (!isInitialized)
init();
return EEPROMReadBufferedByte(_address);
}
void Update(int _address, uint8_t _value)
{
if (!isInitialized)
init();
if (EEPROMReadBufferedByte(_address) != _value)
{
dirtyBuffer = true;
EEPROMWriteBufferedByte(_address, _value);
}
}
void Write(int _address, uint8_t _value)
{
Update(_address, _value);
}
template<typename T>
T &Pull(int _offset, T &_t)
{
// Copy the data from the flash to the buffer if not yet
if (!isInitialized)
init();
uint16_t offset = _offset;
auto* _pointer = (uint8_t*) &_t;
for (uint16_t count = sizeof(T); count; --count, ++offset)
{
*_pointer++ = EEPROMReadBufferedByte(offset);
}
return _t;
}
template<typename T>
const T &Push(int _idx, const T &_t)
{
// Copy the data from the flash to the buffer if not yet
if (!isInitialized) init();
uint16_t offset = _idx;
const auto* _pointer = (const uint8_t*) &_t;
for (uint16_t count = sizeof(T); count; --count, ++offset)
{
EEPROMWriteBufferedByte(offset, *_pointer++);
}
if (commitASAP)
{