dimanche 13 septembre 2020

Too many if else statements, can it be optimized given the "index" variable logic is incrementing by 1 every loop?

In my embedded system, The following C code will be called in the main by a forever while loop when the system is running. Is there a better way to optimize the following C code so that it doesn't have to go through all the if else statements. I'm thinking is there a better way to make the code run faster since "index" is incrementing every loop by 1. "index" is starting from 0 and incrementing up to 7 and reset back to 0. It is in a repeat pattern.

The reason for the optimization is that the following code need to be run every few micro seconds.

Sample Code below: Note that some of the values are made up.

void main(1)
{
    static int index = 0;

    while (1) {
        if (index == 0) {
            valueA = 0.88;
            valueB = 0.88;
            PID.A0 = 0.0012 * 15;
            PID.A1 = -0.001 * 15;
            index++;
        }
        else if (index == 1) {
            valueA = 0.87;
            valueB = 0.87;
            PID.A0 = 0.0012 * 8;
            PID.A1 = -0.001 * 8;
            index++;
        }
        else if (index == 2) {
            valueA = 0.86;
            valueB = 0.86;
            PID.A0 = 0.0012 * 6;
            PID.A1 = -0.001 * 6;
            index++;
        }
        else if (index == 3) {
            valueA = 0.83;
            valueB = 0.83;
            PID.A0 = 0.0012 * 5;
            PID.A1 = -0.001 * 5;
            index++;
        }
        else if (index == 4) {
            valueA = 0.79;
            valueB = 0.79;
            PID.A0 = 0.0012 * 3;
            PID.A1 = -0.001 * 3;
            index++;
        }
        else if (index == 5) {
            valueA = 0.73;
            valueB = 0.73;
            PID.A0 = 0.0012 * 2;
            PID.A1 = -0.001 * 2;
            index++;
        }
        else if (index == 6) {
            valueA = 0.71;
            valueB = 0.71;
            PID.A0 = 0.0012 * 1;
            PID.A1 = -0.001 * 1;
            index++;
        }
        else if (index == 7) {
            valueA = 0.68;
            valueB = 0.68;
            index = 0;
        }
    }           // end of while()
}

Aucun commentaire:

Enregistrer un commentaire