Moonlight293
Moonlight293

Reputation: 197

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 Square wave:

if( sineValue >= 0 )
        value = amp;
    else
        value = -amp;

But I am not sure how to change this to accommodate for a triangle wave.

Upvotes: 1

Views: 10424

Answers (3)

bandybabboon
bandybabboon

Reputation: 2346

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....

Upvotes: 6

Paul R
Paul R

Reputation: 213059

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.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272647

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;

Upvotes: 5

Related Questions