/**
  ******************************************************************************
  * @file    l6208.c 
  * @author  IPC Rennes
  * @version V1.5.0
  * @date    June 1st, 2018
  * @brief   L6208 product related routines
  * @note    (C) COPYRIGHT 2016 STMicroelectronics
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */

#include "l6208.h"
#include "string.h"

/** @addtogroup BSP
  * @{
  */   
   
/** @addtogroup L6208
  * @{
  */   

/* Private constants ---------------------------------------------------------*/

/** @addtogroup L6208_Private_Constants
  * @{
  */

/// The maximum number of devices
#define MAX_NUMBER_OF_DEVICES        (1)

/// Bridge A
#define BRIDGE_A                     (0)
/// Bridge B
#define BRIDGE_B                     (1)

/// Bitmaps for system flags
#define EN_A_set              0x00000001    ///< EN_A pin status
#define HiZstop               0x00000002    ///< motor has to be left in HiZ after stopping
#define busy                  0x00000004    ///< stepper position command executing flag
#define running               0x00000008    ///< running motor flag
#define velocitymode          0x00000010    ///< velocity controlled stepper motor
#define positionmode          0x00000020    ///< position controlled stepper motor
#define fullstep              0x00000040    ///< full step mode controlled    
#define halfstep              0x00000080    ///< half step mode controlled    
#define microstep             0x00000100    ///< micro step mode controlled
#define forward               0x00000200    ///< forward running motor
#define dir2change            0x00000400    ///< direction has to be changed while the motor is running
#define fastdecaymode         0x00000800    ///< decay mode is fast
#define wavestep              0x00001000    ///< wave step mode controlled

/**
  * @}
  */ 

/* Private variables ---------------------------------------------------------*/

/** @addtogroup L6208_Private_Variables
  * @{
  */

/// Function pointer to flag interrupt call back
void (*flagInterruptCallback)(void);
/// Function pointer to error handler call back
void (*errorHandlerCallback)(uint16_t);
static volatile bool isrFlag = FALSE;
static uint16_t l6208DriverInstance = 0;

/// L6208 Device Paramaters structure
deviceParams_t devicePrm;

/// Exponent used to scale the sine function for the RefMicroTable
#define L6208_SINE_WAVEFORM_POWER_OF_TWO_MAX_VALUE (15)

/// RefMicroTable values are 2^L6208_SINE_WAVEFORM_POWER_OF_TWO_MAX_VALUE*|sin(n/16*PI/2)|
/// where n is the index in the table
const uint16_t RefMicroTable[L6208_USTEPS_PER_QUARTER_PERIOD*3] =
{
    0,3212,6393,9512,12540,15447,18205,20788,23170,25330,27246,28899,30274,31357,32138,32610,
    32768,32610,32138,31357,30274,28899,27246,25330,23170,20788,18205,15447,12540,9512,6393,3212,
    0,3212,6393,9512,12540,15447,18205,20788,23170,25330,27246,28899,30274,31357,32138,32610
};

/// microstepping PWM period and torque scaled waveform samples array
uint16_t updatedMicroTable[L6208_USTEPS_PER_QUARTER_PERIOD+1];
/// waveform microstepping PWM period sample arrays for VREFA wave
uint16_t microTable1[L6208_USTEPS_PER_QUARTER_PERIOD*3+1];
/// waveform microstepping PWM period sample array for VREFB wave, 90 deg shifted
uint16_t *pMicroTable2 = &(microTable1[16]);

/**
  * @}
  */ 

/* Private function prototypes -----------------------------------------------*/

/** @addtogroup L6208_Private_functions
  * @{
  */
void L6208_ClearSysFlag(uint32_t mask);
uint32_t L6208_ComputeNbAccOrDecSteps(uint16_t accOrDecRate);
uint16_t L6208_ConvertAcceDecelRateValue(uint16_t newAccOrDecRate);
void L6208_DoAccel(void);
void L6208_DoDecel(void);
void L6208_DoRun(void);
uint8_t L6208_GetMicrostepSample2Scale(void);
void L6208_Indexmodeinit(void);
bool L6208_IsSysFlag(uint32_t mask);
void L6208_ResetSteps(void);
uint32_t L6208_ScaleWaveformSample(uint8_t sampleIndex);
void L6208_ScaleWaveformTable(void);
void L6208_SetDeviceParamsToGivenValues(l6208_Init_t* pInitDevicePrm);
void L6208_SetDeviceParamsToPredefinedValues(void);
void L6208_SetMicrostepSample2Scale(uint8_t value);
void L6208_SetMicrostepSample2Update(uint8_t value);
void L6208_SetMotionState(motorState_t newMotionState);
bool L6208_SetSpeed(uint16_t newSpeed, uint32_t volatile *pSpeed);
void L6208_SetSysFlag(uint32_t mask);
bool L6208_StartMovement(void);
void L6208_UpdateScanWaveformTable(void);
void L6208_UstepWaveformHandling(void);
bool L6208_VectorCalc(uint8_t newTorque);
/**
  * @}
  */

/** @defgroup L6208_Exported_Variables L6208 Exported Variables
  * @{
  */       

/// L6208 motor driver functions pointer structure 
motorDrv_t   l6208Drv = 
{
  L6208_Init,                          //void (*Init)(void*);
  L6208_ReadId,                        //uint16_t (*ReadID)(void);
  L6208_AttachErrorHandler,            //void (*AttachErrorHandler)(void (*callback)(uint16_t));
  L6208_AttachFlagInterrupt,           //void (*AttachFlagInterrupt)(void (*callback)(void));
  0,                                   //void (*AttachBusyInterrupt)(void (*callback)(void));
  L6208_FlagInterruptHandler,          //void (*FlagInterruptHandler)(void);
  L6208_GetAcceleration,               //uint16_t (*GetAcceleration)(uint8_t);
  L6208_GetCurrentSpeed,               //uint16_t (*GetCurrentSpeed)(uint8_t);
  L6208_GetDeceleration,               //uint16_t (*GetDeceleration)(uint8_t);
  L6208_GetMotionState,                //motorState_t(*GetDeviceState)(uint8_t);
  L6208_GetFwVersion,                  //uint32_t (*GetFwVersion)(void);
  L6208_GetMark,                       //int32_t (*GetMark)(uint8_t);
  L6208_GetMaxSpeed,                   //uint16_t (*GetMaxSpeed)(uint8_t);
  L6208_GetMinSpeed,                   //uint16_t (*GetMinSpeed)(uint8_t);
  L6208_GetPosition,                   //int32_t (*GetPosition)(uint8_t);
  L6208_GoHome,                        //void (*GoHome)(uint8_t);
  L6208_GoMark,                        //void (*GoMark)(uint8_t);
  L6208_GoTo,                          //void (*GoTo)(uint8_t, int32_t);
  L6208_HardStop,                      //void (*HardStop)(uint8_t);
  L6208_Move,                          //void (*Move)(uint8_t, motorDir_t, uint32_t );
  0,                                   //void (*ResetAllDevices)(void);
  L6208_Run,                           //void (*Run)(uint8_t, motorDir_t);
  L6208_SetAcceleration,               //bool(*SetAcceleration)(uint8_t ,uint16_t );
  L6208_SetDeceleration,               //bool(*SetDeceleration)(uint8_t , uint16_t );
  L6208_SetHome,                       //void (*SetHome)(uint8_t, int32_t);
  L6208_SetMark,                       //void (*SetMark)(uint8_t, int32_t);
  L6208_SetMaxSpeed,                   //bool (*SetMaxSpeed)(uint8_t, uint16_t );
  L6208_SetMinSpeed,                   //bool (*SetMinSpeed)(uint8_t, uint16_t );
  L6208_SoftStop,                      //bool (*SoftStop)(uint8_t);
  L6208_TickHandler,                   //void (*StepClockHandler)(uint8_t deviceId);
  L6208_WaitWhileActive,               //void (*WaitWhileActive)(uint8_t);
  L6208_Disable,                       //void (*CmdDisable)(uint8_t);
  L6208_Enable,                        //void (*CmdEnable)(uint8_t);
  0,                                   //uint32_t (*CmdGetParam)(uint8_t, uint32_t);
  0,                                   //uint16_t (*CmdGetStatus)(uint8_t);
  0,                                   //void (*CmdNop)(uint8_t);
  0,                                   //void (*CmdSetParam)(uint8_t, uint32_t, uint32_t);
  0,                                   //uint16_t (*ReadStatusRegister)(uint8_t);
  L6208_ReleaseReset,                  //void (*ReleaseReset)(uint8_t);
  L6208_Reset,                         //void (*Reset)(uint8_t);
  L6208_SetStepMode,                   //bool (*SelectStepMode)(uint8_t deviceId, motorStepMode_t);
  L6208_SetDirection,                  //void (*SetDirection)(uint8_t, motorDir_t);
  L6208_GoToDir,                       //void (*CmdGoToDir)(uint8_t, motorDir_t, int32_t);
  0,                                   //uint8_t (*CheckBusyHw)(void);
  L6208_CheckStatusHw,                 //uint8_t (*CheckStatusHw)(void);
  0,                                   //void (*CmdGoUntil)(uint8_t, motorAction_t, motorDir_t, uint32_t);
  0,                                   //void (*CmdHardHiZ)(uint8_t);
  0,                                   //void (*CmdReleaseSw)(uint8_t, motorAction_t, motorDir_t);
  0,                                   //void (*CmdResetDevice)(uint8_t);
  0,                                   //void (*CmdResetPos)(uint8_t);
  0,                                   //void (*CmdRun)(uint8_t, motorDir_t, uint32_t);
  0,                                   //void (*CmdSoftHiZ)(uint8_t);
  0,                                   //void (*CmdStepClock)(uint8_t, motorDir_t);
  0,                                   //void (*FetchAndClearAllStatus)(void);
  0,                                   //uint16_t (*GetFetchedStatus)(uint8_t);
  0,                                   //uint8_t (*GetNbDevices)(void);
  0,                                   //bool (*IsDeviceBusy)(uint8_t);
  0,                                   //void (*SendQueuedCommands)(void);
  0,                                   //void (*QueueCommands)(uint8_t, uint8_t, int32_t);
  0,                                   //void (*WaitForAllDevicesNotBusy)(void);
  L6208_ErrorHandler,                  //void (*ErrorHandler)(uint16_t);
  0,                                   //void (*BusyInterruptHandler)(void);
  0,                                   //void (*CmdSoftStop)(uint8_t);
  0,                                   //void (*StartStepClock)(uint16_t);
  0,                                   //void (*StopStepClock)(void);
  0,                                   //void (*SetDualFullBridgeConfig)(uint8_t);
  L6208_VrefPwmGetFreq,                //uint32_t (*GetBridgeInputPwmFreq)(uint8_t);
  L6208_VrefPwmSetFreq,                //void (*SetBridgeInputPwmFreq)(uint8_t, uint32_t);
  L6208_SetStopMode,                   //void (*SetStopMode)(uint8_t, motorStopMode_t);
  L6208_GetStopMode,                   //motorStopMode_t (*GetStopMode)(uint8_t);
  L6208_SetDecayMode,                  //void (*SetDecayMode)(uint8_t, motorDecayMode_t);
  L6208_GetDecayMode,                  //motorDecayMode_t (*GetDecayMode)(uint8_t);
  L6208_GetStepMode,                   //motorStepMode_t (*GetStepMode)(uint8_t);
  L6208_GetDirection,                  //motorDir_t (*GetDirection)(uint8_t);
  0,                                   //void (*ExitDeviceFromReset)(uint8_t);
  L6208_SetTorque,                     //void (*SetTorque)(uint8_t, motorTorqueMode_t, uint8_t);
  L6208_GetTorque,                     //uint8_t (*GetTorque)(uint8_t, motorTorqueMode_t);
  0,                                   //void (*SetRefFreq)(uint8_t, uint32_t);
  0,                                   //uint32_t (*GetRefFreq)(uint8_t);
  0,                                   //void (*SetRefDc)(uint8_t, uint8_t);
  0,                                   //uint8_t (*GetRefDc)(uint8_t);
  L6208_SetNbDevices,                  //bool (*SetNbDevices)(uint8_t);
  0,                                   //bool (*SetAnalogValue)(uint8_t, uint32_t, float);
  0                                    //float (*GetAnalogValue)(uint8_t, uint32_t);               
};

