很多配置参数在设备运行期间根本不会变化。比如硬件版本、默认 PID、传感器量程、产品型号、设备能力表。却有不少项目把它们定义成普通全局变量,开机时再复制一遍。RAM 就这么一点点被吃掉了。typedef struct
{
uint16_t hardware_version;
uint16_t product_id;
float voltage_max;
float current_max;
float temperature_max;
} FactoryConfig_t;把只读配置声明为 const。static const FactoryConfig_t g_factory_config =
{
.hardware_version = 0x0102U,
.product_id = 0x1020U,
.voltage_max = 28.0f,
.current_max = 5.0f,
.temperature_max = 85.0f
};在常见 MCU 工具链里,这类数据通常会进入只读段,最终存放在 Flash 中,不占用运行时可写 RAM。读取方式和普通结构体没有区别。if (measured_current > g_factory_config.current_max)
{
motor_shutdown();
}还可以定义成配置表。typedef struct
{
uint8_t channel;
float gain;
float offset;
} AdcCalibration_t;
static const AdcCalibration_t g_adc_calibration_table[] =
{
{0U, 1.002f, -0.015f},
{1U, 0.998f, 0.008f},
{2U, 1.005f, -0.021f}
};我见过一个 RAM 只有 8KB 的小项目,初始化表、正弦表、菜单文本和产品参数全没加 const。程序一启动,RAM 使用率直接八成。后来大家花两天排查"偶发栈溢出",最后发现不是任务栈太小,是静态数据把 RAM 挤得只剩一条缝。 |
|