%-----------------------------------|
% ECG Interface: Oxford University  |
%-----------------------------------|
% Configure the HyperTerminal application for the following
% default Configuration:
% - Baud Rate = 115200
% - Data Bits = 8
% - Parity Type = None
% - Stop Bits = One

% Open constructor:
% tabpanel('ECG_interface','myTab')

function varargout = ECG_interface(varargin)
% ECG_INTERFACE MATLAB code for ECG_interface.fig
%      ECG_INTERFACE, by itself, creates a new ECG_INTERFACE or raises the existing
%      singleton*.
%
%      H = ECG_INTERFACE returns the handle to a new ECG_INTERFACE or the handle to
%      the existing singleton*.
%
%      ECG_INTERFACE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in ECG_INTERFACE.M with the given input arguments.
%
%      ECG_INTERFACE('Property','Value',...) creates a new ECG_INTERFACE or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before ECG_interface_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to ECG_interface_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help ECG_interface

% Last Modified by GUIDE v2.5 17-Oct-2013 17:26:00

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ECG_interface_OpeningFcn, ...
                   'gui_OutputFcn',  @ECG_interface_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% 
% function tx
% 
% global BufferSize
% global BaudRate
% global dif
% global COM
% 
% if (dif == 1)
%     infos = instrhwinfo('serial');               %instrument control toolbox! instrhwinfo: information about available hardware
%     coms = size(infos.SerialPorts);
%     if coms(1,1) == 0
%         msgbox('No serial port was found in the system. Please connect the ECG monitor device and restart the Interface.','Help Box:','error');
%         return
%     end
%     
%     %     if ispc
%     %         uports = infos.SerialPorts;
%     %         t_port = 1;
%     %         port = uports{t_port};
%     %         %elseif isunix
%     %     end
%     % On Linux:     port = '/dev/ttyS0';
%     % On MacOS:     port = '/dev/tty.KeySerial1';
%     % On Windows:   port = 'COM1';
%     %out = 0;
%     for i = 1: coms(1,1)
%         %delete(instrfind)
%         s = serial(uports{i});
%         set(s, 'InputBufferSize', BufferSize);            % bytes nr in out buffer: default is 512. 15*1000 bytes
%         %set(s, 'FlowControl', 'hardware');
%         set(s, 'BaudRate', BaudRate);                  % 115200, 128000 and 256000 bits persecond
%         set(s, 'Parity', 'none');
%         set(s, 'DataBits', 8);
%         set(s, 'StopBit', 1);
%         set(s, 'Timeout',10);
%         %set(s, 'RequestToSend','on');
% 
%         %m = zeros(2,1);                                                     %soluçao momentanea pa criar uma matriz de 2 caracteres
%         %m = char(m);
%         %m(2) = bitand(round(t_aquisicao1), 255);
%         %aux = bitshift(round(t_aquisicao1), -8);
%         %m(1) = bitand(aux, 255);
%         fopen(s);     
%         
%         fwrite(s,87);
%         fwrite(s,72);
%         fwrite(s,79);
%         fwrite(s,0);
%         %fwrite(s,m);                                                        %em x de enviarmos um numero com 8 bits, desta forma criamos uma matriz com 2 caracteres de 2 bytes onde vamos por o nº. desta forma n se envia em binario de um char, mas envia se em binario
%         
%         out = fread(s,4);
%         if out(1) == 87 & out(1) == 72 & out(1) == 79 & out(1) == 0
%             fclose(s)
%             delete(s)
%             clear s
%             COM = uports{i};
%             break;
%         end
%         fclose(s)
%         delete(s)
%         clear s
%         %out = bitshift(double(out(2)), 8) + double(out(3));                 %para converter no numero k keremos, fazemos o contrario e fazemos uma soma do byte mudado pa eskerda (em 8 bits) com o byte - significativo
%         %Use double to convert a character array into its numeric codes.
%     end
%     
%     dif = 0;
% end

% --- Executes just before ECG_interface is made visible.
function ECG_interface_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to ECG_interface (see VARARGIN)

