//This program is intended for use with a TMCM-100 with motor and encoder.
//It detects if the shaft is being turned manually and brings it back to
//its original position when manual turning has ended.

Velocity = 4000

//Current values: 0..255 (255=100%)
        SAP 6, 0, 150   //Current when motor is rotating with constant velocity
        SAP 7, 0, 10    //Standby current
        SAP 21, 0, 200  //Current when motor is accelerating

        SAP 4, 0, Velocity  //Velocity to be used for normal positioning
        SAP 5, 0, 50    //Acceleration

//The microstep resolution and the encoder predivider/multiplier are set so
//that microsteps/revolution and encoder steps/revolution are equal.
        SAP 16, 0, 4
        SAP 27, 0, 1
        SAP 28, 0, 1

//Set up the encoder functionality:
//"Deviation correction" is not needed here, so we turn it off.
        SAP 29, 0, 0
        SAP 30, 0, 0
        SAP 31, 0, 0
        
//We need "automatic correction after positioning"
        SAP 32, 0, 1  //Start soon after positioning has finished
        SAP 34, 0, Velocity  //Velcity to be used for position correction


//Reset motor and encoder position
        SAP 1, 0, 0

//Main loop: See if the encoder position is changing, and just do an absolute
//move to 0 when the encoder position is not changing any more.
//The MVP ABS 0, 0 command also triggers the automatic position correction which
//brings the shaft to its original position.

Loop:   GAP 25, 0           //Get actual encoder position
        CALCX LOAD          //Copy to X register
        WAIT TICKS, 0, 10   //Short delay (please try to make it shorter or longer)
        GAP 25, 0           //Read encoder again
        CALCX SUB           //See if it has changed
        JC NZ, Loop         //Yes, so continue waiting until it is not changing any more
        
        MVP ABS, 0, 0       //No, so try to move back to original position
                            //(this also triggers the automatic position correction)
        WAIT POS, 0, 0      //Wait until done
        JA Loop
        
