Outputting a square wave as raw data

So I've very recently started learning C++ and am using it for audio programming. Up until now it's been relatively error free. I'm trying to export a raw data file that contains a square wave. The issue is it is outputting a sine wave.... I have another patch that creates a sine wave and this is quite different. I have no clue what element isn't working as a friends code which is almost identical works just fine.

I've been checking if they work by importing them into audacity.
Also I have the variables at the top as the file will be used to ask users to change the variables, but for now I just want to get the wave working.

Thank you in advance

1
2
3


Last edited on
Without looking at any of your output, your samplevalue variable appears to be just getting set to
4 sin( 2.pi.f.t )
since your multiplying and dividing factors of (2k-1) are simply cancelling out. So that's a monochromatic sine wave.

If you want a square wave then replace your sin() by something that is 1 for half the interval and 0 for the rest. You clearly don't want a sum over harmonics either.

Have you tried to create a "simple" square wave. By simple I mean one that just flips between two values, holding each value for a fixed interval? For a square wave I would expect to see multiple values equal to each other (the interval) before switching to another value and holding that value for some interval.

Your current math doesn't look like a square wave to me.

Also be careful with all of those switches between the numeric types and be careful with the integer math.

Thankyou!

You helped me realise that I simply had a bracket in the wrong place! I knew it'd be something so small and simple...

I changed it to += (sin(t * frequency * 2 * M_PI * (2*k-1)) / (2*k-1)).
Now the whole 'top line' is being divided by (2*k-1), including the sin function.

Appreciate the help!
And also thanks jib,
I have created a square wave that holds +1 and -1 values at a given frequency but wanted to attempt a complex one.

The maths is based on the square wave equation which can be easily found online, it used the addition of odd harmonics.

With the change in brackets above it now works.
Registered users can post here. Sign in or register to post.