% Choose default command line output for ECG_interface
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes ECG_interface wait for user response (see UIRESUME)
% uiwait(handles.figure1);

%clear all
clc

% VARIABLE DEFINITIONS:
global BufferSize
global BaudRate
global PlottedSamples
global SamplingFrequency
global SignalSource
%global dif

axes(handles.axes3);
imshow('ECGox.jpg');

set(handles.popupmenu1,'Value',3);              % 500 SPS
%    '125 SPS'
%    '250 SPS'
%    '500 SPS'
%    '1 KSPS'
%    '2 KSPS'
%    '4 KSPS'
%    '8 KSPS'
set(handles.popupmenu2,'Value',1);
set(handles.edit1,'String',2000);
set(handles.edit2,'String',200);

BufferSize = 2000;
BaudRate = 115200;
PlottedSamples = 200;
SamplingFrequency = 500;    % Hz
SignalSource = 1;           % ECG signal

cla(handles.axes1,'reset')
set(handles.axes1,'Color',[0.502 0.502 0.502]);
set(handles.axes2,'Color',[0.502 0.502 0.502]);

%dif = 1;
%tx;

% Create the serial object:
infos = instrhwinfo('serial');               %instrument control toolbox! instrhwinfo: information about available hardware
ports = size(infos.SerialPorts);
if ports(1,1) == 0
    msgbox('No serial port was found in the system. Please connect the ECG monitor device and restart the Interface.','Help Box:','error');
    return
end

%if ispc
if ports(1,1) > 1
    prompt = {'Enter the ECG serial port:'};
    dlg_title = '3-lead ECG';
    num_lines = 1;
    def = {''};
    answer = inputdlg(prompt,dlg_title,num_lines,def);
    port = answer{1};
else
    uports = infos.SerialPorts;
    t_port = 1;
    port = uports{t_port};
end
%elseif isunix
%end
% On Linux:     port = '/dev/ttyS0';
% On MacOS:     port = '/dev/tty.KeySerial1';
% On Windows:   port = 'COM1';
try
    s = serial(port);
    set(s, 'InputBufferSize', BufferSize);            % bytes nr in out buffer: default is 512. 15*1000 bytes
    %set(s, 'FlowControl', 'hardware');
    set(s, 'BaudRate', BaudRate);                  % 115200, 128000 and 256000 bits persecond
    set(s, 'Parity', 'none');
    set(s, 'DataBits', 8);
    set(s, 'StopBit', 1);
    set(s, 'Timeout',10);
    %set(s, 'RequestToSend','on');
    
    fopen(s);                                    % opens the serial port
    
    % RESET ECG acquisition:
    fwrite(s,1);                                 % fprintf(s,'%s','w');
    fwrite(s,1);                                 % fprintf(s,'%s','h');
    fwrite(s,6);                                 % fprintf(s,'%s','o');
    fwrite(s,4);
    
    fclose(s);
    delete(s);
    clear s;
catch exception
    if ports(1,1) > 1
        prompt = {'Enter the ECG serial port:'};
        dlg_title = '3-lead ECG: Try again';
        num_lines = 1;
        def = {''};
        answer = inputdlg(prompt,dlg_title,num_lines,def);
        port = answer{1};
    else
        uports = infos.SerialPorts;
        t_port = 1;
        port = uports{t_port};
    end
    
    s = serial(port);
    set(s, 'InputBufferSize', BufferSize);            % bytes nr in out buffer: default is 512. 15*1000 bytes
    %set(s, 'FlowControl', 'hardware');
    set(s, 'BaudRate', BaudRate);                  % 115200, 128000 and 256000 bits persecond
    set(s, 'Parity', 'none');
    set(s, 'DataBits', 8);
    set(s, 'StopBit', 1);
    set(s, 'Timeout',10);
    %set(s, 'RequestToSend','on');
    
    fopen(s);                                    % opens the serial port
    
    % RESET ECG acquisition:
    fwrite(s,1);                                 % fprintf(s,'%s','w');
    fwrite(s,1);                                 % fprintf(s,'%s','h');
    fwrite(s,6);                                 % fprintf(s,'%s','o');
    fwrite(s,4);
    
    fclose(s);
    delete(s);
    clear s;