/**
  * @}
  */ 

/** @defgroup L6208_library_Functions L6208 library Functions
  * @{
  */   

/******************************************************//**
 * @brief Return motor handle (pointer to the L6208 motor driver structure)
 * @retval Pointer to the motorDrv_t structure
 **********************************************************/
motorDrv_t* L6208_GetMotorHandle(void)
{
  return (&l6208Drv);
}

/******************************************************//**
 * @brief Start the L6208 library
 * @param[in] pInit pointer to the initialization data
 * @retval None
 **********************************************************/
void L6208_Init(void* pInit)
{
  
  l6208DriverInstance++;
    
  /* Initialise the GPIOs */
  L6208_Board_GpioInit();
  
  if (pInit == NULL)
        { 
    /* Set context variables to the predefined values from l6208_target_config.h */
    /* Set GPIO according to these values */
    L6208_SetDeviceParamsToPredefinedValues();
        }
        else
        { 
    L6208_SetDeviceParamsToGivenValues((l6208_Init_t*) pInit);
        }
  
  /* Initialise the PWMs */
  L6208_Board_VrefPwmInit(BRIDGE_A, devicePrm.vrefPwmFreq);
  L6208_Board_VrefPwmInit(BRIDGE_B, devicePrm.vrefPwmFreq);

  /* Initialise the tick */
  L6208_Board_TickInit();
  
  /* Reset L6208 */
  L6208_ResetDevice();
  
  /* Align motor mechanical position to driver position */
  L6208_Board_VrefPwmStart(BRIDGE_A, devicePrm.vrefPwmFreq);
  L6208_Board_VrefPwmStart(BRIDGE_B, devicePrm.vrefPwmFreq);
  L6208_Enable(0);
      }

/******************************************************//**
 * @brief Read id
 * @retval Id of the l6208 Driver Instance
 **********************************************************/
uint16_t L6208_ReadId(void)
      { 
  return(l6208DriverInstance);
      }

/******************************************************//**
 * @brief  Attaches a user callback to the error Handler.
 * The call back will be then called each time the library 
 * detects an error
 * @param[in] callback Name of the callback to attach 
 * to the error Hanlder
 * @retval None
 **********************************************************/
void L6208_AttachErrorHandler(void (*callback)(uint16_t error))
      { 
  errorHandlerCallback = (void (*)(uint16_t error)) callback;
}

/******************************************************//**
 * @brief  Attach a user callback to the flag Interrupt
 * The call back will be then called each time the EN 
 * pin will be pulled down due to the occurrence of 
 * OCD or OVT 
 * @param[in] callback Name of the callback to attach 
 * to the Flag Interrupt
 * @retval None
 **********************************************************/
void L6208_AttachFlagInterrupt(void (*callback)(void))
{ 
  flagInterruptCallback = (void (*)())callback;
}

/******************************************************//**
 * @brief Check if L6208 has a fault by reading EN pin position.
 * @retval One if L6208 has EN pin down, otherwise zero
 **********************************************************/
uint8_t L6208_CheckStatusHw(void)
{
	if(!L6208_Board_FLAG_PIN_GetState())
  {
    return 0x01;
  }
  else
  {
    return 0x00;
  }
}

/******************************************************//**
 * @brief Disable the power bridges (leave the output bridges HiZ)
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval None
 **********************************************************/
void L6208_Disable(uint8_t deviceId)
        {
  L6208_Board_Disable();
  L6208_ClearSysFlag(EN_A_set);
}

/******************************************************//**
 * @brief Error handler which calls the user callback (if defined)
 * @param[in] error Number of the error
 * @retval None
 **********************************************************/
void L6208_ErrorHandler(uint16_t error)
          { 
  if (errorHandlerCallback != 0)
  {
    errorHandlerCallback(error);
          }
          else
          {
    while(1)
    {
      /* Infinite loop */
          }
        }
      }

/******************************************************//**
 * @brief Enable the power bridges
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval None
 **********************************************************/
void L6208_Enable(uint8_t deviceId)
      { 
  L6208_Board_Enable();
  L6208_SetSysFlag(EN_A_set);
      }

/******************************************************//**
 * @brief Handler of the flag interrupt which calls the user callback (if defined)
 * @retval None
 **********************************************************/
void L6208_FlagInterruptHandler(void)
        {  
  if (flagInterruptCallback != 0)
  {
    /* Set isr flag */
    isrFlag = TRUE;
        
    flagInterruptCallback();

    /* Reset isr flag */
    isrFlag = FALSE;   
  }
        }

/******************************************************//**
 * @brief Get the stepper acceleration rate
 * in step/s^2 for full, half and wave modes
 * in microsteps/s^2 for microstep modes
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval the stepper acceleration rate in step/s^2 or microstep/s^2
 * @note
 **********************************************************/
uint16_t L6208_GetAcceleration(uint8_t deviceId)
        {
    return devicePrm.accelerationSps2;
        }

/******************************************************//**
 * @brief Get the current speed
 * in step/s for full, half and wave modes
 * in microsteps/s for microstep modes
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval return the current speed in step/s or microstep/s
 * @note
 **********************************************************/
uint16_t L6208_GetCurrentSpeed(uint8_t deviceId)
        { 
  uint64_t tmp64 = (uint64_t) devicePrm.speedSpt * L6208_Board_TickGetFreq();
  
  devicePrm.speedSps = (uint16_t)(tmp64 >> 23);
  if (devicePrm.speedSps & 0x1)
          { 
    devicePrm.speedSps = (devicePrm.speedSps >> 1) + 1;
          }
          else
          {
    devicePrm.speedSps = devicePrm.speedSps >> 1;
          }
  return devicePrm.speedSps;
        }
        
/******************************************************//**
 * @brief Get the motor decay mode
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval decay mode
 **********************************************************/
motorDecayMode_t L6208_GetDecayMode(uint8_t deviceId)
      {
  if (L6208_IsSysFlag(fastdecaymode)) return (FAST_DECAY);
  else return (SLOW_DECAY);
    }

/******************************************************//**
 * @brief Get the stepper deceleration rate
 * in step/s^2 for full, half and wave modes
 * in microsteps/s^2 for microstep modes
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval the stepper deceleration rate in step/s^2 or microstep/s^2
 * @note
 **********************************************************/
uint16_t L6208_GetDeceleration(uint8_t deviceId)
          {
    return devicePrm.decelerationSps2;
        }

/******************************************************//**
 * @brief Get the motor current direction
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval direction
 **********************************************************/
