// FILE: serialPc-M-IK-1_0a.sce -Works!
// DATE: 04/20/20 10:34
// AUTH: P.Oh
// DESC: PC USB RS485 connect to (Master) NXT.  Scilab running on PC sends
//       serial message e.g. " @+56 , +40 " (without quotes) containing 
//       end-effector locations for XL-320 Lego-based 2-DOF planar manipulator.  
//       Master (running XXXX PC-M-S-1_0a.nxc) processes this message (and 
//       sends to Slave via Bluetooth).
// VERS: 1_0a: cleaned up version of serialPc-M-IK-0_1a.sce (worked)
// REFS: Works with Master NXT running P-M-S-IK-1_0a.nxc and Slave running
//       btS-R-IK-1_0a.nxc

h = openserial(10,"4800,n,8,1"); // initialize PC's serial port
strHeader = " @"; // white space + at character
stringRoger = "ROGER";
stringRogerFound = 1; // not TRUE

for i = 1:4 
    // four different (x,y) locations.  Recall that xl320-IK-1_0.nxc use 
    // (l1, l2); (l1, -l2); (l2, l1); (l2, -l1) and points.  Each coordinate 
    // must be sign followed by 3 characters i.e. a 4 character string: 
    // sign and 3 characters.  The 3 characters are the digits or when value 
    // < 3, then substitute with white space
    if i == 1 then
        strPosition01 = "+56 ";  // NB1: sign and 2 digits and white space
        strPosition02 = "+40 ";  
    end
    if i == 2 then
        strPosition01 = "+56 ";  
        strPosition02 = "-40 ";  
    end
    if i == 3 then
        strPosition01 = "+40 "; 
        strPosition02 = "+56 "; 
    end
    if i == 4 then
        strPosition01 = "+40 "; 
        strPosition02 = "-56 "; 
    end
        
    strI = strcat([strHeader, strPosition01, ", ", strPosition02]);
    disp(strI);
    writeserial(h, strI); // transmit serially to Master NXT

    buf = readserial(h);
    // Check if Master ready to receive next string
    stringRogerFound = strcmp(stringRoger, buf); // 0: means identical strings
    while (stringRogerFound ~=0) // then NXT -> PC string not ROGER, so wait
       buf = readserial(h);
       stringRogerFound = strcmp(stringRoger, buf);
       sleep(200); // min about 50 ms before reading serial port again
    end; // exit reading serial port when ROGER received           
    disp(buf);
    sleep(5000); // just slows down loop so user can see what's happening    
end

disp("All done!");
closeserial(h)