end


% --- Outputs from this function are returned to the command line.
function varargout = ECG_interface_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global BufferSize
global BaudRate
global PlottedSamples
%global SamplingFrequency
global s
global ecg
global time
global showTime
global count

%BufferSize
%BaudRate
%PlottedSamples

cla(handles.axes1,'reset')
set(handles.axes1,'Color',[0.502 0.502 0.502]);

% Create the serial object:
infos = instrhwinfo('serial');               %instrument control toolbox! instrhwinfo: information about available hardware
ports = size(infos.SerialPorts);
if ports(1,1) == 0
    msgbox('No serial port was found in the system. Please connect the ECG monitor device and restart the Interface.','Help Box:','error');
    return
end

if ispc
    uports = infos.SerialPorts;
    t_port = 1;
    port = uports{t_port};
%elseif isunix
end
% On Linux:     port = '/dev/ttyS0';
% On MacOS:     port = '/dev/tty.KeySerial1';
% On Windows:   port = 'COM1';

s = serial(port);
set(s, 'InputBufferSize', BufferSize);            % bytes nr in out buffer: default is 512. 15*1000 bytes
%set(s, 'FlowControl', 'hardware');
set(s, 'BaudRate', BaudRate);                  % 115200, 128000 and 256000 bits persecond
set(s, 'Parity', 'none');
set(s, 'DataBits', 8);
set(s, 'StopBit', 1);
set(s, 'Timeout',10);
%set(s, 'RequestToSend','on');

fopen(s);                                    % opens the serial port

% START ECG acquisition:
fwrite(s,1);                                 % fprintf(s,'%s','w');
fwrite(s,1);                                 % fprintf(s,'%s','h');
fwrite(s,8);                                 % fprintf(s,'%s','o');
fwrite(s,4);

hold on;
set(gcf,'currentcharacter','G')