motorDir_t L6208_GetDirection(uint8_t deviceId)
        { 
  if (L6208_IsSysFlag(forward))
          {
    return FORWARD;
          }
          else
          {
    return BACKWARD;
          }
        }

/******************************************************//**
 * @brief Return the FW version.
 * @retval FW version
 **********************************************************/
uint32_t L6208_GetFwVersion(void)
        { 
  return L6208_FW_VERSION;
        }

/******************************************************//**
 * @brief Get the mark position (32b signed) 
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval mark position
 **********************************************************/
int32_t L6208_GetMark(uint8_t deviceId)
{
  return devicePrm.markPos;
      }

/******************************************************//**
 * @brief Get the max speed
 * in step/s for full, half and wave modes
 * in microsteps/s for microstep modes
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval return the max speed in step/s or microstep/s
 * @note
 **********************************************************/
uint16_t L6208_GetMaxSpeed(uint8_t deviceId)
      { 
  return devicePrm.maxSpeedSps;
      }

/******************************************************//**
 * @brief Get the min speed
 * in step/s for full, half and wave modes
 * in microsteps/s for microstep modes
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval return the min speed in step/s or microstep/s
 * @note
 **********************************************************/
uint16_t L6208_GetMinSpeed(uint8_t deviceId)
{
  return devicePrm.minSpeedSps;
    }

/******************************************************//**
 * @brief Get the stepper state machine index
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval one of the stepper state machine index in the motorState_t enum
 **********************************************************/
motorState_t L6208_GetMotionState(uint8_t deviceId)
    {
  // gets the new stepper state machine index
  return devicePrm.motionState;    
}

/******************************************************//**
 * @brief Get the current position (32b signed) 
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval current absoulte position
 **********************************************************/
int32_t L6208_GetPosition(uint8_t deviceId)
      { 
  return devicePrm.absolutePos;
      }

/******************************************************//**
 * @brief Get the motor step mode
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval step mode
 **********************************************************/
motorStepMode_t L6208_GetStepMode(uint8_t deviceId)
      { 
  return devicePrm.stepMode;
      }

/******************************************************//**
 * @brief Get the selected stop mode
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval the selected stop mode
 **********************************************************/
motorStopMode_t L6208_GetStopMode(uint8_t deviceId)
      { 
  if (L6208_IsSysFlag(HiZstop) == FALSE)
        { 
      return (HOLD_MODE);
        }
        else
        {
      return (HIZ_MODE);
  }
}

/******************************************************//**
 * @brief Get the torque of the specified device
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] torqueMode torque mode
 * @retval the torqueValue in % (from 0 to 100)
 * @note
 **********************************************************/
uint8_t L6208_GetTorque(uint8_t deviceId, motorTorqueMode_t torqueMode)
{
  uint8_t torqueValue = 0;
  switch(torqueMode)
  {
    case ACC_TORQUE:
      torqueValue = devicePrm.accelTorque;
      break;
    case DEC_TORQUE:
      torqueValue = devicePrm.decelTorque;
      break;
    case RUN_TORQUE:
      torqueValue = devicePrm.runTorque;
      break;
    case HOLD_TORQUE:
      torqueValue = devicePrm.holdTorque;
      break;
    case CURRENT_TORQUE:
      torqueValue = devicePrm.curTorqueScaler;
      break;
    default:
      break;
  }
  return torqueValue;
}

/******************************************************//**
 * @brief Go to the home position
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval None
 **********************************************************/
void L6208_GoHome(uint8_t deviceId)
{
  L6208_GoTo(deviceId, 0);
}

/******************************************************//**
 * @brief Go to the Mark position
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval None
 **********************************************************/
void L6208_GoMark(uint8_t deviceId)
{
  L6208_GoTo(deviceId, devicePrm.markPos);
}

/******************************************************//**
 * @brief Move the motor to the absolute position using the shortest path
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] abs_pos 32 bit signed value position
 * @retval None
 * @note The position is at the resolution corresponding to the
 * selected step mode.
 * STEP_MODE_FULL or STEP_MODE_WAVE : step
 * STEP_MODE_HALF                     : 1/2 step
 * STEP_MODE_1_4              : 1/4 step
 * STEP_MODE_1_8              : 1/8 step
 * STEP_MODE_1_16             : 1/16 step 
 **********************************************************/
void L6208_GoTo(uint8_t deviceId, int32_t abs_pos)
{
  uint32_t steps = 0;
  
  if(L6208_IsSysFlag(running))
  {
    L6208_HardStop(0);
  }
  
  if (abs_pos > devicePrm.absolutePos)
  {
    steps = abs_pos - devicePrm.absolutePos;
    if (steps < (L6208_POSITION_RANGE>>1))
    {
      L6208_Move(0, FORWARD, steps);
}
    else
  {
      L6208_Move(0, BACKWARD, (L6208_POSITION_RANGE - steps));
  }
}
  else
{
    steps = devicePrm.absolutePos - abs_pos;
    if (steps < (L6208_POSITION_RANGE>>1))
  {
      L6208_Move(0, BACKWARD, steps);
  }
	else 
  {
      L6208_Move(0, FORWARD, (L6208_POSITION_RANGE - steps));
  }
}
}

/******************************************************//**
 * @brief Move the motor to the absolute position
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] direction FORWARD or BACKWARD
 * @param[in] abs_pos 32 bit signed value position
 * @retval None
 * @note The position is at the resolution corresponding to the
 * selected step mode.
 * STEP_MODE_FULL or STEP_MODE_WAVE : step
 * STEP_MODE_HALF                     : 1/2 step
 * STEP_MODE_1_4              : 1/4 step
 * STEP_MODE_1_8              : 1/8 step
 * STEP_MODE_1_16             : 1/16 step 
 **********************************************************/
void L6208_GoToDir(uint8_t deviceId, motorDir_t direction, int32_t abs_pos)
{ 
  uint32_t steps = 0;
  
  if(L6208_IsSysFlag(running))
  {
    L6208_HardStop(0);
  }
  
  if (direction != BACKWARD)
  {
    if (abs_pos > devicePrm.absolutePos)
    {
      steps = abs_pos - devicePrm.absolutePos;
  }
  else
  {
      steps = L6208_POSITION_RANGE + (abs_pos - devicePrm.absolutePos);
  }
}
  else
{
    if (abs_pos > devicePrm.absolutePos)
    {
      steps = L6208_POSITION_RANGE + (devicePrm.absolutePos - abs_pos);
}
    else
{
      steps = devicePrm.absolutePos - abs_pos;
    }
  }
  L6208_Move(0, direction, steps);
}

/******************************************************//**
 * @brief Immediately stop the motor and disables the power bridges
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval None
 **********************************************************/
void L6208_HardHiZ(uint8_t deviceId)
{ 
  /* Disables power stage */
  L6208_Disable(0);

  /* Sets inactive state */
  L6208_SetMotionState(INACTIVE);
  
  /* Clears the running motor and the position */
  L6208_ClearSysFlag(running);
 
  /* Disables PWMs */
  L6208_Board_VrefPwmStop(BRIDGE_A);
  L6208_Board_VrefPwmStop(BRIDGE_B);
  
  /* Disables tick timer */
  L6208_Board_TickStop();
}

/******************************************************//**
 * @brief Immediately stop the motor and keeps holding torque
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval None
 **********************************************************/
void L6208_HardStop(uint8_t deviceId) 
{
  /* Sets inactive state */
  L6208_SetMotionState(INACTIVE);
  
  /* Clears the running motor and the position */
  L6208_ClearSysFlag(running);
  L6208_VectorCalc(devicePrm.holdTorque);
    
  /* Disables tick timer */
  L6208_Board_TickStop();
}

/******************************************************//**
 * @brief Move the motor by the specified number of steps
 * in the specified direction
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] direction FORWARD or BACKWARD
 * @param[in] stepCount 32 bit unsigned step count
 * @retval None
 * @note The step count resolution is corresponding to the
 * selected step mode.
 * STEP_MODE_FULL or STEP_MODE_WAVE : step
 * STEP_MODE_HALF                   : 1/2 step
 * STEP_MODE_1_4                    : 1/4 step
 * STEP_MODE_1_8                    : 1/8 step
 * STEP_MODE_1_16                   : 1/16 step 
 **********************************************************/
void L6208_Move(uint8_t deviceId, motorDir_t direction, uint32_t stepCount)
{
  if(L6208_IsSysFlag(running))
  {
    L6208_HardStop(0);
  }
  
  /* clear the velocity driving mode flag */
  L6208_ClearSysFlag(velocitymode);
  
  /* Set the indexing driving mode flag */
  /* and the user command executing flag */
  L6208_SetSysFlag(positionmode);
 
  /* store relative number of steps to move */
  devicePrm.positionTarget = stepCount;
  
  L6208_SetDirection(0, direction); 
  
  /* Motor activation */
  L6208_StartMovement(); 
}

/******************************************************//**
 * @brief  Release the L6208 reset (Reset pin set to high level)
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval None
 **********************************************************/
void L6208_ReleaseReset(uint8_t deviceId)
  {
  L6208_Board_ReleaseReset(); 
}

/******************************************************//**
 * @brief Reset the L6208 (Reset pin set to low level)
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval None
 **********************************************************/
void L6208_Reset(uint8_t deviceId)
  {
  L6208_Board_Reset();
  }

/******************************************************//**
 * @brief  Reset the device with current step mode, resets current speed,
 * positions and microstep variables.
 * @retval None
 **********************************************************/
