Codeserialport: Difference between revisions

From CNI Wiki
Jump to navigation Jump to search
imported>Saggar
No edit summary
imported>Saggar
No edit summary
Line 8: Line 8:
     % Written by Manish Saggar (saggar@stanford.edu) on 3/26/2012
     % Written by Manish Saggar (saggar@stanford.edu) on 3/26/2012
     function tabletCodeSerialPort()
     function tabletCodeSerialPort()
    % change the path below for location of tablet mount, usually in
      % change the path below for location of tablet mount, usually in
    % /dev/...
      % /dev/...
    s = serial('/dev/cu.usbmodem12341','BaudRate',57600);
      s = serial('/dev/cu.usbmodem12341','BaudRate',57600);
     fopen(s);     
     fopen(s);     
     c = onCleanup(@()letscleanup(s));
     c = onCleanup(@()letscleanup(s));

Revision as of 19:15, 26 March 2012

Matlab code to use serial port to communicate with the CNI tablet.

NOTE: on Linux, you may need to create a symbolic link for matlab to find the port location; see here for more info http://www.mathworks.com/support/solutions/en/data/1-3ZT8GP/index.html?product=ML&solution=1-3ZT8GP

   % Code to use CNI Tablet using serial port
   % Aim: Simply outputs x and y coordinates from the tablet.  
   % Written by Manish Saggar (saggar@stanford.edu) on 3/26/2012
   function tabletCodeSerialPort()
      % change the path below for location of tablet mount, usually in
      % /dev/...
      s = serial('/dev/cu.usbmodem12341','BaudRate',57600);
   fopen(s);     
   c = onCleanup(@()letscleanup(s));
   % screen resolution
   theRect = [0 0 1200 800];
   while(1)
       ln = fgets(s);
       if size(ln,2) ~=18 || ln(3) == 'N'
           continue;
       end            
       x = str2double(ln(3:5));
       y = str2double(ln(9:11));
       b = str2double(ln(15));
       if x <= 0 || y <= 0
           continue;
       end 
       x = floor((x/(850+180))*theRect(3))
       y = floor((y/(800+230))*theRect(4))
   end
   fclose(s); delete(s); clear s; 
   end
   % if Ctrl+C is used this function clears up the pointer of the tablet.
   % Otherwise Matlab crashes or you need to quit matlab every time. 
   function letscleanup(s)
   % clear serial port
   fclose(s); delete(s); clear s; 
   Screen('CloseAll');
   ShowCursor;
   psychrethrow(psychlasterror);
   end