我仍在学习 C 以用于微处理器。一开始我使用了很多全局变量。现在我尽量避免它,但对我来说,并不总是很清楚如何做到这一点。
例如电池监视器,在这种情况下,有 4 个函数需要读取或修改变量。我有这些功能都使用变量 LowVoltage。
void Check_Voltage(){
checks current voltage against LowVoltage
}
void Menu_Voltage(){
a menu on the LCD screen to set the value of LowVoltage
}
void Save_LowVoltage(){
runs after the settings menu is finished to save LowVoltage to EEPROM
}
void Load_LowVoltage(){
reads EEPROM and sets LowVoltage at startup
}
- Check_Voltage() 和 Save_LowVoltage() 需要读取 LowVoltage。
- Load_LowVoltage() 需要写入 LowVoltage。
- Menu_Voltage() 需要读写 LowVoltage。
如何在不使 LowVoltage 全球化的情况下完成这项工作?我是否需要创建另一个函数来读取或写入 LowVoltage?像这样的东西:
unsigned int Low_Voltage(short Get, unsigned int Value){
static unsigned int LowVoltage;
if(Get) return LowVoltage;
else LowVoltage= Value;
}
还是有更好的方法来做到这一点?我想一定有:)我最近一直在阅读有关结构的文章,但老实说,我并不完全理解它们,我什至不确定在这种情况下它会对我有帮助吗?