void L6208_ResetDevice(void)
  {
  L6208_SetStepMode(0, L6208_GetStepMode(0));
}

/******************************************************//**
 * @brief Run the motor in the specified direction
 * according to the speed profile defined by the minimum speed,
 * maximum speed, and acceleration parameters. 
 * The device accelerates from the minimum speed up to the maximum
 * speed by using the device acceleration.
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] direction FORWARD or BACKWARD
 * @retval None
 **********************************************************/
void L6208_Run(uint8_t deviceId, motorDir_t direction)
{
  if(L6208_IsSysFlag(running))
  {
    L6208_HardStop(0);
  }
  L6208_SetDirection(0, direction);
  /* Clear the indexing driving mode flag */
  L6208_ClearSysFlag(positionmode);
  /* Set the velocity driving mode flag */
  L6208_SetSysFlag(velocitymode);
  /* Motor activation */
  L6208_StartMovement(); 
}

/******************************************************//**
 * @brief Set the stepper acceleration rate
 * in step/s^2 and step/tick^2 for full, half and wave modes
 * in microsteps/s^2 and microsteps/tick^2 for microstep modes
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] newAcc new acceleration rate in step/s^2 or microstep/s^2
 * @retval TRUE
 * @note
 **********************************************************/
bool L6208_SetAcceleration(uint8_t deviceId, uint16_t newAcc)
{
  uint16_t newAccSpt2 = L6208_ConvertAcceDecelRateValue(newAcc);
  if (newAccSpt2)
  {
    devicePrm.accelerationSps2 = newAcc;
    devicePrm.accelerationSpt2 = newAccSpt2; 
  }
  else
  {
    L6208_ErrorHandler(L6208_ERROR_SET_ACCELERATION);
  }
  return TRUE;
}

/******************************************************//**
 * @brief Select the motor decay mode
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] decayMode (SLOW_DECAY or FAST_DECAY)
 * @retval None
 **********************************************************/
void L6208_SetDecayMode(uint8_t deviceId, motorDecayMode_t decayMode)
{
  if ((decayMode & L6208_FAST_DECAY_MODE_MASK) == L6208_FAST_DECAY_MODE_MASK)
  {
    L6208_Board_CONTROL_PIN_Set();
    L6208_SetSysFlag(fastdecaymode);
  }
  else 
  {
    L6208_Board_CONTROL_PIN_Reset();
    L6208_ClearSysFlag(fastdecaymode);
  }
}

/******************************************************//**
 * @brief Set the stepper deceleration rate
 * in step/s^2 and step/tick^2 for full, half and wave modes
 * in microsteps/s^2 and microsteps/tick^2 for microstep modes
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] newDec new deceleration rate in step/s^2 or microstep/s^2
 * @retval TRUE
 * @note
 **********************************************************/
bool L6208_SetDeceleration(uint8_t deviceId, uint16_t newDec)
{
  uint16_t newDecSpt2 = L6208_ConvertAcceDecelRateValue(newDec);
  if (newDecSpt2)
  {
    devicePrm.decelerationSps2 = newDec;
    devicePrm.decelerationSpt2 = newDecSpt2;
  }
  else
  {
    L6208_ErrorHandler(L6208_ERROR_SET_DECELERATION);
  }
  return TRUE;
}

/******************************************************//**
 * @brief Specify the direction
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] dir FORWARD or BACKWARD
 * @note In velocity mode a direction change forces the device to stop and 
 * then run in the new direction. In position mode, if the device is 
 * running, a direction change will generate an error.
 * @retval None
 **********************************************************/
void L6208_SetDirection(uint8_t deviceId, motorDir_t dir)
{
  L6208_ClearSysFlag(dir2change);
  if (dir == FORWARD)
  {
    if (!L6208_IsSysFlag(forward))
    {
      if (L6208_IsSysFlag(running))
      {
        /* motor is running */
        if (L6208_IsSysFlag(positionmode))
        {
          L6208_ErrorHandler(L6208_ERROR_SET_DIRECTION);
        }
        else
        {
          /* set the rotation direction to change flag */
          L6208_SetSysFlag(dir2change);
        }
      }
      else /* the motor is stopped, cw direction selected */
      {
        L6208_SetSysFlag(forward);
        L6208_Board_DIR_PIN_Set();
      }
    }
  }
  else
  {
    if (L6208_IsSysFlag(forward))
   {
      if (L6208_IsSysFlag(running))
      {
        /* motor is running */
        if (L6208_IsSysFlag(positionmode))
        {
          L6208_ErrorHandler(L6208_ERROR_SET_DIRECTION);
        }
        else
        {
          /* set the rotation direction to change flag */
          L6208_SetSysFlag(dir2change);
        }
      }
      else /* the motor is stopped, ccw direction selected */
      {
        L6208_ClearSysFlag(forward);
        L6208_Board_DIR_PIN_Reset();
      }
    }
  }
  if(L6208_IsSysFlag(dir2change))
  {
    L6208_VectorCalc(devicePrm.decelTorque);     
    L6208_SetMotionState(DECELERATINGTOSTOP);  
  }
}

/******************************************************//**
 * @brief Set home position 
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] homePos new home position
 * @retval None
 **********************************************************/
void L6208_SetHome(uint8_t deviceId, int32_t homePos)
{
  if (!L6208_IsSysFlag(running))
  {
      devicePrm.absolutePos -= homePos;
  }
  else
  {
      L6208_ErrorHandler(L6208_ERROR_SET_HOME);
  }
}

/******************************************************//**
 * @brief Set mark position 
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] markPos new mark position
 * @retval None
 **********************************************************/
void L6208_SetMark(uint8_t deviceId, int32_t markPos)
{
  devicePrm.markPos = markPos;
}

/******************************************************//**
 * @brief Set the user selected maximum speed 
 * in step/s and step/tick for full, half and wave modes
 * in microsteps/s and microsteps/tick for microstep modes
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] newSpeed speed value (step/s or microstep/s)
 * @retval TRUE
 * @note One microstep is 1/16 step
 **********************************************************/
bool L6208_SetMaxSpeed(uint8_t deviceId, uint16_t newSpeed)
{
  if (L6208_SetSpeed(newSpeed, &devicePrm.maxSpeedSpt))
  {
    devicePrm.maxSpeedSps = newSpeed;
  }
  else
  {
    L6208_ErrorHandler(L6208_ERROR_SET_MAX_SPEED);
  }
  return TRUE;
}

/******************************************************//**
 * @brief Set the user selected minimum speed 
 * in step/s and step/tick for full, half and wave modes
 * in microsteps/s and microsteps/tick for microstep modes
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] newSpeed speed value (step/s or microstep/s)
 * @retval TRUE
 * @note One microstep is 1/16 step
 **********************************************************/
bool L6208_SetMinSpeed(uint8_t deviceId, uint16_t newSpeed)
{
  if (L6208_SetSpeed(newSpeed, &devicePrm.minSpeedSpt))
  {
    devicePrm.minSpeedSps = newSpeed;
  }
  else
  {
    L6208_ErrorHandler(L6208_ERROR_SET_MIN_SPEED);
  }
  return TRUE;
}

/******************************************************//**
 * @brief  Sets the number of devices to be used 
 * @param[in] nbDevices (from 1 to MAX_NUMBER_OF_DEVICES)
 * @retval TRUE if successfull, FALSE if failure, attempt to set a number of 
 * devices greater than MAX_NUMBER_OF_DEVICES
 **********************************************************/
bool L6208_SetNbDevices(uint8_t nbDevices)
{
  if (nbDevices <= MAX_NUMBER_OF_DEVICES)
  {
    return TRUE;
  }
  else
  {
    return FALSE;
  }
}

/******************************************************//**
 * @brief Set the step mode
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] stepMode
 * @retval true if the command is successfully executed, else false
 * @note Every time the step mode is changed, the step state machine is reset
 **********************************************************/
bool L6208_SetStepMode(uint8_t deviceId, motorStepMode_t stepMode)
{
  devicePrm.stepMode = stepMode;
  L6208_ClearSysFlag(fullstep | halfstep | microstep | wavestep);
  switch (stepMode)
  {
    case STEP_MODE_HALF:
      /* Set the Half/Full pin low and Reset and the set the Half/Full pin high*/
      L6208_Board_HALF_FULL_PIN_Reset(); 
      L6208_Board_Reset();
      L6208_Board_HALF_FULL_PIN_Set();
      /* Set system flag */
      L6208_SetSysFlag(halfstep);
      break;
    case STEP_MODE_FULL:
       /* Set the Half/Full pin low and Reset */
      L6208_Board_HALF_FULL_PIN_Reset(); 
      L6208_Board_Reset();
      /* Set system flag */
      L6208_SetSysFlag(fullstep);
      break;
    case STEP_MODE_WAVE:
      /* Set the Half/Full pin low and Reset and the set the Half/Full pin high*/
      L6208_Board_CLOCK_PIN_Reset();
      L6208_Board_HALF_FULL_PIN_Reset();
      L6208_Board_Reset();
      L6208_Board_CLOCK_PIN_Set();
      L6208_Board_HALF_FULL_PIN_Set();
      L6208_Board_Delay(2);
      L6208_Board_CLOCK_PIN_Reset();
      L6208_Board_Delay(2);
      L6208_Board_HALF_FULL_PIN_Reset();
      /* Set system flag */
      L6208_SetSysFlag(wavestep);
      break;
      case STEP_MODE_1_4:
      /* Set the Half/Full pin low and Reset */
      L6208_Board_HALF_FULL_PIN_Reset();
      L6208_Board_Reset();
      /* Set system flag */
      L6208_SetSysFlag(microstep);
      devicePrm.uStepInc = 4;
      break;
    case STEP_MODE_1_8:
      /* Set the Half/Full pin low and Reset */
      L6208_Board_HALF_FULL_PIN_Reset();
      L6208_Board_Reset();
      /* Set system flag */
      L6208_SetSysFlag(microstep);
      devicePrm.uStepInc = 2;
      break;
      case STEP_MODE_1_16:
      /* Set the Half/Full pin low and Reset */
      L6208_Board_HALF_FULL_PIN_Reset();
      L6208_Board_Reset();
      /* Set system flag */
      L6208_SetSysFlag(microstep);
      devicePrm.uStepInc = 1;
      break;
    default:
      return FALSE;
    }
  L6208_Board_Delay(2);
  L6208_Board_ReleaseReset();
  L6208_ResetSteps();
  return TRUE;
}

