%###########################################################
%#########--MATLAB to CMUcam interface code--###############
%################--by Lee von Kraus--#######################
%###########################################################
%Note #1:
%if using the CMUcam java GUI to grab a frame and find the # values for a color you want to track, 
%notice that the color #s (mins and maxs) are NOT in the same order as they are in the TC command!
%here's a color I used for testing (depends on lighting): Red Pringles Can = 'TC 215 255 6 56 0 41' 
%Note #2:
%unless you know how to clear the serial input buffer (I don't) then make sure to turn on pole mode
%('PM 1') this way, you're constantly getting up to date data, and not some stuff from the buffer.


%lets you see the program start at MATLAB command line
'-------------------------------------New Start-----------'	
pause(1);
'go!'

%-----------------set up serial port properties ('terminator' part verrry important!!)
SerCam = serial('COM3');        
set(SerCam,'BaudRate', 115200, 'DataBits', 8, 'Parity', 'none','StopBits', 1, 'FlowControl', 'none', 'Terminator', 13);              %set up the camera com port
fopen(SerCam);                              			%open the camera com port


%-----------------set up camera properties
fprintf(SerCam, '%s\r', 'RM 2'); 				%tell Cam to stop sending ACKs and NCKs
fprintf(SerCam, '%s\r', 'PM 1'); 				%make sure pole mode is on
fprintf(SerCam, '%s\r', 'OM 0 3');				%makes TC return only the ctnroid coordinates
fprintf(SerCam, '%s\r', 'TC 215 255 6 56 0 41'); 		%set tracking color (Rmin Rmax Gmin Gmax Bmin Bmax)
garbage = fscanf(SerCam, '%*s %d %d')				%throw out what's sitting in the buffer


%----------------collect tracking data from camera
for g = 0:100
    fprintf(SerCam, '%s\r', 'TC 215 255 6 56 0 41');
    i = fscanf(SerCam, '%*s %d %d')   				% %*s=non-whitespace %d=base10number
end


%-------------------close serial port
fclose(SerCam)
delete(SerCam)
clear SerCam