function serialObj = openSerial(portNumber, teamNumberHexString)
% openSerial opens a connection to the COM port for serial communication.
% Example usage:
%   pic = openSerial(4)
% Example usage later in the lab:
%   pic = openSerial(4, '50')
%   Note, the hex values are passed in as a string to allow for a-f values.

% Close any open connections
open_ports=instrfind('Type','serial','Status','open');
if ~isempty(open_ports)
     fclose(open_ports);
end

% Allow 1 or 2 arguments (2 arguments for later in lab).
% But don't allow 0 arguments!  (must have COM port number)
switch nargin
    case 2
        teamNumber = hex2dec(teamNumberHexString);
    case 1
        teamNumber = 0;
    otherwise
        fprintf('You must supply a COM port number\n');
        return
end

% Open the serial connection and provide some feedback to the user.
% Call the serial_PICDEM_BytesAvailableFcn function when bytes are received
portStr = sprintf('COM%d',portNumber);
fprintf('Connecting to %s...',portStr);
serialObj = serial(portStr, 'BaudRate', 9600,...
    'TimeOut',1,...
    'Terminator',[],...
    'BytesAvailableFcnMode','byte',...
    'BytesAvailableFcnCount',1,...
    'BytesAvailableFcn',{@serial_PIC_BytesAvailableFcn, teamNumber});
fprintf('Status is %s\n',serialObj.Status);
fprintf('Opening...');
fopen(serialObj);
fprintf('Status is %s\n',serialObj.Status);
end

function serial_PIC_BytesAvailableFcn(serialObj, eventData, teamNumber)
%serial_PICDEM_BytesAvailableFcn bytes from serial object

numBytes = get(serialObj, 'BytesAvailable');
if (numBytes > 0)
    receivedData = fread(serialObj, numBytes, 'uint8');
    for i = 1:numBytes
        singleByte = receivedData(i);

% Uncomment only one part at a time.
		
		% Part D parts 1-3 when passing ASCII '0' - '7'
        fprintf('%c', singleByte); % Just print the ASCII directly to the MATLAB console.

		
		% Part D parts 4-5 when passing 0 - 7
        % fprintf('%c', singleByte + 48); % Add 48 here since the message is not in ASCII (only ASCII is printable to the console).

		
        % Part E (and beyond)
		% receivedTeam = bitand(singleByte, hex2dec('F0')); % Do NOT modify this line.  This is NOT your team number, leave as 'F0'.
		% if (receivedTeam == teamNumber)
		%     singleByte = singleByte - teamNumber;
		%     if (singleByte > 9)
		%         fprintf('\n'); % Separate messages onto different lines.
		%     end
		%     fprintf('%c', singleByte + 48); % Print the ASCII version of the byte.
		% end
    end    
end


end