% -------------------------------------------------------------
% ECE230X D07
% Matlab examples of common "analog" modulated digital signals
% D. Richard Brown III
% 29-Mar-2007
% -------------------------------------------------------------
% User parameters below
% -------------------------------------------------------------

bits = [0 0 0 1 1 0 1 1 1 1 1 0 0 1 0 0];   % bits to transmit

% parameters of each signal in the alphabet
T = 0.1;                                    % duration of each bit (seconds)
freq = [1000 1000];                         % frequencies (Hz)
amp = [1 0];                                % amplitudes (V)
ph = [0 0];                                 % phases (radians)

% -------------------------------------------------------------
% End of user parameters
% -------------------------------------------------------------

N = log2(length(freq));                 % 2^N waveforms
fs = 16000;                             % sampling frequency
t = [0:(round(fs*T)-1)]/fs;             % time vector
L = length(t);
signal = zeros(2^N,L);                  % make space for signals

% create signals in alphabet
for n=1:2^N,
    signal(n,:) = amp(n)*sin(2*pi*freq(n)*t+ph(n));
end

% now generate transmitted signal
x = zeros(1,L*length(bits)/N);            % make space for transmitted signal
index = 1;
v = 2.^[N-1:-1:0];
for n=1:N:length(bits),
    signalindex = sum(bits(n:n+N-1).*v)+1;
    x(index:index+L-1) = signal(signalindex,:);
    index = index+L;
end

% plotting
subplot(2,1,1);
plot([0:(length(x)-1)]/fs,x);
xlabel('time (sec)');
ylabel('transmitted signal');
grid on
axis([0 T*length(bits)/N min(x)-0.5 max(x)+0.5])

subplot(2,1,2);
[Pxx,f] = pwelch(x,2^11,2^10,2^11,fs);
deltaf = (fs/2)/(2^11);
plot(f/1e3,10*log10(Pxx/deltaf)+30);
xlabel('frequency (kHz)');
ylabel('power spectral density (dBm/Hz)')
grid on

% play sound
soundsc(x,fs);