Generate sine signal in C without using the standard function

后端 未结 11 867
情歌与酒
情歌与酒 2021-02-02 09:41

I want to generate a sine signal in C without using the standard function sin() in order to trigger sine shaped changes in the brightness of a LED. My basic idea was to use a lo

11条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-02 09:53

    I would go with Bhaskara I's approximation of a sine function. Using degrees, from 0 to 180, you can approximate the value like so

    float Sine0to180(float phase)
    {
        return (4.0f * phase) * (180.0f - phase) / (40500.0f - phase * (180.0f - phase));
    }
    

    if you want to account for any angle, you'd add

    float sine(float phase)
    {
        float FactorFor180to360 = -1 * (((int) phase / 180) % 2 );
        float AbsoluteSineValue = Sine0to180(phase - (float)(180 * (int)(phase/180)));
        return AbsoluteSineValue * FactorFor180to360;
    }
    

    If you want to do it in radians, you'd add

    float SineRads(float phase)
    {
        return Sine(phase * 180.0f / 3.1416);
    }
    

    Here is a graph showing the points calculated with this approximation and also points calculated with the sine function. You can barely see the approximation points peeking out from under the actual sine points.

提交回复
热议问题