Csound Csound-dev Csound-tekno Search About

Pulse width modulation!

Date1998-12-10 02:05
FromPaul Winkler
SubjectPulse width modulation!
This should please the analog fans...

Some time ago there was a discussion of simulating pulse width
modulation. I don't remember anyone posting a solution. Well, the other
day, inspiration struck, and I came up with the idea to do it by
indexing a square wave in a funny way... This orc is rather simple with
some rough edges, but it gives the idea and doesn't sound too bad. Put
an amplitude envelope, a filter, and a chorus on there, and we're off to
Roland heaven...

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;copyright 1998 Paul M. Winkler, zarmzarm@erols.com
;****++++
;**** Last modified: Wed Dec  9 20:32:30 1998
;****----
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


	sr	=	44100
	kr	=	22050
	ksmps	=	2
	nchnls	=	1

            instr 1
            ;  simulated pulse width modulation

; This works! But p5 should be handled better.
ipitch = cpspch (p4)
aindex   phasor    ipitch

; Make the WIDTH (p5) 'feel' a little nicer -- an exponential curve from 
; ftlen/2 to ftlen, controlled by a linear percentage (0 to 100).
; This is not great: p5 less than about 10 is TOO small!
ilength = ftlen(1) 
inum = p5 * p5 * .0001 ; normalize it to 0 - 1
; pow would be a better solution, but it's broken in my csound version?

irange = ( ilength + ( inum * ilength )) * .5
aindex = aindex * irange
print irange
; display   aindex, .1                           
aout   table          aindex, 1;  use f1
out aout 
            endin 

            instr 2
; Same thing, only pulse width is controlled by an envelope.
ipitch = cpspch (p4)
aindex   phasor    ipitch
ilength = ftlen(1) 
krange   expseg  ilength * .5, p3 * .5, ilength, p3 * .5, ilength * .5
aindex = aindex * krange
aout   table          aindex, 1;  table 1
out aout 
            endin

;;;;;; sample score!

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;copyright 1998 Paul M. Winkler, zarmzarm@erols.com
;****++++
;**** Last modified: Wed Dec  9 20:34:05 1998
;****----
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

f1 0  512  -7   30000 256 30000 0 -30000 256 -30000 ;square wave,
!normalized

;  at dur pch    width     

t 0 180
i1 0  1   6.00   100
i. +  .5  6.02   100
i. .  .    .     50
i. .  .   6.03   50 
i. .  .   6.00   10 
i. .  .   6.01   10  
i. .  .   6.10   10
i. .  .   7.10   20   
i. .  .   7.08   .
i. .  .   7.07   40
i. .  .   6.07   .
i. .  .   5.07   60
i. .  .   4.07   .
i. .  .   5.07   80
i. .  .   4.07   . 
i. .  .   5.07   100 
i. .  .   4.07    >
i. .  2   5.07   30

s
t 0 120
i2 1 3   5.00
i2 + 3   5.11
i2 . 3   6.10
i2 . 3   7.09
i2 . 3   8.08
i2 . 3   9.07
i2 . 3   10.06
i2 . 3   11.05     ; quite bad aliasing there!