Creating a Triangle wave from a Sine wave in C++
I am having trouble finding out how to form a triangle (not sawtooth) wave from a sine wave.
I understand how to create it for a S开发者_Go百科quare wave:
if( sineValue >= 0 )
value = amp;
else
value = -amp;
But I am not sure how to change this to accommodate for a triangle wave.
I missed this question, here is a very cool maths trick:
asin(cos(x))/1.5708 <-- click this to see graph
same with sine:
Acos(Sin(x))/1.5708 // is a square version of sin(x)
the precise value of the devider is something of that kidn, 1.5708....
A triangle wave is the integral of a square wave. So you need to integrate (sum) your square wave over time:
if (sineValue >= 0)
{
value += delta;
}
else
{
value -= delta;
}
Note that this can be written more succinctly as:
value += (sineValue >= 0) ? delta : -delta;
You can use the sign of the derivative of your sine wave to generate a triangular wave like this:
if (sineValue - oldSineValue >= 0)
{
value += delta;
}
else
{
value -= delta;
}
oldSineValue = sineValue;
You will need to choose delta to give the required amplitude for your triangular wave, and this will of course be dependent on the frequency of the sine wave and the sampling rate.
The advantage of this method is that the triangular wave and sine wave have the same phase, i.e. peaks and zero crossings coincide.
精彩评论