/*
 * Multi axis several shifts with calibration script
 *
 * Description of the script: 
 *  This program makes shifts given number of times to the specified distance, and stands the appointed time after every shift. First it goes left, then it returns back to the origin and repeats all movements to right.
 * 
 * Note:
 *  This is a rather difficult script to learn, since it uses a large number of commands and structures.
 * 
 * Important: 
 *  To run the script, upload it to the mDrive Direct Control software. For multi-controller operation, open them in a single multi-axis mDrive Direct Control window
 */

const LEFT = -1;
const RIGHT = 1;

var axes = [];
var number_of_axes = 0;
var last_serial = 0;
while (serial = get_next_serial(last_serial)) // get next serial number and repeat for each axes.
{
    axes[number_of_axes] = new_axis(serial);
    log("Found axis " + number_of_axes + " with serial number " + serial);
    number_of_axes++;
    last_serial = serial;
}

// Start the main function for all avaliable axes
for (var i = 0; i < number_of_axes; i++)
{
    main(axes[i]);
}


function main(axis)
{
    axis.command_move(0,0); // Go back to the origin.
    msleep(500);

/* Creating and filling the calibration structure for specifying distances in um */
    var calibration = new Object;
    calibration.A = 5; // 1 step correspond to 5 um for 8MT50-100BS1
    calibration.MicrostepMode = axis.get_engine_settings().MicrostepMode; // Get MicrostepMode from controller settings
/*******************************************************/

/* Main cycle */

    var N = 10; // Number of shifts
    var stand_time  = 3000; // Stand time in ms
    var shift = 10; // Distance of shift in um

    MakeShifts(axis, LEFT,   shift, N, stand_time, calibration); // Make 10 shifts to the left
    MakeShifts(axis, RIGHT, shift, N, stand_time, calibration); // Make 10 shifts to the right
    MakeShifts(axis, RIGHT, shift, N, stand_time, calibration); // Make 10 shifts to the right again
    MakeShifts(axis, LEFT,   shift, N, stand_time, calibration); // Make 10 shifts to the left
}

function MakeShifts(axis, Direction, ShiftDistance, ShiftsQuantity, StandTime, Calibration)
{
/**
    This function makes shifts which number is specified by ShiftQuantity and length is specified by ShiftDistance. After every shift it stands StandTime miliseconds. Calibration parameter is a structure for convertation between steps and micrometers.
*/
    for (var i = 0; i < ShiftsQuantity; i++)
    {
        axis.command_movr_calb(Direction*ShiftDistance, Calibration);
        axis.command_wait_for_stop(100);
        msleep(StandTime);
    }
}