/******************************************************//**
 * @brief Select the mode to stop the motor. When the motor
 * is stopped, if autoHiZ is TRUE, the power bridges are disabled
 * if autoHiZ is FALSE, the power bridges are kept enabled.
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] stopMode HOLD_MODE to let power bridge enabled
 * @retval None
 **********************************************************/
void L6208_SetStopMode(uint8_t deviceId, motorStopMode_t stopMode)
{
  if (stopMode == HOLD_MODE)
  {
    L6208_ClearSysFlag(HiZstop);
  }
  else
  {
    L6208_SetSysFlag(HiZstop);
  }
}

/******************************************************//**
 * @brief Set the torque of the specified device
 * @param[in] deviceId Unused parameter
 * @param[in] torqueMode Torque mode as specified in enum motorTorqueMode_t
 * @param[in] torqueValue in % (from 0 to 100)
 * @retval None
 * @note
 **********************************************************/
void L6208_SetTorque(uint8_t deviceId, motorTorqueMode_t torqueMode, uint8_t torqueValue)
{
  if (torqueValue>100) torqueValue = 100;
  switch(torqueMode)
  {
    case ACC_TORQUE:
      devicePrm.accelTorque = torqueValue;
      break;
    case DEC_TORQUE:
      devicePrm.decelTorque = torqueValue;
      break;
    case RUN_TORQUE:
      devicePrm.runTorque = torqueValue;
      break;
    case HOLD_TORQUE:
      devicePrm.holdTorque = torqueValue;
      if (devicePrm.motionState != INACTIVE)
      {
        break;
      }
      L6208_VectorCalc(devicePrm.holdTorque);
      break;
    case CURRENT_TORQUE:
      devicePrm.curTorqueScaler = torqueValue;
      L6208_SetMicrostepSample2Scale(L6208_USTEPS_PER_QUARTER_PERIOD);
    default:
      break; //ignore error
  }
}

/******************************************************//**
 * @brief  Stop the motor by using the device deceleration and set deceleration torque
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval true if the command is successfully executed, else false
 * @note .
 **********************************************************/
bool L6208_SoftStop(uint8_t deviceId)
{
  L6208_VectorCalc(devicePrm.decelTorque);
  L6208_SetMotionState(DECELERATINGTOSTOP);
  return TRUE;
}

/******************************************************//**
 * @brief  Handle the device state machine at each tick timer pulse end.
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval None
 **********************************************************/
void L6208_TickHandler(uint8_t deviceId)
{
  uint32_t locMaxSpeedSpt = devicePrm.maxSpeedSpt;
  uint32_t locMinSpeedSpt = devicePrm.minSpeedSpt;

  /* Update state, target speed, acceleration and deceleration rates */
  L6208_Board_CLOCK_PIN_Reset();
    
  switch(L6208_GetMotionState(0))
  {
    /* ============ Velocity control mode states ======================== */
    case ACCELERATING:
      /* velocity mode: acceleration phase */
      /* Increase Speed and update position */
      L6208_DoAccel();
      if(locMaxSpeedSpt < devicePrm.speedSpt)
      {
        /*Target speed reached */
        devicePrm.speedSpt = locMaxSpeedSpt;
        L6208_VectorCalc(devicePrm.runTorque); 
        L6208_SetMotionState(STEADY);
      }
      break;
    case STEADY:  
      /* velocity mode: constant speed phase */
      /* Update position */
      L6208_DoRun();  
      if(locMaxSpeedSpt != devicePrm.speedSpt)
      { 
        /* targeted speed  has changed */
        if(locMaxSpeedSpt< devicePrm.speedSpt)
        { 
          /* Slow down the motor */
          L6208_VectorCalc(devicePrm.decelTorque);     
          L6208_SetMotionState(DECELERATING); 
        }
        else
        {
          /* speed up the motor */
          L6208_VectorCalc(devicePrm.accelTorque);     
          L6208_SetMotionState(ACCELERATING);
        }
      }
      break;
    case DECELERATING:  
      /* velocity mode: running motor deceleration phase */
      /* Decrease Speed and update position */
      L6208_DoDecel();  
      if(locMaxSpeedSpt > devicePrm.speedSpt)
      {
        /*Target speed reached but motor has still to be run*/
        devicePrm.speedSpt = locMaxSpeedSpt;
        L6208_VectorCalc(devicePrm.runTorque);   
        L6208_SetMotionState(STEADY);  
      }
      break;
    case DECELERATINGTOSTOP: 
      /* velocity mode: decelerate to stopped phase */
      /* Decrease current speed */
      L6208_DoDecel();
      if(devicePrm.speedSpt == locMinSpeedSpt)
      {
        if (L6208_IsSysFlag(dir2change))
        {
          L6208_ClearSysFlag(running);
          /* Change direction */
          if (L6208_IsSysFlag(forward))
          {
            /* switch to reverse rotation */
            L6208_SetDirection(0, BACKWARD);
          }
          else
          {
            /* switch to forward rotation */
            L6208_SetDirection(0, FORWARD);
          }
          L6208_SetSysFlag(running);
          L6208_SetMotionState(ACCELERATING);
          /* Set VRefA and VRefB to the selected acceleration torque */
          L6208_VectorCalc(devicePrm.accelTorque);
        }
        else
        {
          if (L6208_IsSysFlag(HiZstop))
          {
            L6208_HardHiZ(0);
          }
          else
          {
            L6208_HardStop(0);
          }
        }
      }
      break;

    /* ============ Position (indexed) control mode states ======================== */
  
    case INDEX_ACCEL:
      /*  position mode: acceleration state*/
      
      /* Increase Speed and update position */
      L6208_DoAccel();  

      if(devicePrm.positionTarget1 <= devicePrm.step)
      {
        /* End of acceleration phase */
        L6208_VectorCalc(devicePrm.runTorque); 
        L6208_SetMotionState(INDEX_RUN);    
      }
      break;
  
      case INDEX_RUN:   
        /* position mode: constant speed phase */
        
        /* Update position */
        L6208_DoRun();  

        if(devicePrm.positionTarget2 <= devicePrm.step)
        {
          /* reach position targeted for constant speed */
          L6208_VectorCalc(devicePrm.decelTorque);   
          L6208_SetMotionState(INDEX_DECEL); 
        }
        break;

      case INDEX_DECEL: 
        /* position mode: deceleration phase */
        
        /* Decrease Speed and update position */
        L6208_DoDecel();  

        if(devicePrm.positionTarget3 <= devicePrm.step)
        {
          /* reach position targeted for deceleration phase */
          /* the motor terminated its run */
          /* the torque will be the deceleration one */
          devicePrm.step = devicePrm.positionTarget3;
          L6208_SetMotionState(INDEX_DWELL);   
        }
        break;

      case INDEX_DWELL: 
        /* position mode: dwelling state */
        if(devicePrm.dwellCounter > 0)
        {
          /* decrease the dwelling wait tick counter */
          devicePrm.dwellCounter--;
        }
        if(devicePrm.dwellCounter == 0)
        {
          /* dwelling wait time is elapsed */
          /* so stop the motor */
          if (L6208_IsSysFlag(HiZstop))
          {
            L6208_HardHiZ(0);
          }
          else
          {
            L6208_HardStop(0);
          }
        }
        break;

    /* ============ stopped state ======================== */
    case INACTIVE:
    {
      if(L6208_IsSysFlag(running))
      {
        /* clear the user move command executing  */
        /* and the motor running flags */
        L6208_ClearSysFlag(running);
      }
      break;
    }
    default:
      break;
  } /* switch(L6208_GetMotionState(0)) */
  if(L6208_GetMotionState(0) != INACTIVE)
  {
    if (L6208_IsSysFlag(microstep))
    {
      /* Microstep handling */     
      switch(devicePrm.uStepInc)
      {
        default:
        case 1:  
          /* 1 microstep increment */
          devicePrm.lsbTicks = (uint8_t)(devicePrm.ticks>>16);
          break;

        case 2:  
          /* 2 microsteps increment */           
          devicePrm.lsbTicks = (uint8_t)(devicePrm.ticks>>17);
          break;

        case 4:  
          /* 4 microsteps increment */
          devicePrm.lsbTicks = (uint8_t)(devicePrm.ticks>>18);
          break;
      }
      devicePrm.lsbTicks &= 0x01;
      if(devicePrm.lsbOldUSteppingTicks != devicePrm.lsbTicks)
      {
        /*  waveform sample to update */
        devicePrm.lsbOldUSteppingTicks = devicePrm.lsbTicks;
        devicePrm.step++;
        if (L6208_IsSysFlag(forward))
        {
          /* the motor is going forward */
          devicePrm.absolutePos++;
          /* Reset the absolute motor position in step/microsteps */
          /* Get next microstep sample */
          devicePrm.uStepSample += devicePrm.uStepInc;  
          if(devicePrm.uStepSample > 31)
          {
            devicePrm.uStepSample = 0;
          }
        }
        else
        {
         /* the motor is going backward */
          devicePrm.absolutePos--;
          if(devicePrm.uStepSample >= devicePrm.uStepInc)
          {
            /* Get previous microstep sample */
            devicePrm.uStepSample -= devicePrm.uStepInc; 
          }
          else
          {
            devicePrm.uStepSample = 32 - devicePrm.uStepInc;
          }
        } 
        /* set the PWM to update VRefs */
        L6208_Board_VrefPwmSetDutyCycle(BRIDGE_A, pMicroTable2[devicePrm.uStepSample], FALSE);
        L6208_Board_VrefPwmSetDutyCycle(BRIDGE_B, microTable1[devicePrm.uStepSample], FALSE);
        if(devicePrm.uStepsample2update > 0)
        {
          /*  the waveform samples table has been recalculated 
          so update the waveform scanning table */
          L6208_UpdateScanWaveformTable();
          devicePrm.uStepsample2update = 0;
        }
      }
      /* Microstep: use the bit4 toggling as step clock */
      /* this bit is used because there are 16 microstep samples per quarter period */
      devicePrm.lsbTicks = (uint8_t)((devicePrm.uStepSample>>4) & 0x01);
      if(devicePrm.lsbOldTicks != devicePrm.lsbTicks)
      {
        /* the selected bit status changed ==> get the next motor step
        save the current masked motor tick position for step setting scope ... */
        devicePrm.lsbOldTicks = devicePrm.lsbTicks;
        L6208_Board_CLOCK_PIN_Set();
      }
    }
    else
    {
      /* Full and half step handling code */ 
      if(!L6208_IsSysFlag(halfstep))
      { 
        /* Full step: use the bit 16 toggling as step clock */
        devicePrm.lsbTicks = (uint8_t)((devicePrm.ticks>>16) & 0x00000001);
      }
      else
      {
        /* half step: use the bit 15 toggling as step clock */
        devicePrm.lsbTicks = (uint8_t)((devicePrm.ticks>>15) & 0x00000001);
      }
      if(devicePrm.lsbOldTicks != devicePrm.lsbTicks)
      {
        /* the selected bit status changed ==> get the next motor step */
        devicePrm.step++;
        if(L6208_IsSysFlag(forward))
        {
          /* the motor is going forward */
          devicePrm.absolutePos++;
        }
        else
        {
          /* the motor is going backward */
          devicePrm.absolutePos--;          
        }
        /* save the current masked motor tick position for step setting scope ... */
        devicePrm.lsbOldTicks = devicePrm.lsbTicks;
        L6208_Board_CLOCK_PIN_Set();
      }
    }
  }
  L6208_UstepWaveformHandling();
}

