%%% upconvert.m
%%%
%%% Demonstrates upconversion and downconversion
%%%
%%% by Prof. Brian L. Evans, bevans@ece.utexas.edu
%%% The University of Texas at Austin
%%%
%%% August 28, 2015
%%%
%%% This Matlab script will play three sounds:
%%% (1) low-frequency signal (baseband signal)
%%% (2) modulated signal centered at a higher frequency,
%%% (3) the demodulated signal,
%%% The demodulated signal consists of the baseband
%%% signal plus some higher frequency artifacts.

fs = 44100;          %%% Sampling rate
Ts = 1/fs;           %%% Sampling time
tmax = 10;           %%% Signals last tmax seconds
t = 0 : Ts : tmax;   %%% Vector of time samples

%%% Generate baseband signal
f1 = 440;            %%% Middle 'A' on Western scale
basebandInput = cos(2*pi*f1*t);

%%% Modulate/upconvert baseband signal
%%% to be centered at frequency fc
fc = 8*f1;           %%% 3 octaves above f1
carrier = cos(2*pi*fc*t);
modulated = basebandInput .* carrier;

%%% Demodulate/downconvert modulated signal
%%% 1. Modulate using the same carrier signal
%%%    (causes gain to be reduced by 1/2)
%%% 2. Apply lowpass filter to extract baseband
%%%    (and multiply by 2 of compensate for step 1)
%%% Use same carrier frequency fc as in modulation
carrier = cos(2*pi*fc*t);
modulateAgain = modulated .* carrier;

FIRlength = floor(fs/(2*f1));
lowpassCoeffs = ones(1, FIRlength) / FIRlength;
basebandOutput = 2*filter(lowpassCoeffs, 1, modulateAgain);

%%% Playback signals
sound(basebandInput, fs);
pause(tmax+1);
sound(modulated, fs);
pause(tmax+1);
sound(basebandOutput, fs);