try
    %fprintf('\n-------------------------------\n')
    t = 1;
    ecg = int32(zeros(1,2000000));                 % Preallocate 2M samples
    time = zeros(1,2000000);
    showTime = 0;
    %t0 = 2*BufferSize/15;    %15 bytes of eacg packet
    count = 0;
    
    while t
        
        set(handles.pushbutton1,'Enable','off')
        %set(handles.pushbutton2,'Enable','off')
        set(handles.popupmenu1,'Enable','off')
        set(handles.popupmenu2,'Enable','off')
        set(handles.edit1,'Enable','off')
        set(handles.edit2,'Enable','off')
        Cont_or_Quit = get(gcf,'currentcharacter');
        if (Cont_or_Quit ~='G')
           
            set(handles.pushbutton1,'Enable','on')
            %set(handles.pushbutton2,'Enable','on')
            set(handles.popupmenu1,'Enable','on')
            set(handles.popupmenu2,'Enable','on')
            set(handles.edit1,'Enable','on')
            set(handles.edit2,'Enable','on')
            
            % STOP ECG acquisition:
            fwrite(s,1);                                 % fprintf(s,'%s','w');
            fwrite(s,1);                                 % fprintf(s,'%s','h');
            fwrite(s,10);                                % fprintf(s,'%s','o');
            fwrite(s,4);
            
            fclose(s);
            delete(s);
            clear s;
            
            break;
        end
        
        a = fread(s);
        a=a';
        if count ~=0
            a = [temp,a];
        end
        
        %fprintf('\n1\n')
        ind = find(a==69);
        
        % Check if the last 69 byte is not a command start
        if (a(ind(end)) == 69) && (a(ind(end)-1) ~= 4)
            ind(end) = [];
        end
        
        % Save bytes of last packet that might be incomplete:
        temp = a(ind(end):end);
        ind(end) = [];                                          % Remove from processing
        
        %fprintf('\n2\n')
        % Check from all the other 69 bytes which ones are a command start
        for i = 1:length(ind)
            if count >= 1 && (i~=1)
                if(a(ind(i)) == 69) && (a(ind(i)-1) ~= 4)
                    ind(i) = 0;
                end
            elseif (count == 0) && (i~=1) && a(ind(i)) ~= a(1)  % To avoid for the first 69 always present from the second while loop
                if(a(ind(i)) == 69) && (a(ind(i)-1) ~= 4)
                    ind(i) = 0;
                end
            end
        end
        ind(ind==0) = [];
        
        %fprintf('\n3\n')
        ECGlead = bitshift(a(ind(1:end)+8), 16) + bitshift(a(ind(1:end)+9), 8) + a(ind(1:end)+10);
        %ECGlead2 = bitshift(a(ind(1:end)+11), 16) + bitshift(a(ind(1:end)+12), 8) + a(ind(1:end)+13);
        ECGlead1 = int32(ECGlead);
        ECGl = find(ECGlead>(2^24)/2-1);
        ECGlead1(ECGl) = int32(ECGlead(ECGl))-2^24;

        %fprintf('\n4\n')
        timet = showTime(end)+1:showTime(end)+length(ECGlead1);
        %fprintf('\n5\n')
        
        if count == 0
            ecg(1:length(ECGlead1)) = ECGlead1;
            time(1:length(timet)) = timet;
        else
            ind = find(ecg);
            ecg(length(ind)+1:length(ind)+length(ECGlead1)) = ECGlead1;
            time(length(ind)+1:length(ind)+length(timet)) = timet;
        end
        %fprintf('\n6\n')
        eind = find(ecg);
        tind = find(time);
        showEcg = ecg(1:length(eind));
        showTime = time(1:length(tind));
        plot(handles.axes1,showTime,showEcg,'Marker','.','LineWidth',1,'Color',[0 1 0]);
        set(handles.axes1,'Color',[0.502 0.502 0.502],'YGrid','on','XGrid','on')%, ...
            %'YColor',[0.941 0.941 0.941],'XColor',[0.941 0.941 0.941]);
        xlim(handles.axes1,[showTime(end)-PlottedSamples showTime(end)]);
        %ylim(handles.axes1,)
        drawnow;
        set(handles.axes1,'Visible','on');

        %axis([0,interv,0,1024]);
        
        %timet = time+(datenum(clock))/length(ECGlead1(1:end));
        %time(count) = datenum(clock);
        %time = cputime - initial_time;
        %create time signal
        %time =(0:length(ECGlead1)-1)/SamplingFrequency;
        %set(plotHandle,'YData',ecg,'XData',time);
        %set(plotHandle,'YData',ECGlead1,'XData',count);
        %set(figureHandle,'Visible','on');
        %time = time+1;
        
        count = count+1;
        %clc
        %fprintf('\n-------------------------------\n')
    end
catch exception
    set(handles.pushbutton1,'Enable','on')
    %set(handles.pushbutton2,'Enable','on')
    set(handles.popupmenu1,'Enable','on')
    set(handles.popupmenu2,'Enable','on')
    set(handles.edit1,'Enable','on')
    set(handles.edit2,'Enable','on')
    
    % STOP ECG acquisition:
    fwrite(s,1);                                 % fprintf(s,'%s','w');
    fwrite(s,1);                                 % fprintf(s,'%s','h');
    fwrite(s,10);                                % fprintf(s,'%s','o');
    fwrite(s,4);
    
    fclose(s);
    delete(s);
    clear s;
end


% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global BufferSize
global BaudRate
global PlottedSamples
global SamplingFrequency
global SignalSource
global s
global ecg
global time
global showTime
global count