/******************************************************//**
 * @brief Get the frequency of VREFA and VREFB PWM
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval the frequency of VREFA and VREFB PWM in Hz
 * @note
 **********************************************************/
uint32_t L6208_VrefPwmGetFreq(uint8_t deviceId)
  {
  return devicePrm.vrefPwmFreq;
}

/******************************************************//**
 * @brief Set the frequency of the VREFA and VREFB PWM
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @param[in] newFreq in Hz
 * @retval None
 * @note
 **********************************************************/
void L6208_VrefPwmSetFreq(uint8_t deviceId, uint32_t newFreq)
{
  if (!L6208_Board_VrefPwmFreqCheck(newFreq)) L6208_ErrorHandler(L6208_ERROR_SET_PWM);
  devicePrm.vrefPwmFreq = newFreq;
  /* Re-Initialise the PWMs -----------------------------------------------------*/
  L6208_Board_VrefPwmInit(BRIDGE_A, devicePrm.vrefPwmFreq);
  L6208_Board_VrefPwmInit(BRIDGE_B, devicePrm.vrefPwmFreq);
  /* Recompute the waveform samples according to the new PWM frequency */
  L6208_ScaleWaveformTable();
  /* Update the waveform scanning table */
  L6208_UpdateScanWaveformTable();
  if (L6208_IsSysFlag(running))
  { 
    L6208_Board_VrefPwmStart(BRIDGE_A, devicePrm.vrefPwmFreq);
    L6208_Board_VrefPwmStart(BRIDGE_B, devicePrm.vrefPwmFreq);
  }
}

/******************************************************//**
 * @brief Lock while motor is running
 * @param[in] deviceId dummy parameter for compatibility with motor.h
 * @retval None
 **********************************************************/
void L6208_WaitWhileActive(uint8_t deviceId)
{
  /* Wait while motor is running */
  while (L6208_IsSysFlag(running));
}

/**
  * @}
  */ 

/* ------------------------------------------------------------------------- */
/* Private functions ------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/******************************************************//**
 * @brief Clear the bit/s of flags according to the specified mask
 * @param[in] mask flag bit mask
 * @retval None
 **********************************************************/
inline void L6208_ClearSysFlag(uint32_t mask)
  {
  devicePrm.flags &= ~mask;    
}

/******************************************************//**
 * @brief Compute the number of steps at the end of the accereration/deceleration phase
 * P = position in steps at the end of the acceleration/deceleration phase
 * T = acceleration/deceleration time in seconds
 * A =  acceleration/deceleration rate in steps per second per second (steps/sec^2)
 * V = peak velocity during acceleration/deceleration phase
 * V1 = average velocity during acceleration/deceleration phase
 * T = V/A
 * V1 = V/2
 * P = V1*T
 * P = V^2/2A
 * @param  accOrDecRate acceleration/deceleration rate in steps per second per second (steps/sec^2)
 * @retval end position or 0xFFFFFFFF on error 
 **********************************************************/
uint32_t L6208_ComputeNbAccOrDecSteps(uint16_t accOrDecRate)
  {
  uint32_t nbAccOrDecSteps;
  uint32_t locMaxSpeedSps = (uint32_t)devicePrm.maxSpeedSps;
    
  if (L6208_IsSysFlag(microstep))
  {  
    switch(devicePrm.uStepInc)
    {
      case 1:  
        locMaxSpeedSps = (uint32_t)devicePrm.maxSpeedSps;
        break;
      case 2:            
        locMaxSpeedSps = ((uint32_t)devicePrm.maxSpeedSps)>>1;
        accOrDecRate >>= 1;
        break;
      case 4:  
        locMaxSpeedSps = ((uint32_t)devicePrm.maxSpeedSps)>>2;
        accOrDecRate >>= 2;
        break;
      default:
        break;
    }
  }
  else if (L6208_IsSysFlag(halfstep))
    {
    locMaxSpeedSps = ((uint32_t)devicePrm.maxSpeedSps)<<1;
    accOrDecRate <<= 1;
    }
  
  if(accOrDecRate == 0)
    {
    /* division by 0 error */
    return 0xFFFFFFFF;
    }
  nbAccOrDecSteps = locMaxSpeedSps * locMaxSpeedSps;
  nbAccOrDecSteps /= (uint32_t)accOrDecRate;
  nbAccOrDecSteps /= 2;

  return nbAccOrDecSteps;
  }

/******************************************************//**
 * @brief Compute the acceleration/deceleration speed increment value
 * @param[in] newAccOrDecRate acceleration or deceleration value (steps/s^2) greater or equal than 24
 * @retval the speed (step/tick) increment value
 * LSB = 2^-24 step/tick^2 or 2^-20 microstep/tick^2
 * @note return 0 if the rate is too low or if the tick frequency is too small
 * or if the device is running in position mode
 **********************************************************/
uint16_t L6208_ConvertAcceDecelRateValue(uint16_t newAccOrDecRate)
{
  uint64_t tmp64;
  uint32_t tmp32;

  if (((L6208_IsSysFlag(running))&&(L6208_IsSysFlag(positionmode)))||\
      (newAccOrDecRate < L6208_MIN_ACC_DEC_RATE))
  {
    return 0;
  }
  /* Compute (tick frequency)^2 */
  tmp32 = (uint32_t)L6208_Board_TickGetFreq();
  tmp32 *= tmp32;
  /* Return 0 if the (tick frequency)^2 is too small */
  if ( tmp32 < (uint32_t)newAccOrDecRate )
  {
    return 0;
}
  /* Compute the decimal number of microstep or step per tick^2 */
  /* Decimal part is on 32 bits */
  tmp64 = (uint64_t)newAccOrDecRate << 32;
  tmp64 /= ((uint64_t)tmp32);

  return (uint16_t)((tmp64 & 0x00000000FFFFFFFF)>>8);
}

/******************************************************//**
 * @brief Compute next position and speed according to the acceleration rate
 * @retval None
 **********************************************************/
void L6208_DoAccel(void)
{
  /* Increase speed by acceleration rate */
  uint32_t locAccelerationSpt2 = (uint32_t)devicePrm.accelerationSpt2;
  uint32_t locMinSpeedSpt = devicePrm.minSpeedSpt;
  if ((devicePrm.speedSpt + locAccelerationSpt2) < locMinSpeedSpt)
  {
    devicePrm.speedSpt = locMinSpeedSpt;
  }
  else
  {
    devicePrm.speedSpt += locAccelerationSpt2;
  }
  /* Compute next position */
  L6208_DoRun();
}

