User guide

3.7. COROUTINE EXAMPLES 85
3.7.1 A square wave generator
The following function is the main function of a coroutine that generates square wave
samples.
LET squarefn(args) = VALOF
{ LET freq, amplitude, rate = args!0, args!1, args!2
LET x = 0
cowait(@freq) // Return a pointer -> [freq, amplitude, rate]
{ // freq is a scaled fixed point value with
// three digits after the decimal point.
LET q4 = rate*1000
LET q2 = q4/2
UNTIL x > q2 DO { cowait(+amplitude) // First half cycle
x := x + freq
}
UNTIL x > q4 DO { cowait(-amplitude) // Second half cycle
x := x + freq
}
x := x - q4
} REPEAT
}
The following call creates a coroutine that initially generates a square wave with fre-
quency 440Hz and amplitude 5000 at a rate of 44100 samples per second.
sqco := initco(squarefn, 300, 440_000, 5_000, 44_100)
sqparmv := result2 // sqparmv -> [freq, amplitude, rate]
One second’s worth of samples can now be obtained by:
FOR i = 1 TO 44100 DO
{ LET sample = callco(sqco)
...
}
At any moment, the frequency and amplitude can be changed by assignments such as:
sqparmv!0 := newfrequency
sqparmv!1 := newamplitude
Other examples of the use of initco can be found below.
3.7.2 Hamming’s Problem
A following problem permits a neat solution i nvolving coroutines.
Generate the sequence 1,2,3,4,5,6,8,9,10,12,... of all
numbers divisible by no primes ot he r than 2, 3, or 5”.