Raulp
Raulp

Reputation: 8146

Checking the status of the GPIO even before main starts in embedded programming

I have two version of the boards , where a particular portion of the code gets executed based on the value of the #define BIAS_VOLTAGE

if(vol < BIAS_VOLTAGE)
{

    //Execute this

}
else if (vola >= BIAS_VOLTAGE)
{
 //Execute This

}

Now BIAS_VOLTAGE is #defined in a header file (#define BIAS_VOLTAGE 3) but for a different board it is 5(5V).

The only way to detect this is by polling one GPIO status (which remains High or low after GPIO initialization in main .This is done just once).

If it is high , BIAS_VOLTAGE 3 other wise 5 Since #BIAS_VOLTAGE is used at many places , how can i know the status of GPIO at the startup ( even before main) and fix the #define value.

I know #define gets fixed at the compile time , but I need to fix this constant value at the runtime.(and this will remain forever) Update : tool chain is IAR and microcontroller is STM32F4

Upvotes: 0

Views: 543

Answers (2)

Clifford
Clifford

Reputation: 93476

You may be making a simple thing complicated:

Given:

#define BIAS_3V0 3
#define BIAS_5V0 5

int getBiasVoltage()
{
    static int bias_voltage = 0 ;

    // Initialise on first use...
    if( bias_voltage == 0 )
    {
        bias_voltage = boardId() ? BIAS_3V0 : BIAS_5V0 ;
    }

    return bias_voltage ;
}

where boardId() is the GPIO read to identify the variant (replace with your own code as required), then your code becomes:

if(vol < getBiasVoltage() )
{

    //Execute this

}
else if (vola >= getBiasVoltage() )
{
 //Execute This

}

The board identity is checked once on first use and thereafter the previously determined value will be returned. Because the variable is hidden inside the function, it is read-only too.

Upvotes: 2

Lundin
Lundin

Reputation: 213892

Smells like something that should be done very early on. If so, you have to either tweak your current "CRT" (library start-up code) or write it all yourself, which is a job I would only recommend to veteran embedded devs.

Most tool chains do unfortunately come with a CRT which is useless beyond hobbyist projects. Some advice for how it should be written properly can be found here: https://stackoverflow.com/a/47940277/584518. If your current CRT doesn't resemble the advise given there - particularly if it lets the CRT run the whole of .data/.bss setup using the default internal RC oscillator, and with no wdog enabled, you should ask your tool vendor why they let incompetent quacks write the CRT.

Upvotes: 1

Related Questions