/******************************************************//**
 * @brief Compute next position and speed according to the deceleration rate
 * @retval None
 **********************************************************/
void L6208_DoDecel(void)
{
  /* Decrease current speed by deceleration rate */
  uint32_t locDecelerationSpt2 = (uint32_t)devicePrm.decelerationSpt2;
  uint32_t locMinSpeedSpt = devicePrm.minSpeedSpt;
  if((devicePrm.speedSpt - locMinSpeedSpt) > (uint32_t)locDecelerationSpt2)  
  {
    devicePrm.speedSpt -= (uint32_t)locDecelerationSpt2;
  }
  else
  {
    /* Set minimum speed */
    devicePrm.speedSpt = locMinSpeedSpt;
  }
  /* Compute next position */
  L6208_DoRun(); 
}

/******************************************************//**
 * @brief Compute next position by adding current speed
 * @retval None
 **********************************************************/
void L6208_DoRun(void)
{
  devicePrm.ticks += (devicePrm.speedSpt >> 8) & 0x0000FFFF;
}

/******************************************************//**
 * @brief Get number of samples to rescale
 * @retval uStepsample2scale the number of micro stepping waveform samples to rescale
 **********************************************************/
uint8_t L6208_GetMicrostepSample2Scale(void)
{
  return devicePrm.uStepsample2scale;
}

/******************************************************//**
 * @brief  Initialize the system for position mode motor moving command
 *  P = total move distance in steps
 *  P1 = steps required to accel from 0 to V
 *  P2 = steps required to decel from V to 0
 *  V = peak velocity in steps per second (steps/sec)
 *  V1 = average velocity during accel or decel*
 *  A = required accel rate in steps per second per second (steps/sec2)
 *  D = required decel rate in steps per second per second (steps/sec2)
 *  T1 = acceleration time in seconds
 *  T2 = deceleration time in seconds*
 *
 *  1) T1 = V / A
 *  2) V1 = V / 2
 *  3) P1 = V1 T1
 *  Substituting 1 and 2 into 3 yields:
 *  4) P1 = V2 / 2A
 *  In the same manner we have:
 *  5) P2 = V2 / 2D
 *
 *  P1 = PD/(D+A)
 *
 *  \sa Application Note: AN2044  
 * @retval None
 **********************************************************/
void L6208_Indexmodeinit(void)
  {
  uint32_t tmpVal0;
  uint32_t tmpVal1;
  uint32_t locAccelSteps;
  uint32_t locDecSteps;

  /* calculate the number of steps to get the running speed */
  locAccelSteps = L6208_ComputeNbAccOrDecSteps(devicePrm.accelerationSps2);
  /* calculate the number of steps to get the motor stopped */
  locDecSteps = L6208_ComputeNbAccOrDecSteps(devicePrm.decelerationSps2);
  if(( locAccelSteps + locDecSteps ) > devicePrm.positionTarget)
  { 
    /* Triangular move needed */
    /* accelsteps = P1 = PD/(D+A) */
    tmpVal0 = devicePrm.positionTarget * devicePrm.decelerationSps2;
    tmpVal1 = (uint32_t)devicePrm.decelerationSps2;
    tmpVal1 += (uint32_t)devicePrm.accelerationSps2;
    locAccelSteps = tmpVal0 / tmpVal1;
    devicePrm.positionTarget1 = locAccelSteps;
    devicePrm.positionTarget2 = devicePrm.positionTarget1 + 1;
    devicePrm.positionTarget3 = devicePrm.positionTarget;
    if(devicePrm.positionTarget1 == 0)
    {
      devicePrm.positionTarget1 = 1;
    }
  }
  else
  { 
    /* trapezoidal move needed */
    /* P1 = V^2/2A */
    /* P2 = P - V^2/2D */
    devicePrm.positionTarget1 = locAccelSteps;
    devicePrm.positionTarget2 = devicePrm.positionTarget - locDecSteps;
    devicePrm.positionTarget3 = devicePrm.positionTarget;
  }
  L6208_SetMotionState(INDEX_ACCEL);  
}

/******************************************************//**
 * @brief Check the bit/s of flags according to the specified mask
 * @param[in] mask flag bit mask
 * @retval TRUE if the bit of the mask are set
 **********************************************************/
inline bool L6208_IsSysFlag(uint32_t mask)
    {
  return (bool)((devicePrm.flags & mask) == mask);    
    }

/******************************************************//**
 * @brief Stepper driver device step state reset subroutine
 * @retval None
 **********************************************************/
void L6208_ResetSteps(void)
    { 
  devicePrm.speedSpt = 0;             // reset the current speed value
  devicePrm.ticks = 0;                // reset the current ticks counter value
  devicePrm.step = 0;                 // reset the current step counter value
  devicePrm.lsbOldTicks = 0;          // reset copy of the previous position (tick)
  devicePrm.lsbOldUSteppingTicks = 0; // reset copy of the previous position (tick) ( micro stepping )
  devicePrm.lsbTicks = 0;             // reset copy of the current position (tick)
  devicePrm.absolutePos = 0;          // reset the absolute motor position in step/microsteps
  devicePrm.uStepSample = 0;          // reset the microstepping waveform sample index
}

/******************************************************//**
 * @brief Compute the specified micro stepping waveform sample with the
 * current selected torque and pwm period
 * @param[in] sampleIndex sample Index
 * @retval scaled sample value
 **********************************************************/
uint32_t L6208_ScaleWaveformSample(uint8_t sampleIndex)
{
  uint32_t sample;

  sample = (uint32_t)RefMicroTable[sampleIndex];
  sample *= L6208_Board_VrefPwmGetPeriod();
  sample >>= (uint32_t)L6208_SINE_WAVEFORM_POWER_OF_TWO_MAX_VALUE;

  sample *= (uint32_t)devicePrm.curTorqueScaler; // torque val (%)
  sample /= (uint32_t)100;

  return sample;
    }

/******************************************************//**
 * @brief Compute the micro stepping waveform sample table samples with the
 * current selected torque and pwm period
 * @retval None
 **********************************************************/
void L6208_ScaleWaveformTable(void)
{
  uint8_t index;
  for(index=0; index<=L6208_USTEPS_PER_QUARTER_PERIOD; index++)
  { 
    /* Calculate the scaled sample and save its value into the waveform to update table */
    updatedMicroTable[index] = (uint16_t)L6208_ScaleWaveformSample(index);
  }
}

/******************************************************//**
 * @brief  Set the parameters of the device to values of the structure pointed
 * by pInitDevicePrm. Set GPIO according to these values.
 * @param pInitDevicePrm pointer onto the structure containing values to
 * initialize the device parameters.
 * @retval None
 **********************************************************/
void L6208_SetDeviceParamsToGivenValues(l6208_Init_t* pInitDevicePrm)
{
  memset(&devicePrm, 0, sizeof(devicePrm));
  L6208_SetAcceleration(0, pInitDevicePrm->accelerationSps2);
  L6208_SetDeceleration(0, pInitDevicePrm->decelerationSps2);
  L6208_SetMaxSpeed(0, pInitDevicePrm->maxSpeedSps);
  L6208_SetMinSpeed(0, L6208_MIN_SPEED);
  devicePrm.accelTorque = pInitDevicePrm->accelTorque;
  devicePrm.decelTorque = pInitDevicePrm->decelTorque;
  devicePrm.runTorque = pInitDevicePrm->runTorque;
  devicePrm.holdTorque = pInitDevicePrm->holdTorque;
  /* Only once acceleration, deceleration, min speed and max speed have been */
  /* initialized, set the step mode */
  devicePrm.stepMode = pInitDevicePrm->stepMode;
  L6208_SetDecayMode(0, pInitDevicePrm->decayMode);
  devicePrm.moveDwellTime = pInitDevicePrm->moveDwellTime;
  if (L6208_CONF_PARAM_AUTO_HIZ_STOP) L6208_SetSysFlag(pInitDevicePrm->autoHiZstop);
  if (!L6208_Board_VrefPwmFreqCheck(pInitDevicePrm->vrefPwmFreq))
    L6208_ErrorHandler(L6208_ERROR_SET_PWM);  
  devicePrm.vrefPwmFreq = pInitDevicePrm->vrefPwmFreq;
  /* Initialize current stepper state machine index  */
  L6208_SetMotionState(INACTIVE);
}

/******************************************************//**
 * @brief  Set the parameters of the device to predefined values
 * Set GPIO according to these values
 * from l6208_target_config.h
 * @retval None
 **********************************************************/
