Avoiding global bindings in this case (embedded C)

I am still studying C to be used in microprocessors. At first I used a lot of globals. Now I am trying to avoid this as much as possible, but for me it is not always clear how to do this.

For example, a battery monitor, in this case there are 4 functions that you need to read or change a variable. I have all these functions using the LowVoltage variable.

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 () and Save_LowVoltage () need to read LowVoltage.
  • Load_LowVoltage () must be written LowVoltage.
  • Menu_Voltage () should read and write LowVoltage.

How can I make this work without making LowVoltage global? Should I make another function to read or write LowVoltage? Something like that:

unsigned int Low_Voltage(short Get, unsigned int Value){
  static unsigned int LowVoltage;

  if(Get) return LowVoltage;
  else LowVoltage= Value;
}

? , :) , , , , , ?

+4
3

:

  • - , . -, -
  • .
  • - . ; .

, , - . C LowVoltage :

static unsigned int LowVoltage;

, :

  • C "" .
  • C . LowVoltage, .
+8

,

  • ,

    unsigned int Load_LowVoltage(unsigned int lowVoltage);
    

    LowVoltage ,

    LowVoltage = Load_LowVoltage(LowVoltage);
    
  • LowVoltage LowVoltage,

    void LowVoltage(unsigned int *lowVoltage)
     {
        *lowVoltage = modifiedValue;
     }
    

    Load_LowVoltage(&LowVoltage);
    

, , , , . .

0

, , :

typedef struct {
  int low_voltage; 
  int voltage;
  int capacity;
  int temperature;
  ...
} BatteryData

:

BatteryData *battery = malloc(sizeof(BatteryData));
battery->low_voltage = 0;
...

, , :

void Load_LowVoltage(BatteryData *battery){
 //reads EEPROM and sets LowVoltage at startup 
 int eeprom_val = get_low_voltage_from_eeprom();
 battery->low_voltage = eeprom_val;
}

, :

free(battery);
0

All Articles