%=====clean up any leftover serial connections==============
clear all
try
    fclose(instrfind) %close any bogus serial connections
end

%=====open a serial connection===============================
%set its rate to 9600 baud
%SR830 terminator character is  (ACSII 13)
%use fprintf(s,['m' mode]) to write
%find which COM port you need!!!!
tries = 1
s = serial('COM6','baudrate',9600,'terminator',13); 
fopen(s)
%initialize data matrix
imgr = 0;
%intialize a counter
count = 0;
%get 2500 bytes of data since transfer is very slow
while(count<2499)
    %get data from mcu
    fprintf(s,'g');     %send char to get another data packet
    temp = fscanf(s,'%d');    %get the data packet available
    imgr = [imgr, temp];  %store data packet in img
    count=count+1;            %count the number of packets received
    l = mod(count,100);
    if(l==0)
        count
    end
    
    
end
%done filling the data matrix -- send done bit
fprintf(s,'d');
size(imgr)
%reshape the img vector into a square matrix
imgx = reshape(imgr,50,50); 
%make sure everything is 8bit
img = uint8(imgx);
%display original image
figure
colormap gray;
subplot(331);
title('original');
imshow(img);
%display minimized image
subplot(332);
title('minimized original');
img2 = imresize(img,[50 50],'bicubic');
imshow(img2);
%try to remove ccd noise - gaussian using lucy-richardson filter
psf = fspecial('gaussian',[50 50],0.5);
img3 = deconvlucy(img,psf,10);
subplot(333)
title('lucy original');
imshow(img3);
%display minimized image after lucy filter
img4 = imresize(img3,[50 50],'bicubic');
subplot(334);
title('minimized lucy');
imshow(img4);
%edge detection on minimized original
img5 = edge(img2);
subplot(335);
title('edge original minimized');
imshow(img5)
%edge detection on minimized lucy
img6 = edge(img4);
subplot(336);
title('edge lucy minimized');
imshow(img6);
fprintf(s,'b'); %rec_en, send start char to uC for matlab transfer to uC
%ran out of time to implement TV blasting
%send matlab data to uC for blasting on to the TV
% [n1,n2] = size(img6);
% for l = 1:n1 %row
%     for p = 1:n2 %col
%         if(img6(1,p) == 0)
%             fprintf(s,'0');
%         else
%             fprintf(s,'1');
%         end
%         %fprintf(s,img6(l,p));
%     end
% end
%entire array has been transferred
fprintf(s,'p');	%send done char to uC
fclose(s);  %close the serial connections