void L6208_SetDeviceParamsToPredefinedValues(void)
  {
  memset(&devicePrm, 0, sizeof(devicePrm));
  L6208_SetAcceleration(0, L6208_CONF_PARAM_ACC_RATE);
  L6208_SetDeceleration(0, L6208_CONF_PARAM_DEC_RATE);
  L6208_SetMaxSpeed(0, L6208_CONF_PARAM_RUNNING_SPEED);
  L6208_SetMinSpeed(0, L6208_MIN_SPEED);
  devicePrm.accelTorque = L6208_CONF_PARAM_ACC_CURRENT;
  devicePrm.decelTorque = L6208_CONF_PARAM_DEC_CURRENT;
  devicePrm.runTorque = L6208_CONF_PARAM_RUNNING_CURRENT;
  devicePrm.holdTorque = L6208_CONF_PARAM_HOLDING_CURRENT;
  /* Only once acceleration, deceleration, min speed and max speed have been */
  /* initialized, set the step mode */
  devicePrm.stepMode = L6208_CONF_PARAM_STEP_MODE;
  L6208_SetDecayMode(0, L6208_CONF_PARAM_DECAY_MODE);
  devicePrm.moveDwellTime = L6208_CONF_PARAM_DWELL_TIME;
  if (L6208_CONF_PARAM_AUTO_HIZ_STOP) L6208_SetSysFlag(HiZstop);
  if (!L6208_Board_VrefPwmFreqCheck(L6208_CONF_VREF_PWM_FREQUENCY))
    L6208_ErrorHandler(L6208_ERROR_SET_PWM);
  devicePrm.vrefPwmFreq = L6208_CONF_VREF_PWM_FREQUENCY;
  /* Initialize current stepper state machine index  */
  L6208_SetMotionState(INACTIVE);
  } 

/******************************************************//**
 * @brief Set the number of micro stepping waveform samples to rescale
 * @param[in] value number of micro stepping waveform samples 
 * @retval None
 **********************************************************/
void L6208_SetMicrostepSample2Scale(uint8_t value)
{
  // clamp to maximum number of samples per period/4
  if(value > L6208_USTEPS_PER_QUARTER_PERIOD)
  {
    value = L6208_USTEPS_PER_QUARTER_PERIOD;
  }
  devicePrm.uStepsample2scale = value;    
}

/******************************************************//**
 * @brief Set the number of micro stepping waveform samples to update into scanning
 * @param[in] value number of micro stepping waveform samples 
 * @retval None
 **********************************************************/
void L6208_SetMicrostepSample2Update(uint8_t value)
{
  // clamp to maximum number of samples per period/4
  if(value > L6208_USTEPS_PER_QUARTER_PERIOD)
  {
    value = L6208_USTEPS_PER_QUARTER_PERIOD;  
  }
  devicePrm.uStepsample2update = value;    
  } 

/******************************************************//**
 * @brief Set the stepper state machine index
 * @param[in] newMotionState
 * @retval None
 **********************************************************/
void L6208_SetMotionState(motorState_t newMotionState)
{
  // sets the new stepper state machine index
  devicePrm.motionState = newMotionState;    
}

/******************************************************//**
 * @brief Set the user selected speed in step/tick
 * @param[in] newSpeed speed value (step/s)
 * @param[in] pSpeed pointer to the selected speed field
 * @retval return FALSE if the speed is too low or too high
 * or if the device is running in position mode, else TRUE
 **********************************************************/
bool L6208_SetSpeed(uint16_t newSpeed, uint32_t volatile *pSpeed)
{
  uint64_t tmp64;
  uint32_t tmp32;

  if (((L6208_IsSysFlag(running))&&(L6208_IsSysFlag(positionmode)))||\
      (newSpeed < L6208_MIN_SPEED))
  {
    return FALSE;
  }
  tmp32 = (uint32_t)L6208_Board_TickGetFreq();
  if (tmp32 < newSpeed)
  {
    return FALSE;
  }
  /* Compute the decimal number of microstep or step per tick */
  /* Decimal part is on 32 bits */
  tmp64 = (uint64_t)newSpeed << 32;
  tmp64 /= ((uint64_t)tmp32);
  /* set the running constant speed value (step/tick) */
  *pSpeed = (uint32_t)((tmp64 & 0x00000000FFFFFFFF)>>8);
  
  return TRUE;
}

/******************************************************//**
 * @brief Set the bit/s of flags according to the specified mask
 * @param[in] mask flag bit mask
 * @retval None
 **********************************************************/
inline void L6208_SetSysFlag(uint32_t mask)
  {  
  devicePrm.flags |= mask;    
}

/******************************************************//**
 * @brief Stepper motor start command
 * @retval true on correct command execution
 **********************************************************/
bool L6208_StartMovement(void)
{
  uint32_t tmp;
  if (L6208_IsSysFlag(running))
  {
    /* Motor is already running ==> quit */
    return FALSE;    
  }
  if (!L6208_IsSysFlag(positionmode))
  {
    /* Set the VREFA and VREFB to the selected acc. torque */
    L6208_VectorCalc(devicePrm.accelTorque);
  
    /* If the speed control mode is selected */
    /* setup the motor acceleration for velocity mode driving */
    L6208_SetMotionState(ACCELERATING);  
  }
  else
  {
    /* if position control mode is selected, reset the current step counter  */
    devicePrm.step = 0;    
    if(devicePrm.uStepSample > 31)
    {
      /* check the micro stepping waveform sample index */
      devicePrm.uStepSample = 0;
    }
    /* Set the position dwelling wait time */
    /* compute number of ticks per millisecond */
    tmp = (uint32_t)L6208_Board_TickGetFreq() / 1000;
    /* Compute the dwelling time in ticks => dwellCounter (ticks) */
    devicePrm.dwellCounter = tmp * (uint32_t)devicePrm.moveDwellTime;
    if (devicePrm.positionTarget == 0)
    {
      /* if the position to go is 0 (no move) */
      /* Set the deceleration torque */
      L6208_VectorCalc(devicePrm.decelTorque); 
      /* Set the dwelling delay state index */
      L6208_SetMotionState(INDEX_DWELL);       
  }
    else
  {
      /* Set the VREFA and VREFB to the selected acc. torque */
      L6208_VectorCalc(devicePrm.accelTorque);
      /* go to the selected position */
      L6208_Indexmodeinit();
      L6208_SetMotionState(INDEX_ACCEL);
  }
  }
  /* Sets the motor running flag */
  L6208_SetSysFlag(running);
  /* Start the VREFA and VREFB PWMs */
  L6208_Board_VrefPwmStart(BRIDGE_A, devicePrm.vrefPwmFreq);
  L6208_Board_VrefPwmStart(BRIDGE_B, devicePrm.vrefPwmFreq);
  if (!(L6208_IsSysFlag(EN_A_set)))
  {
    /* Enable power bridges */
    L6208_Enable(0);
  }
  /* Start the tick */
  L6208_Board_TickStart();

  return TRUE;
}

/******************************************************//**
 * @brief Update the micro stepping waveform samples table with the
 * values previously scaled with current selected torque and tick period
 * @retval None
 **********************************************************/
void L6208_UpdateScanWaveformTable(void)
{
  uint8_t index;

  for(index=0; index<=L6208_USTEPS_PER_QUARTER_PERIOD; index++)
  {
    microTable1[index] = updatedMicroTable[index];
    microTable1[L6208_USTEPS_PER_QUARTER_PERIOD*2 - index] = microTable1[index];
    microTable1[index + L6208_USTEPS_PER_QUARTER_PERIOD*2] = updatedMicroTable[index];
  }
  /* clear the number of samples to update */
  L6208_SetMicrostepSample2Update(0); 
}

/******************************************************//**
 * @brief Check if there are waveform samples to rescale and if so, perform the rescaling
 * @retval None
 **********************************************************/
void L6208_UstepWaveformHandling(void)
{
  /* micro stepper waveform samples rescaling ... and updating */
  if(L6208_GetMicrostepSample2Scale() > 0)
  { 
    /* Current torque value has been changed, so recalculate the waveform table */
    L6208_ScaleWaveformTable();
	
    /* Set the number of samples to update */
    L6208_SetMicrostepSample2Update(L6208_USTEPS_PER_QUARTER_PERIOD);

    /* Reset the number of samples to rescaled afer rescaling */
    L6208_SetMicrostepSample2Scale(0);
  }
}

/******************************************************//**
 * @brief Set the current torque value (Vref)
 * @param[in] newTorque Selected torque value
 * @retval always TRUE
 **********************************************************/
bool L6208_VectorCalc(uint8_t newTorque)
{
  /* save current selected torque value */
  devicePrm.curTorqueScaler = newTorque;

  if(!L6208_IsSysFlag(microstep))
  {
    /* full/half step mode or the motor is not running */
    /* set the PWM duty cycle according to the current torque value (%). */
    /* The TON value will be calculated inside the TIMx_PWM_duty_setup f(). */
    L6208_Board_VrefPwmSetDutyCycle(BRIDGE_A, devicePrm.curTorqueScaler, TRUE);
    L6208_Board_VrefPwmSetDutyCycle(BRIDGE_B, devicePrm.curTorqueScaler, TRUE);
  }
  else
  { 
    /* microstep mode */
    if(L6208_IsSysFlag(running))
    {
      /* set the number of waveform sample to rescale according current selected */
      /* torque value */
      L6208_SetMicrostepSample2Scale(L6208_USTEPS_PER_QUARTER_PERIOD);
    }
    else
    { 
      /* micro stepping mode motor stopped */
      /* Recompute the waveform samples according to the new PWM frequency */
      L6208_ScaleWaveformTable();
      /* Update the waveform scanning table */
      L6208_UpdateScanWaveformTable();
      /* Set the VREF timer PWM TON to update VREFA and VREFB */
      L6208_Board_VrefPwmSetDutyCycle(BRIDGE_A, pMicroTable2[devicePrm.uStepSample], FALSE);
      L6208_Board_VrefPwmSetDutyCycle(BRIDGE_B, microTable1[devicePrm.uStepSample], FALSE);
    }
  }
  return TRUE;
}

/**
  * @}
  */

/**
  * @}
  */
  
/**
  * @}
  */

/******************* (C) COPYRIGHT 2016 STMicroelectronics *****END OF FILE****/
