0001 %SERIAL_OPEN - Opens the device file supplied as the argument "port" for
0002 %              serial communication in the manner required by GNU Octave
0003 %              or MATLAB.
0004 %
0005 % GNU Octave and MATLAB handle opening a serial port differently. This function
0006 % detects which environment it is in and opens the serial port accordingly.
0007 %
0008 % Syntax:  sp = serial_open(port)
0009 %
0010 % Inputs:
0011 %    port - the device file or communications port
0012 %
0013 % Outputs:
0014 %    sp - the handle for sending and receiving data over the serial port
0015 %
0016 % Example:
0017 %    sp = serial_open('/dev/ttyUSB0'); % UNIX like systems
0018 %    sp = serial_open('C0M9'); % Windows
0019 %
0020 %
0021 % Other m-files required: none
0022 % Subfunctions: none
0023 % MAT-files required: none
0024 %
0025 % See also:
0026 %
0027 % Author: Jonathan Thomson
0028 % Work:
0029 % email:
0030 % Website: http://jethomson.wordpress.com
0031 %
0032 %
0033 % MATLAB terminator notes:
0034 % Additionally, you can set Terminator to a 1-by-2 cell array. The first element
0035 % of the cell is the read terminator and the second element of the cell array is 
0036 % the write terminator.
0037 % When performing a write operation using the fprintf function, all occurrences 
0038 % of \n are replaced with the Terminator value. Note that %s\n is the default
0039 % format for fprintf. A read operation with fgetl, fgets, or fscanf completes
0040 % when the Terminator value is read. The terminator is ignored for binary
0041 % operations.
0042 % Source: http://www.mathworks.com/help/toolbox/instrument/terminator.html
0043 
0044 
0045 
0046 function sp = serial_open(port)
0047 
0048     BOOTLOADER_PAUSE_TIME = 3; % seconds
0049 
0050     fprintf('Opening serial port. ');
0051 
0052     if exist('OCTAVE_VERSION')
0053         sp = fopen(port, 'r+');
0054     else
0055         % Terminator values are line feed ('\n') when receiving data
0056         % and nothing (no terminator) when sending data.
0057         sp = serial(port, 'BaudRate', 9600, ...
0058                     'Terminator', {'LF', ''});
0059         fopen(sp);
0060     end
0061     % opening the serial port in MATLAB causes the uc to reset.
0062     % pause to allow the bootloader to timeout.
0063     fprintf('Pausing for bootloader. ');
0064     pause(BOOTLOADER_PAUSE_TIME);
0065     disp('Done.')
0066 end