%try
if isvalid(s)
        %fwrite(s,1);                                 % fprintf(s,'%s','w');
        %fwrite(s,1);                                 % fprintf(s,'%s','h');
        %fwrite(s,6);                                 % fprintf(s,'%s','o');
        %fwrite(s,4);
        
        % STOP ECG acquisition:
        fwrite(s,1);                                 % fprintf(s,'%s','w');
        fwrite(s,1);                                 % fprintf(s,'%s','h');
        fwrite(s,10);                                % fprintf(s,'%s','o');
        fwrite(s,4);
        
        hold off
        set(handles.axes1,'Visible','off');
        cla(handles.axes1,'reset')
        clear handles.axes
        set(handles.axes1,'Color',[0.502 0.502 0.502]);
        %set(handles.axes2,'Color',[0.502 0.502 0.502]);
        
        ecg = int32(zeros(1,2000000));                 % Preallocate 2M samples
        time = zeros(1,2000000);
        showTime = 0;
        %t0 = 2*BufferSize/15;    %15 bytes of eacg packet
        count = 0;
        
        hold on
        set(handles.axes1,'Visible','on');
        % START ECG acquisition:
        fwrite(s,1);                                 % fprintf(s,'%s','w');
        fwrite(s,1);                                 % fprintf(s,'%s','h');
        fwrite(s,8);                                 % fprintf(s,'%s','o');
        fwrite(s,4);
    %end
else    
%catch exception
    
    set(handles.popupmenu1,'Value',3);              % 500 SPS
    %    '125 SPS'
    %    '250 SPS'
    %    '500 SPS'
    %    '1 KSPS'
    %    '2 KSPS'
    %    '4 KSPS'
    %    '8 KSPS'
    set(handles.popupmenu2,'Value',1);
    set(handles.edit1,'String',2000);
    set(handles.edit2,'String',200);
    
    BufferSize = 2000;
    BaudRate = 115200;
    PlottedSamples = 200;
    SamplingFrequency = 500;    % Hz
    SignalSource = 1;           % ECG signal
    
    cla(handles.axes1,'reset')
    set(handles.axes1,'Color',[0.502 0.502 0.502]);
    set(handles.axes2,'Color',[0.502 0.502 0.502]);
    
    % Create the serial object:
    infos = instrhwinfo('serial');               %instrument control toolbox! instrhwinfo: information about available hardware
    ports = size(infos.SerialPorts);
    if ports(1,1) == 0
        msgbox('No serial port was found in the system. Please connect the ECG monitor device and restart the Interface.','Help Box:','error');
        return
    end
    
    if ispc
        uports = infos.SerialPorts;
        t_port = 1;
        port = uports{t_port};
        %elseif isunix
    end
    % On Linux:     port = '/dev/ttyS0';
    % On MacOS:     port = '/dev/tty.KeySerial1';
    % On Windows:   port = 'COM1';
    
    s = serial(port);
    set(s, 'InputBufferSize', BufferSize);            % bytes nr in out buffer: default is 512. 15*1000 bytes
    %set(s, 'FlowControl', 'hardware');
    set(s, 'BaudRate', BaudRate);                  % 115200, 128000 and 256000 bits persecond
    set(s, 'Parity', 'none');
    set(s, 'DataBits', 8);
    set(s, 'StopBit', 1);
    set(s, 'Timeout',10);
    %set(s, 'RequestToSend','on');
    
    fopen(s);                                    % opens the serial port
    
    % RESET ECG acquisition:
    fwrite(s,1);                                 % fprintf(s,'%s','w');
    fwrite(s,1);                                 % fprintf(s,'%s','h');
    fwrite(s,6);                                 % fprintf(s,'%s','o');
    fwrite(s,4);
    
    fclose(s);
    delete(s);
    clear s;
end

% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1
global SamplingFrequency
global BufferSize
global BaudRate
global s

SamplingFrequency = get(hObject,'Value') - 1;

if isvalid(s)
    
%     % STOP ECG acquisition:
%     fwrite(s,1);                                 % fprintf(s,'%s','w');
%     fwrite(s,1);                                 % fprintf(s,'%s','h');
%     fwrite(s,10);                                % fprintf(s,'%s','o');
%     fwrite(s,4);
    
    fwrite(s,1);                                 % fprintf(s,'%s','w');
    fwrite(s,85);                                % fprintf(s,'%s','h');
    fwrite(s,SamplingFrequency);                 % fprintf(s,'%s','o');
    fwrite(s,4);
    
%     % START ECG acquisition:
%     fwrite(s,1);                                 % fprintf(s,'%s','w');
%     fwrite(s,1);                                 % fprintf(s,'%s','h');
%     fwrite(s,8);                                 % fprintf(s,'%s','o');
%     fwrite(s,4);
    %end
