Generating pulse waves

I've already managed to generate sine, saw and even square waves by transforming the other two. Now, I'm extremely frustrated with pulse waves.

The idea is, the frequency controls the pitch (leave at default for testing), shape controls the width of a pulse and volume controls the volume, where 255 is the largest char value, 0 and 256 is the lowest and considered the same thing. 128 is the max volume.

Oh, and 50 is the default shape, which should produce a square wave.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<cmath>
#include<cstdio>

class oscillator{
char time;
public:
int frequency = 7;
int shape = 50;
int volume = 128;

char pulsewave(){
char a;
time = time +frequency;
if(time > (128*((double)shape/50)) ) return (255*volume)/128;
else return 0;
}

};

int main(){
oscillator a1;
while(1){
printf("%c", a1.pulsewave() );
}
}

P.S. Why doe the forum break when I insert code tags??
Last edited on
Look closely at the code below.
1
2
3
4
5
6
7
8
9
char pulsewave()
{
   char a;
   time = time + frequency;
   if(time > (128 * ((double)shape / 50)) ) 
      return (255 * volume) / 128;
   else 
      return 0;
}


In your code what is the value held in volume?

What is the maximum value that can be held in a char on your system?

I don't understand, the value for volume is 128, 128*255 /128 = 255, the maximum value of a char. Oh, wait. It's because it's signed, isn't it? Never mind, unsigning it didn't do anything... Wait, changing the 128 to a 1 in the if statement got it producing a sqaure, but adjusting the shape does nothing. It's a start! Produces a square, and changing the shape to a radically high value adjusts the shape, thanks!
Last edited on
you should try including iostreams first before making the executions
Why do you think including <iostream> would help? The OP didn't use any streams in his program, he was using the <cstdio> functions instead.
Yeah, Jibs got it. I like to stay away from more abstract C++ stuff and stick to C because it's cleaner. The only time I use C++ stuff is when it's necessary or would optimise my code.
I like to stay away from more abstract C++ stuff and stick to C because it's cleaner.

Then stick with C, by using a C compiler instead of a C++ compiler. But IMO the C++ streams are much safer to use than the C-stdio functions.

The only time I use C++ stuff is when it's necessary or would optimise my code.

What would you consider a necessity?

How would you use C++ to optimize your C code?

Topic archived. No new replies allowed.