Skip to content

Instantly share code, notes, and snippets.

@electronicayciencia
Last active March 26, 2017 21:29
Show Gist options
  • Save electronicayciencia/4e493864f23724f010b77e2454343426 to your computer and use it in GitHub Desktop.
Save electronicayciencia/4e493864f23724f010b77e2454343426 to your computer and use it in GitHub Desktop.
Fractional divider snippet
Fc = 10; % clock frequency
Tfreq = 4; % Target frequency
% working options
n = 100000; % number of points
SR = 10*Fc; % sampling rate
T = n/SR; % sampling time (s)
% working vectors
t = 0:1/SR:T-1/SR; % time vector
w = square(2*pi*2*Fc*t);
out = zeros(1,n);
% calculate counters
idiv = Fc / Tfreq;
rem = mod(Fc,Tfreq);
icounter_max = floor(idiv);
fcounter_max = round(Fc/rem);
% main loop
icounter = 0;
fcounter = 0;
last_v = 0;
vout = 0;
for i = 1:length(w);
v = w(i);
if (v == 1) && (v ~= last_v) % raising edge
fcounter = fcounter + 1;
if (fcounter == fcounter_max)
fcounter = 0;
else
icounter = icounter + 1;
end
end
if (icounter >= icounter_max)
vout = 1 - vout; % toogle output
icounter = 0;
end
out(i) = vout;
last_v = v;
end
out;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment