Phase locked loop for three phase grid I have been implementing a control software where one of its core functionalities is the ability to synchronize with the three phase grid. Basically I need to implement some form of the phase locked loop (PLL) suitable for three phases. I have found that there are several posibilies how to do that. One of the simplest I have found is basically based on calculation of the time integral of the phase voltages. My first idea how to do that was to use the trapezoidal integration rule in recurent form
$$I(k) = I(k-1) + \frac{T}{2}\cdot\left[x(k-1) + x(k)\right].$$
I have implemented the above written difference equation in C and I have tried to pass a sinewave into it
    #define PI 3.14
    #define N 64

    float x, y;
    for(int k = 0; k &lt; N; k++){
        x = sin(k*2*PI/N);
        y = integrate(1.0, x);
    }

    float integrate(float T, float xk)
    {
        static float intk_1 = 0; // I(k-1) 
        static float xk_1 = 0; // x(k-1)
    
        float intk = intk_1 + T/2*(xk_1 + xk);
        intk_1 = intk;
        xk_1 = xk;
    
        return intk;
    }

Based on the outcomes of my experiment I have realized that in case the integration process starts from the point where the sinewave has zero value the resulted integral has large offset

In case the integration process starts from point where the sinewave has its positive maximum the integral has zero offset.
I need to have the integral with zero offset to be able to estimate the phase and frequency of the three phase grid. The obvious solution could be to somehow detect the positive maximum of the sinewaves and then start integration process. The problem is that the frequency of the three phase grid fluctuates in some tolerance band. Can anybody give me an advice how to do the integration process so that the resulted integrals have zero offsets?
I recommend a standard dq-PLL, check this reference https://vbn.aau.dk/ws/portalfiles/portal/273236528/PLL_Review_RSER.pdf

There are 2 required integrators. For algebraic loop reasons, the last integrator, the one that converts the angular frequency to the phase, should be a forward-Euler integrator. The integrator in the PI controller, can be a trapezoidal integrator if you want.
Edit : Ts = Sampling Period