sawtooth(t) := t - floor(t);
freq : 0.05$
sinesignal(t) := (1/2)+(499/1000)*sin(2*%pi*freq*t);
pwm(t) := if(sawtooth(t) >= sinesignal(t)) then 0 else 1;
load(draw)$
n : 1e4;kill(crossing);
crossing : (x:[0],
for i:0 while i<20*n do
if( pwm(i/n)#pwm((i+1)/n) ) /* detect edge */
then x:append(x,[(i/n)]),
setify(x));
length(crossing); /* copy the x-tics from here */
source : gr2d(
font="Times",nticks=50,
grid=true,ytics={0,1},yrange=[-.25,1.25],
user_preamble="set format x "";set xlabel "" 0,1;
set bmargin 0;set tmargin 0",
xtics= {0,0.592,0.999,1.762,1.999,2.893,2.999,3.973,
3.999,4.998,4.999,5.975,5.999,6.911,6.999,7.816,7.999,
8.698,9,9.567,10,10.432,
10.999,11.301,11.999,12.183,12.999,13.088,13.999,14.024,
14.999,15.001,15.999,16.026,16.999,17.106,17.999,18.237,
18.999,19.407,19.999},
xlabel="",ylabel="source signals",
explicit(sawtooth(x),x,0,19),
color=red,explicit(sinesignal(x),x,0,19)
)$
pwm_plot : gr2d(
font="Times",nticks=50,
grid=true,ytics={0,1},yrange=[-.25,1.25],
user_preamble="set format x "";set bmargin 2.25",
xtics= {0,0.592,0.999,1.762,1.999,2.893,2.999,3.973,
3.999,4.998,4.999,5.975,5.999,6.911,6.999,7.816,7.999,
8.698,9,9.567,10,10.432,
10.999,11.301,11.999,12.183,12.999,13.088,13.999,14.024,
14.999,15.001,15.999,16.026,16.999,17.106,17.999,18.237,
18.999,19.407,19.999},
xlabel="Time",ylabel="PWM signal",
color=magenta,explicit(pwm(x),x,0,19)
)$
draw(terminal=svg,file_name="Pwm",
source,pwm_plot);