Debian Codegraph @

examples/basic/pulse.ck

raw
1 //------------------------------------------------------------------------------
2 // name: pulse.ck
3 // desc: basic demo using PulseOsc UGen to do pulse width modulation
4 //
5 // This UGen defines an oscillator that uses Pulse Width Modulation (PWM), a
6 // process that allows for the control of the width of output pulses while
7 // keeping the frequency constant. The on/off ratio of the signal is called the
8 // "duty cycle". A pulse wave may be thought of as a square wave with adjustable
9 // time between cycles. A square wave has a duty cycle of 50% -- alternating
10 // between "on" and "off" in equal proportions. A duty cycle of 75% would mean
11 // the pulse signal is "on" three times as long as it is "off" in one cycle.
12 // The PulseOsc UGen can be used to create sound, or to control other signals!
13 //
14 // author: Alex Han
15 // date: Spring 2023
16 //------------------------------------------------------------------------------
17
18 // connect
19 PulseOsc pulse => dac;
20 // set gain
21 pulse.gain( .2 );
22 // set frequency
23 pulse.freq( 110 );
24
25 // The key characteristic of PulseOsc is the ability to set the pulse width
26 // (i.e. duty cycle). When the pulse wave is used to create sound, varying
27 // the duty cycle affects the timbre. This demo shows how the timbre changes
28 // significantly with small changes to the pulse width.
29
30 // time loop
31 while( true )
32 {
33 for( int i; i < 20; i++ )
34 {
35 // .width() takes a float from 0.0 to 1.0
36 pulse.width( .05 * i );
37 // print
38 chout <= "current duty cycle: " <= pulse.width();
39 // floating point equality
40 if( Math.equal( pulse.width(), .5) )
41 {chout <= " <- this is just a square wave!";}
42 // newline
43 chout <= IO.newline();
44 // next time step
45 .5::second => now;
46 }
47 }
48
49 // for more PWM fun...
50 // 1) smoothly vary the pulse width (using a small time scale)
51 // 2) filter the sound (e.g., with LPF)