///////////////////////////////////////////////////////////////////////////////////////
//
//    Program to Demonstrate Synchronization of Two NXT Motors using RobotC
//
// This example will loop continuously. Motor A is rotated one complete revolution. Motor
// C is slaved to motor A movement, but set to go only 50% of its speed. After 2 seconds,
// the synchronization will be reversed, so A is slaved to C with the same ratio, and so
// A will go half the speed of C.
//
// There will be a brief pause / wait before the next iteration of the loop.
//
// You can best view the motor movement by attaching a beam to each of the motor output to
// create / a shape like the 'hand' on a clock.
//
///////////////////////////////////////////////////////////////////////////////////////

task main()
{
  //
  // These variables are declared as RAM values. This will allow you, in the RobotC
  // interactive real-time debugger to change them and watch the effect on the motor.
  //
  int nMoveSize     = 360;    // One full rotation
  int nSpeed        = 35;
  int nDelay        = 2000;
  int nTurnRatio    = 50;  //C will travel half as fast as A, in the same direction

  const TSynchedMotors kSyncType     = synchAC;
  const tMotor         kPrimaryMotor = motorA;
  //
  // Setup the motor configuration
  //
  bFloatDuringInactiveMotorPWM = false;

  nMotorEncoder[kPrimaryMotor]       = 0;
  nMotorEncoderTarget[kPrimaryMotor] = 0;

  //
  // Enable synchronization between two motors.
  //     -- motor C will be the 'primary' motor
  //     -- motor B will be the slave motor
  //     -- Turn ratio +100% -- same direction and same speed as primary
  //                      0  -- stopped
  //                   -100% -- reversed direct and same speed as primary
  //
  nSyncedMotors            = kSyncType;  // "C" will be synchronized to "A".
  nSyncedTurnRatio         = nTurnRatio;
  nPidUpdateInterval       = 10;   // Best performance if we do really frequent updates
                                     // (i.e. calculation) on the motor speeds to correct
                                     // for errors.
  while (true)
  {
    //
    // Loop continuously moving the motors forward one revolution of "A"
    //
    nMotorEncoderTarget[kPrimaryMotor] = nMoveSize; // incremental amount to move motor
    motor[kPrimaryMotor]               = nSpeed;    // motor speed
    wait1Msec(nDelay);                       // wait for action to complete

  	nSyncedMotors            = synchCA;  // Reverse: "C" will be synchronized to "A".
  	nSyncedTurnRatio         = nTurnRatio;

    nMotorEncoderTarget[motorC] 	= nMoveSize; // incremental amount to move motor
    motor[motorC]                 = nSpeed;    // motor speed
    wait1Msec(nDelay);                       // wait for action to complete

    nSyncedMotors            = kSyncType;  // Reset: "C" will be synchronized to "A".
	  nSyncedTurnRatio         = nTurnRatio;
  }
}