else
    %catch exception

    % Create the serial object:
    infos = instrhwinfo('serial');               %instrument control toolbox! instrhwinfo: information about available hardware
    ports = size(infos.SerialPorts);
    if ports(1,1) == 0
        msgbox('No serial port was found in the system. Please connect the ECG monitor device and restart the Interface.','Help Box:','error');
        return
    end
    
    if ispc
        uports = infos.SerialPorts;
        t_port = 1;
        port = uports{t_port};
        %elseif isunix
    end
    % On Linux:     port = '/dev/ttyS0';
    % On MacOS:     port = '/dev/tty.KeySerial1';
    % On Windows:   port = 'COM1';
    
    s = serial(port);
    set(s, 'InputBufferSize', BufferSize);            % bytes nr in out buffer: default is 512. 15*1000 bytes
    %set(s, 'FlowControl', 'hardware');
    set(s, 'BaudRate', BaudRate);                  % 115200, 128000 and 256000 bits persecond
    set(s, 'Parity', 'none');
    set(s, 'DataBits', 8);
    set(s, 'StopBit', 1);
    set(s, 'Timeout',10);
    %set(s, 'RequestToSend','on');
    
    fopen(s);                                    % opens the serial port
    
    fwrite(s,1);                                 % fprintf(s,'%s','w');
    fwrite(s,85);                                % fprintf(s,'%s','h');
    fwrite(s,SamplingFrequency);                 % fprintf(s,'%s','o');
    fwrite(s,4);
    
    fclose(s);
    delete(s);
    clear s;
end

% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double
global BufferSize
BufferSize = str2double(get(hObject,'String'));


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double
global PlottedSamples
PlottedSamples = str2double(get(hObject,'String'));


% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu2
global BufferSize
global BaudRate
global SignalSource
global PlottedSamples
global s

if get(hObject,'Value') == 1
    SignalSource = 1;
    PlottedSamples = 500;
    set(handles.edit2,'String',500);
else
    SignalSource = 2;
    PlottedSamples = 2000;
    set(handles.edit2,'String',2000);
end

%try
if isvalid(s)
        fwrite(s,1);                                 % fprintf(s,'%s','w');
        fwrite(s,1);                               % fprintf(s,'%s','h');
        fwrite(s,SignalSource);                      % fprintf(s,'%s','o');
        fwrite(s,4);
    %end
else    
%catch exception
    % Create the serial object:
    infos = instrhwinfo('serial');               %instrument control toolbox! instrhwinfo: information about available hardware
    ports = size(infos.SerialPorts);
    if ports(1,1) == 0
        msgbox('No serial port was found in the system. Please connect the ECG monitor device and restart the Interface.','Help Box:','error');
        return
    end
    
    if ispc
        uports = infos.SerialPorts;
        t_port = 1;
        port = uports{t_port};
        %elseif isunix
    end
    % On Linux:     port = '/dev/ttyS0';
    % On MacOS:     port = '/dev/tty.KeySerial1';
    % On Windows:   port = 'COM1';
    
    s = serial(port);
    set(s, 'InputBufferSize', BufferSize);            % bytes nr in out buffer: default is 512. 15*1000 bytes
    %set(s, 'FlowControl', 'hardware');
    set(s, 'BaudRate', BaudRate);                  % 115200, 128000 and 256000 bits persecond
    set(s, 'Parity', 'none');
    set(s, 'DataBits', 8);
    set(s, 'StopBit', 1);
    set(s, 'Timeout',10);
    %set(s, 'RequestToSend','on');
    
    fopen(s);                                % opens the serial port
    
    fwrite(s,1);                                 % fprintf(s,'%s','w');
    fwrite(s,1);                               % fprintf(s,'%s','h');
    fwrite(s,SignalSource);                      % fprintf(s,'%s','o');
    fwrite(s,4);
    
    
    fclose(s);
    delete(s);
    clear s;
end

% --- Executes during object creation, after setting all properties.
function popupmenu2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
