Generate sine signal in C without using the standard function

后端 未结 11 769
情歌与酒
情歌与酒 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:55

    The classic hack to draw a circle (and hence generate a sine wave too) is Hakmem #149 by Marvin Minsky. E.g.,:

    #include 
    
    int main(void)
    {
        float x = 1, y = 0;
    
        const float e = .04;
    
        for (int i = 0; i < 100; ++i)
        {
            x -= e*y;
            y += e*x;
            printf("%g\n", y);
        }
    }
    

    It will be slightly eccentric, not a perfect circle, and you may get some values slightly over 1, but you could adjust by dividing by the maximum or rounding. Also, integer arithmetic can be used, and you can eliminate multiplication/division by using a negative power of two for e, so shift can be used instead.

提交回复
热议问题