mbedos senza corrente

MX.cpp

Committer:
marcodesilva
Date:
2019-11-05
Revision:
22:5d3f37356915
Parent:
21:fe5dd48bebc6

File content as of revision 22:5d3f37356915:


#include "MX.h"

MX::MX(){
}

MX::MX(int* broadcastID, int Nmotor, int MotorBaud, UARTSerial_half* pCommLayer){
    _MotorBaud = MotorBaud;   
    _pCommLayer = pCommLayer;
    _broadcastID = broadcastID ; 
    _Nmotor = Nmotor;
}


int MX::SyncTorqueEnable(bool enableVal[], int ID) {

    int Nmotor = _Nmotor;
    char data[1*Nmotor]; 

    for (int i=0 ; i<Nmotor ; i++){  
        data[i] = enableVal[i];
    }    
    
    #if SYNC_TORQUE_ENABLE_DEBUG
    printf("\n          SYNC TORQUE ENABLE\n");
    for (int i=0 ; i<Nmotor ; i++){  
        printf("\n Torque Enable value for ID[%d] = %d",_broadcastID[i], enableVal[i]);
    }
    #endif
    
    int rVal = SyncSendPacket(MX_REG_TORQUE_ENABLE, 1, data, ID);
    
    return(rVal);
}


int MX::SyncSetBaud(int MotorBaud[], int ID) {

    int Nmotor = _Nmotor;
    char data[1*Nmotor]; 

    for (int i=0 ; i<Nmotor ; i++){  
        data[i] = MotorBaud[i];
    }    
    
    #if SYNC_SET_BAUD_DEBUG
    printf("\n          SYNC_SET_BAUD_DEBUG\n");
    for (int i=0 ; i<Nmotor ; i++){  
        printf("Set Baud rate value to: 0x%02x\n",MotorBaud[i]);
    }
    printf( "*    0x00 =     9,600  bps \n"
            "*    0x01 =    57,600  bps (DEFAULT)\n"
            "*    0x02 =    115,200 bps \n"
            "*    0x03 =    1       Mbps \n"
            "*    0x04 =    2       Mbps \n"
            "*    0x05 =    3       Mbps \n"
            "*    0x06 =    4       Mbps \n"
            "*    0x06 =    4,5     Mbps \n");
    for (int i=0 ; i<Nmotor ; i++){  
        printf("\n Operating mode value for ID[%d] = %d",_broadcastID[i], MotorBaud[i]);
    }
    #endif
    
    int rVal = SyncSendPacket(MX_REG_OPERATING_MODE, 1, data, ID);
    
    return(rVal);
}



int MX::SyncSetGoal(float degrees, int ID) {
    
    float goal = (degrees) * (float)(4095/360);
    
    goal = goal+2048;
    char data[4];    
        
    for (int j = 0 ; j < 4 ; j++){
        data[j] = ((int)goal >> (j*8) ) & 0xff;     // top 8 bits
    }   
    
    #if SYNC_SETGOAL_DEBUG         
    printf("\n          SYNC SET GOAL\n ");
    printf("\nGOAL CHOSEN FOR EACH MOTOR\n");
    printf("goal[ID]: value(0-4095) - value(0 - 360)\n");
    printf("goal[%d]: %f - %.02f\n",ID,goal,degrees);
    printf("\nDATA TO SET FOR EACH MOTOR (entire buffer RAW values) \n");
    for (int j = 0 ; j < 4; j++){
        printf("data[%d]: %02x\n",j+(4),data[j+(4)]);             //debug data 
    }    
    #endif

    int rVal = SyncSendPacket(MX_REG_GOAL_POSITION, 4, data, ID); 

    return(rVal);
}

int MX::SyncSetGoal(float degrees[]) {
    
    char data[4*_Nmotor];   //4 is dimension in bytes of instruction         
    int goal[_Nmotor];
                
    for (int i=0 ; i<_Nmotor ; i++){                                      //set goal array with goal in RAW(uint32) values from DEGREES(float)
         goal[i] = (degrees[i]) * (float)(4095/360);  
         goal[i] = goal[i]+2048;
      
    }
     
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 4 bytes sequence (split RAW(uint32) in 4x bytes(uint8) 0-255
        for (int j = 0 ; j < 4; j++){
            data[j+(i*4)] = (goal[i] >> (j*8) ) & 0xff;    // top 8 bits
            }
    }      
      
    #if SYNC_SETGOAL_DEBUG         
    printf("\n          SYNC SET GOAL\n ");
    printf("\nGOAL CHOSEN FOR EACH MOTOR\n");
    printf("goal[ID]: value(0-4095) - value(0 - 360)\n");
    for (int i=0; i<_Nmotor ; i++){
        printf("goal[%d]: %d - %.02f\n",_broadcastID[i],goal[i],degrees[i]);
    }
    printf("\nDATA TO SET FOR EACH MOTOR (entire buffer RAW values) \n");
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 4 bytes sequence (split RAW(uint32) in 4x bytes(uint8)
        for (int j = 0 ; j < 4; j++){
            printf("data[%d]: %02x\n",j+(i*4),data[j+(i*4)]);             //debug data 
        }
        printf("\n");           
    }    
    #endif   
        
    // write the packet, and return the error code
    int rVal = SyncSendPacket(MX_REG_GOAL_POSITION, 4, data);
    
    return(rVal);
}


int MX::SyncOperatingMode(int mode[], int ID) {

    int Nmotor = _Nmotor;
    char data[1*Nmotor]; 

    for (int i=0 ; i<Nmotor ; i++){  
        data[i] = mode[i];
    }    
    
    #if SYNC_OPERATING_MODE_DEBUG
    printf("\n          SYNC OPERATING MODE DEBUG\n");
    for (int i=0 ; i<Nmotor ; i++){  
        printf("Set Operating Mode value to: 0x%02x\n",mode[i]);
    }
    printf( "*    0x00 =    Current Control Mode\n"
            "*    0x01 =    Velocity Control Mode\n"
            "*    0x03 =    Position Control Mode (DEFAULT)\n"
            "*    0x04 =    Extended Position Control Mode(Multi-turn)\n"
            "*    0x05 =    Current-based Position Control Mode\n"
            "*    0x16 =    PWM Control Mode (Voltage Control Mode)\n");
    for (int i=0 ; i<Nmotor ; i++){  
        printf("\n Operating mode value for ID[%d] = %d",_broadcastID[i], mode[i]);
    }
    #endif
    
    int rVal = SyncSendPacket(MX_REG_OPERATING_MODE, 1, data, ID);
    
    return(rVal);
}


int MX::SyncCurrentLimit(float mAmpere, int ID) {
 
    uint8_t byte = 2;     //2 is dimension in bytes of instruction    
    float goal = (mAmpere) * (float)(1941/6521.76);
    char data[byte];    
        
    for (int j = 0 ; j < byte ; j++){
        data[j] = ((int)goal >> (j*8) ) & 0xff;     // top 8 bits
    }   
    
    #if SYNC_CURRENT_LIMIT_DEBUG         
    printf("\n          SYNC CURRENT LIMIT DEBUG\n ");
    printf("\nCURRENT LIMIT CHOSEN FOR EACH MOTOR\n");
    printf("Current limit[ID]: value(0-1941) - value(0mA - 6521.76mA)\n");
    printf("Current[%d]: %f - %.02f\n",ID,goal,mAmpere);
    printf("\nDATA TO SET FOR EACH MOTOR (entire buffer RAW values) \n");
    for (int j = 0 ; j < byte; j++){
        printf("data[%d]: %02x\n",j+(byte),data[j+(byte)]);             //debug data 
    }    
    #endif

    int rVal = SyncSendPacket(MX_REG_CURRENT_LIMIT, byte, data, ID); 

    return(rVal);
}


int MX::SyncCurrentLimit(float mAmpere[]) {
    
    uint8_t byte = 2;     //2 is dimension in bytes of instruction 
    char data[byte*_Nmotor];           
    int goal[_Nmotor];
                
    for (int i=0 ; i<_Nmotor ; i++){                                      //set goal array with goal in RAW(uint32) values from DEGREES(float)
         goal[i] = (mAmpere[i]) * (float)(1941/6521.76);        
    }
     
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 2 bytes sequence (split RAW(uint32) in 2*bytes(uint8)
        for (int j = 0 ; j < byte; j++){
            data[j+(i*byte)] = (goal[i] >> (j*8) ) & 0xff;    // top 8 bits
            }
    }      
      
    #if SYNC_CURRENT_LIMIT_DEBUG         
    printf("\n          SYNC CURRENT LIMIT DEBUG\n ");
    printf("\nCURRENT LIMIT CHOSEN FOR EACH MOTOR\n");
    printf("Current limit[ID]: value(0-1941) - value(0mA - 6521.76mA)\n");
    for (int i=0; i<_Nmotor ; i++){
        printf("goal[%d]: %d - %.02f\n",_broadcastID[i],goal[i],mAmpere[i]);
    }
    printf("\nDATA TO SET FOR EACH MOTOR (entire buffer RAW values) \n");
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 2 bytes sequence (split RAW(uint32) in 2*bytes(uint8)
        for (int j = 0 ; j < byte; j++){
            printf("data[%d]: %02x\n",j+(i*byte),data[j+(i*byte)]);             //debug data 
        }
        printf("\n");           
    }    
    #endif   
        
    // write the packet, and return the error code
    int rVal = SyncSendPacket(MX_REG_CURRENT_LIMIT, byte, data);
    
    return(rVal);
}


int MX::SyncGoalCurrent(float mAmpere, int ID) {
 
    uint8_t byte = 2;     //2 is dimension in bytes of instruction    
    float goal = (mAmpere) * (float)(1941/6521.76);
    char data[byte];    
        
    for (int j = 0 ; j < byte ; j++){
        data[j] = ((int)goal >> (j*8) ) & 0xff;     // top 8 bits
    }   
    
    #if SYNC_GOAL_CURRENT_DEBUG         
    printf("\n          SYNC GOAL CURRENT\n ");
    printf("\nGOAL CHOSEN FOR EACH MOTOR\n");
    printf("goal[ID]: value(-1941-1941) - value(-6521.76mA - 6521.76mA)\n");
    printf("goal[%d]: %f - %.02f\n",ID,goal,mAmpere);
    printf("\nDATA TO SET FOR EACH MOTOR (entire buffer RAW values) \n");
    for (int j = 0 ; j < byte; j++){
        printf("data[%d]: %02x\n",j+(byte),data[j+(byte)]);             //debug data 
    }    
    #endif

    int rVal = SyncSendPacket(MX_REG_GOAL_CURRENT, byte, data, ID); 

    return(rVal);
}


int MX::SyncGoalCurrent(float mAmpere[]) {
    
    uint8_t byte = 2;     //2 is dimension in bytes of instruction 
    char data[byte*_Nmotor];           
    int goal[_Nmotor];
                
    for (int i=0 ; i<_Nmotor ; i++){                                      //set goal array with goal in RAW(uint32) values from DEGREES(float)
         goal[i] = (mAmpere[i]) * (float)(1941/6521.76);        
    }
     
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 2 bytes sequence (split RAW(uint32) in 2*bytes(uint8)
        for (int j = 0 ; j < byte; j++){
            data[j+(i*byte)] = (goal[i] >> (j*8) ) & 0xff;    // top 8 bits
            }
    }      
      
    #if SYNC_GOAL_CURRENT_DEBUG          
    printf("\n          SYNC GOAL CURRENT\n ");
    printf("\nGOAL CHOSEN FOR EACH MOTOR\n");
    printf("goal[ID]: value(0-1941) - value(-6521.76mA - 6521.76mA)\n");
    for (int i=0; i<_Nmotor ; i++){
        printf("goal[%d]: %d - %.02f\n",_broadcastID[i],goal[i],mAmpere[i]);
    }
    printf("\nDATA TO SET FOR EACH MOTOR (entire buffer RAW values) \n");
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 2 bytes sequence (split RAW(uint32) in 2*bytes(uint8)
        for (int j = 0 ; j < byte; j++){
            printf("data[%d]: %02x\n",j+(i*byte),data[j+(i*byte)]);             //debug data 
        }
        printf("\n");           
    }    
    #endif   
        
    // write the packet, and return the error code
    int rVal = SyncSendPacket(MX_REG_GOAL_CURRENT, byte, data);
    
    return(rVal);
}


int MX::SyncGoalPWM(float values[], int ID) {
    
    uint8_t byte = 2;     //2 is dimension in bytes of instruction 
    char data[byte*_Nmotor];           
    int goal[_Nmotor];
                
    for (int i=0 ; i<_Nmotor ; i++){                                      //set goal array with goal in RAW(uint32) values from DEGREES(float)
         goal[i] = (values[i]) * (float)(885/100);        
    }
     
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 2 bytes sequence (split RAW(uint32) in 2*bytes(uint8)
        for (int j = 0 ; j < byte; j++){
            data[j+(i*byte)] = (goal[i] >> (j*8) ) & 0xff;    // top 8 bits
            }
    }            
    // write the packet, and return the error code
    int rVal = SyncSendPacket(MX_REG_GOAL_PWM, byte, data, ID);     
    
    return(rVal);
}



int MX::SyncProfileAccel(float profileValAcc[]) {
    
    char data[4*_Nmotor];   //4 is dimension in bytes of instruction         
    int goal[_Nmotor];
                
    for (int i=0 ; i<_Nmotor ; i++){                                      //set goal array with goal in RAW(uint32) values from DEGREES(float)
        goal[i] = (profileValAcc[i]);      
    }
     
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 4 bytes sequence (split RAW(uint32) in 4x bytes(uint8) 0-255
        for (int j = 0 ; j < 4; j++){
            data[j+(i*4)] = (goal[i] >> (j*8) ) & 0xff;                   // top 8 bits
            }
    }      
      
    #if SYNC_SETGOAL_DEBUG    
    printf("\n##########################################");      
    printf("\n          SYNC SET PROFILE ACCELERATION \n ");
    printf("\nACCELLERATION CHOSEN FOR EACH MOTOR\n");
    printf("Acceleration[ID]: value(0-32767) \n");
    for (int i=0; i<_Nmotor ; i++){
        printf("goal[%d] :   %d        ",_broadcastID[i],goal[i]);
    }
    printf("\nDATA TO SET FOR EACH MOTOR (entire buffer RAW values) \n");
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 4 bytes sequence (split RAW(uint32) in 4x bytes(uint8)
        for (int j = 0 ; j < 4; j++){
            printf("data[%d]: %02x\n",j+(i*4),data[j+(i*4)]);             //debug data 
        }
        printf("\n");           
    }    
    #endif   
        
    // write the packet, and return the error code
    int rVal = SyncSendPacket( MX_REG_PROFILE_ACCELER , 4, data);
    
    return(rVal);
}


int MX::SyncProfileVel(float profileValueVel[]) {
    
    char data[4*_Nmotor];   //4 is dimension in bytes of instruction         
    int goal[_Nmotor];
                
    for (int i=0 ; i<_Nmotor ; i++){                                      //set goal array with goal in RAW(uint32) values from DEGREES(float)
        goal[i] = (profileValueVel[i]);      
    }
     
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 4 bytes sequence (split RAW(uint32) in 4x bytes(uint8) 0-255
        for (int j = 0 ; j < 4; j++){
            data[j+(i*4)] = (goal[i] >> (j*8) ) & 0xff;                   // top 8 bits
            }
    }      
      
    #if SYNC_SETGOAL_DEBUG    
    printf("\n##########################################");      
    printf("\n          SYNC SET PROFILE VELOCITY \n ");
    printf("\nVELOCITY CHOSEN FOR EACH MOTOR\n");
    printf("Velocity[ID]: value(0-44) \n");
    for (int i=0; i<_Nmotor ; i++){
        printf("goal[%d] :   %d        ",_broadcastID[i],goal[i]);
    }
    printf("\nDATA TO SET FOR EACH MOTOR (entire buffer RAW values) \n");
    for (int i=0 ; i<_Nmotor ; i++){                                      //set data array in 4 bytes sequence (split RAW(uint32) in 4x bytes(uint8)
        for (int j = 0 ; j < 4; j++){
            printf("data[%d]: %02x\n",j+(i*4),data[j+(i*4)]);             //debug data 
        }
        printf("\n");           
    }    
    #endif   
        
    // write the packet, and return the error code
    int rVal = SyncSendPacket( MX_REG_PROFILE_VELOCITY , 4, data);
    
    return(rVal);
}

void MX::SyncGetPosition(float* angle) {
    int bytes = 4;
    int NumberOfMotor  = _Nmotor;

    char data[(11+bytes)*NumberOfMotor];
    
    int32_t position[NumberOfMotor];
    float ScaleFactor = (float)360/4095;  


    SyncReadPacket(MX_REG_PRESENT_POSITION, bytes,data);

    
    for (int i=0 ;i<_Nmotor ;i++){  
        position[i]   = (int)data[12+(11+bytes)*i] << 24;         
        position[i]  |= (int)data[11+(11+bytes)*i] << 16;
        position[i]  |= (int)data[10+(11+bytes)*i] << 8;
        position[i]  |= (int)data[9 +(11+bytes)*i];
    }   
    
    for (int i=0 ;i<_Nmotor ;i++){
        // angle(degree) obtained from position(0 - 4095)
        position[i] = position[i]-2048;
        angle[i] = (float)position[i]*ScaleFactor;
    }

#if SYNC_GET_POSITION_DEBUG    
    for (int i=0 ;i<_Nmotor ;i++){     
        printf("\nGet RAW current data from ID: %d\n",_broadcastID[i]);  
        printf("  Data[%d]: 0x%02x\n",(9 +(11+bytes)*i),data[9 +(11+bytes)*i]);
        printf("  Data[%d]: 0x%02x\n",(10 +(11+bytes)*i),data[10 +(11+bytes)*i]);
        printf("  Data[%d]: 0x%02x\n",(11 +(11+bytes)*i),data[11 +(11+bytes)*i]);
        printf("  Data[%d]: 0x%02x\n",(12 +(11+bytes)*i),data[12 +(11+bytes)*i]);
        printf("Converted position (0 - 4095): %d\n",position[i]);
        printf("Converted angle %f\n\n",angle[i]); 
    }           
#endif      

    //return angle;
}

void MX::SyncGetCurrent(float* presentCurrent) {

    printf("\n##########################################");
    printf("\n SYNC GET CURRENT ");
    
    int bytes = 4;
    char data[(11+bytes)*_Nmotor];
    int32_t current[bytes];

    //float presentCurrent[NumberOfMotor] ;
    float scaleFactor = (float)3.36;  //  3.36mA is a unit for scale from 0 to 1941 in DEC 

     
    //char Status[(11+bytes)*_Nmotor]; (11+bytes)
    SyncReadPacket(MX_REG_PRESENT_CURRENT, bytes, data);

    for (int i=0 ;i<_Nmotor ;i++){  
        current[i]   = (int)data[12+(11+bytes)*i] << 24;         
        current[i]  |= (int)data[11+(11+bytes)*i] << 16;
        current[i]  |= (int)data[10+(11+bytes)*i] << 8;
        current[i]  |= (int)data[9 +(11+bytes)*i];
    }   

    for (int i=0 ;i<_Nmotor ;i++){
        if ((int)data[10+(11+bytes)*i] == 255){
            current[i] = current[i] - (float)65535;
        }
    // PresentCurrent (mA) obtained from current (0 - 1941)
    presentCurrent[i] = (float)current[i]*scaleFactor;
    }

#if SYNC_GET_CURRENT_DEBUG    
    for (int i=0 ;i<_Nmotor ;i++){     
        printf("\nGet RAW current data from ID: %d\n",_broadcastID[i]);    
        printf("  Data[%d]: 0x%02x\n",(9 +(11+bytes)*i),data[9 +(11+bytes)*i]);
        printf("  Data[%d]: 0x%02x\n",(10 +(11+bytes)*i),data[10 +(11+bytes)*i]);
        printf("  Data[%d]: 0x%02x\n",(11 +(11+bytes)*i),data[11 +(11+bytes)*i]);
        printf("  Data[%d]: 0x%02x\n",(12 +(11+bytes)*i),data[12 +(11+bytes)*i]);
        printf("Converted Current (0 - 1941): %d\n",current[i]);
        printf("Converted Present Current %f mA\n\n",presentCurrent[i]);
    }           
#endif      
}


int MX::SyncSendPacket(int start, int bytes, char* data, int ID) {
      
    int Nmotor ;   
    if (ID == -1){
        Nmotor = _Nmotor;
        }
    else{
        Nmotor = 1;
        }
    
    char TxBuf[12+((bytes+1)*Nmotor)+2];
    char Status[11];
    int TxBufSize = sizeof(TxBuf);
    
    // initialization of vector TxBuf
    for (int i=0; i<TxBufSize ; i++){  
        TxBuf[i] = 0x00; 
    } 
    
    // Inizialization
    Status[8]=0x00; //The error is set to zero  
    // Build the TxPacket first in RAM, then we'll send in one go
    TxBuf[0] = 0xff;        //H1
    TxBuf[1] = 0xff;        //H2
    TxBuf[2] = 0xfd;        //H3
    TxBuf[3] = 0x00;        //Reserved
    TxBuf[4] = 0xfe;        //Broadcast ID
    // Length
    TxBuf[5] = (7+( (bytes+1)*Nmotor) ) & 0xff;    //packet length low 8 = inst(1bytes)+ param(instr.bytes+1)+CRC(2bytes)
    TxBuf[6] = (7+( (bytes+1)*Nmotor) ) >> 8;      //packet length high
    // Instruction
    TxBuf[7] = 0x83;        //Sync Write
    // Parameters         
    TxBuf[8] = start & 0xff;             //Low order byte from starting address
    TxBuf[9] = start >> 8;               //High order byte from starting address
    // Bytes lenght needed for instruction         
    TxBuf[10] = bytes & 0xff;            //Low order byte from starting address
    TxBuf[11] = bytes >> 8;              //High order byte from starting address
    // data
    // Motor parameters for each motors

    #if SYNC_SENDPACKET_DEBUG
    printf("\nDEBUG DI SyncSendPacket");
    printf("\nTxBuf length : %d\n",TxBufSize );
    printf("\nTxBuf before data and CRC adding:\n ");
    for (int i=0; i<TxBufSize ; i++){  
        printf("\nTxBuf[%d] = %x ",i,TxBuf[i]); 
    }
    printf("\n\nData to add");
    for (int i=0; i<(Nmotor*bytes) ; i++){  
        printf("\ndata[%d] = %02x ",i,data[i]); 
    } 
    #endif             

    for (int i=0; i<Nmotor ; i++){    
        // t is a index of TxBuf
        int t = 12 +((bytes+1)*i);      // (bytes+1) => instruction dim + 1 (for ID) * i (for each motor) 
    
        if (Nmotor == 1){
            #if SYNC_SENDPACKET_DEBUG
            printf("\nSINGLE MOTOR ");
            #endif
            TxBuf[t] = ID;
        }else{
            #if SYNC_SENDPACKET_DEBUG
            printf("\n\nMULTI MOTOR "); 
            printf("\nID: %d", _broadcastID[i]);
            #endif
            TxBuf[t] = _broadcastID[i];
        }
        
       for (int j = 0; j < bytes ; j++){           
            //Little endian  
            TxBuf[t+j+1] = data[j+(i*(bytes))];        //(first byte is a low order byte, second byte are High order byte) 
            #if SYNC_SENDPACKET_DEBUG
            printf("\nTxBuf[%d] = data[%d] = %x ",t+j+1,j+(i*bytes),data[j+(i*bytes)]);
            #endif
        }
    }
    //        CRC         //
    uint16_t crc16 ;
    int dataSize = TxBufSize-2;
    crc16 = update_crc(0, TxBuf, dataSize); 
      
    TxBuf[TxBufSize-2] = (crc16 & 0x00FF);
    TxBuf[TxBufSize-1] = (crc16>>8) & 0x00FF; 
    //printf("\nCRC 1 : %02x CRC 1 : %02x ",TxBuf[14+((bytes)*Nmotor)],TxBuf[15+((bytes)*Nmotor)]);
   
    #if SYNC_SENDPACKET_DEBUG_PACKETONLY
    printf("\n\n        Complete Packet to send of %d elements\n", TxBufSize);
    for (int i=0; i<TxBufSize ; i++){  
        printf("\nTxBuf[%d] = %02x ",i,TxBuf[i]); 
    }
    printf("\n          SYNC SEND PACKET     \n");
    for (int i=0; i<TxBufSize ; i++){  
        printf("|%02x",TxBuf[i]); 
    }
    printf("\n               \n");
    #endif
    
    // Build the TxPacket first in RAM, then we'll send in one go
    _pCommLayer->flush();
    _pCommLayer->write(TxBuf,TxBufSize); // UART-write 

    return(Status[8]); // return error code
}


void MX::SyncReadPacket(int start, int bytes, char* data) {

    char TxBuf[12+(_Nmotor)+2];
    char Status[(11+bytes)*_Nmotor];
    int TxBufSize = sizeof(TxBuf);
    //char data[(11+bytes)*_Nmotor];
    Status[8] = 0x00;           // The error is set to zero

    // Build the TxPacket (FIXED !) first in RAM, then we'll send in one go
    //Header 
    TxBuf[0] = 0xff;            //H1
    TxBuf[1] = 0xff;            //H2
    TxBuf[2] = 0xfd;            //H3
    // Reserved
    TxBuf[3] = 0x00;            
    // ID 
    TxBuf[4] = 0xfe;            // Broadcast
    // Lenght             7 bytes = inst(1)+ param(4 + numbers of motors)+CRC(2)
    TxBuf[5] = 7+(_Nmotor) & 0xff;    // packet length low 
    TxBuf[6] = (7+(_Nmotor)) >> 8;      // packet length high
    // Instruction
    TxBuf[7] = 0x82;                 
    // Param 
    TxBuf[8] = start & 0xFF;    // Address
    TxBuf[9] = start >> 8;       
    TxBuf[10] = bytes & 0xFF;;  // Lenght of reply 
    TxBuf[11] = bytes >> 8;  
    for (int i=0; i<_Nmotor ;i++){
        TxBuf[12+i] = _broadcastID[i];  
    }     
    // CRC

    uint16_t crc16 ;
    int dataSize = TxBufSize-2;
    crc16 = update_crc(0, TxBuf, dataSize);
    TxBuf[TxBufSize-2] = (crc16 & 0x00FF);
    TxBuf[TxBufSize-1] = (crc16>>8) & 0x00FF; 
    
    #if SYNC_READPACKET_DEBUG_PACKETONLY
    printf("\n\n        Complete Packet to send of %d elements\n", TxBufSize);
    for (int i=0; i<TxBufSize ; i++){  
        printf("\nTxBuf[%d] = %02x ",i,TxBuf[i]); 
    }
    printf("\n          SYNC READ PACKET     \n");
    for (int i=0; i<TxBufSize ; i++){  
        printf("|%02x",TxBuf[i]); 
    }
    printf("\n               \n");
    #endif  

    _pCommLayer->flush();
    _pCommLayer->write(TxBuf,TxBufSize);   // UART-write
 
    wait_us(200);

    _pCommLayer->read_timeout(Status, (11+bytes)*_Nmotor, 2.0);
    

    
    // Take data from 8th cell of status array
    // first byte contain error code, for this we use (bytes+1)   
    for (int i=0; i<(11+bytes)*_Nmotor ; i++){ 
            data[i] = Status[i];
    } 
    

    
    #if SYNC_READPACKET_DEBUG_PACKETONLY
    printf("\n          SYNC-READ (entire buffer RAW values)\n");
    for (int i=0; i<(11+bytes)*_Nmotor ; i++){ 
        printf("Status[%d]:%02x\n",i,Status[i]);
    }
    #endif 
    
    //return(data);                              // return error code
}


///////////////////////////////////////////////////////////////////////////////
////////////////////////SINGLE OPERATIONS//////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////


int MX::SetGoalSpeed(int speed, int flags) {

    char reg_flag = 0;
    char data[4];

    // set the flag is only the register bit is set in the flag
    if (flags == 0x2) {
        reg_flag = 1;
    }

    int goal = (speed) ;

    data[0] = goal & 0xff;          // bottom 8 bits
    data[1] = goal >> 8 & 0xff;     // top 8 bits
    data[2] = goal >> 16 & 0xff;    // top 8 bits
    data[3] = goal >> 24 & 0xff;    // top 8 bits
    
    // write the packet, return the error code
    int rVal = sendPacket( MX_REG_GOAL_VELOCITY, 4, data, reg_flag);

    if (flags == 1) {
        // block until it comes to a halt
        while (isMoving()) {}
    }
    
#if SETGOAL_SPEED_DEBUG
int16_t sp = speed * float(234.27/1023); //rev/min
printf("\nSetGoal to:  %d Velocity in [rev/min]%d \n" ,speed,sp);
printf("Goal L: 0x%02x ; H: 0x%02x\n",data[0],data[1]);
#endif

    return(rVal);
}


int MX::SetGoal(float degrees, int flags) {

    char reg_flag = 0;
    char data[4];

    // set the flag is only the register bit is set in the flag
    if (flags == 0x2) {
        reg_flag = 1;
    }

    int goal = (degrees) * (float)(4095/360);

    data[0] = goal & 0xff; // bottom 8 bits
    data[1] = goal >> 8 & 0xff;   // top 8 bits
    data[2] = goal >> 16 & 0xff;   // top 8 bits
    data[3] = goal >> 24 & 0xff;   // top 8 bits
    
    // write the packet, return the error code
    int rVal = sendPacket( MX_REG_GOAL_POSITION, 4, data, reg_flag );

    if (flags == 1) {
        // block until it comes to a halt
        while (isMoving()) {}
    }
    
#if SETGOAL_DEBUG
printf("\n  SetGoal to:  %d in degree is: %f\n",goal,degrees);
printf("  Goal L: 0x%02x ; H: 0x%02x\n",data[0],data[1]);
#endif
    return(rVal);
}

// if flag[0] is set, were blocking
// if flag[1] is set, we're registering
// they are mutually exclusive operations

int MX::OperatingMode(int mode) {

    char data[1];                
         data[0] = mode;          // bottom 8 bits
    
#if OPERATING_MODE_DEBUG
    printf("\nOPERATING_MODE_DEBUG\n");
    printf("Set Operating Mode value to: 0x%02x\n",mode);
    printf( "*    0x00 =    Current Control Mode\n"
            "*    0x01 =    Velocity Control Mode\n"
            "*    0x03 =    Position Control Mode (DEFAULT)\n"
            "*    0x04 =    Extended Position Control Mode(Multi-turn)\n"
            "*    0x05 =    Current-based Position Control Mode\n"
            "*    0x16 =    PWM Control Mode (Voltage Control Mode)\n");
#endif 

       //sendPacket(Motor ID, Address, Lenght, data);       
       //return give back a error code of sendPacket function 
    return (sendPacket(  MX_REG_OPERATING_MODE, 1, data));
}


// return 1 is the servo is still in flight
bool MX::isMoving(void) {

    bool data[1];
         data[0] = 1;
    data[0] = readPacket( MX_REG_MOVING,1 );
    return(data[0]);
}


int MX::motorSetBaud (int MotorBaud) {

    char data[1];
         data[0] = MotorBaud;

#if SETBAUD_DEBUG 
    printf("\nSTATUS Packet - SETBAUD_DEBUG\n");
    printf("Set Baud rate value to: 0x%02x\n",MotorBaud);
    printf( "*    0x00 =     9,600  bps \n"
            "*    0x01 =    57,600  bps (DEFAULT)\n"
            "*    0x02 =    115,200 bps \n"
            "*    0x03 =    1       Mbps \n"
            "*    0x04 =    2       Mbps \n"
            "*    0x05 =    3       Mbps \n"
            "*    0x06 =    4       Mbps \n"
            "*    0x06 =    4,5     Mbps \n");
#endif 

       //sendPacket(Motor ID, Address, Lenght, data);       
       //return give back a error code of sendPacket function 
    return (sendPacket(  MX_REG_BAUD, 1, data));
}

void MX::Reboot() {

    char TxBuf[10];
    char Status[11];
    Status[8]=0x00; //The error is set to zero

    // Build the TxPacket first in RAM, then we'll send in one go
    TxBuf[0] = 0xff;        //H1
    TxBuf[1] = 0xff;        //H2
    TxBuf[2] = 0xfd;        //H3
    TxBuf[3] = 0x00;        //Reserved
    TxBuf[4] = _ID;         //ID
    // packet Length
    TxBuf[5] = 0x03;        //packet length low
    TxBuf[6] = 0x00;        //packet length high
    // Instruction
    TxBuf[7] = 0x08;        // Instruction to reboot Device 
    /*****************CRC***********************/
    uint16_t crc16 ;
    int dataSize = sizeof(TxBuf)-2;
    crc16 = update_crc(0, TxBuf, dataSize /*5+bytes*/);  
    TxBuf[8] = (crc16 & 0x00FF);
    TxBuf[9] = (crc16>>8) & 0x00FF; 
// Build the TxPacket first in RAM, then we'll send in one go
    _pCommLayer->flush();
    _pCommLayer->write(TxBuf,10);   // UART-write 
    _pCommLayer->read_timeout(Status, 11, 2.0);  
    
#if REBOOT_ENABLE_DEBUG
    printf("\n Reboot Motor: (%d)",enableVal);
#endif
}    
    

int MX::TorqueEnable(bool enableVal) {

    char data[1];
         data[0] = enableVal;
    
#if TORQUE_ENABLE_DEBUG
    printf("\n  Setting Torque Enable value: (%d)",enableVal);
#endif

    return (sendPacket(  MX_REG_TORQUE_ENABLE, 1, data));
}


float MX::GetPosition(void) {
printf("\nGET POSITION ");
    char* data;
    int32_t position;
    float angle = 0;
    float ScaleFactor = (float)360/4095;  
    
    data = readPacket( MX_REG_PRESENT_POSITION, 4);
    position  = (uint32_t)data[3] << 24;
    position |= (uint32_t)data[2] << 16;
    position |= (uint32_t)data[1] << 8;
    position |= (uint32_t)data[0];
    // angle(degree) obtained from position(0 - 4095)
    angle = (float)position*ScaleFactor;
    
#if GETPOSITION_DEBUG
    printf("\nGetPosition from ID: %d\n",_ID);    
    for (uint16_t i=0; i<4 ; i++) {
        printf("  Data[%d]       : 0x%02x\n",(i+1),data[i]);
    }        
    printf("  Read position (0 - 4095): %d\n",position);
    printf("  Converted angle %f\n",angle);
#endif      
    return (angle);
}


int MX::sendPacket( int start, int bytes, char* data, int flag) {

    char TxBuf[12+bytes];
    char Status[11];
    Status[8]=0x00; //The error is set to zero

    // Build the TxPacket first in RAM, then we'll send in one go
    TxBuf[0] = 0xff;        //H1
    TxBuf[1] = 0xff;        //H2
    TxBuf[2] = 0xfd;        //H3
    TxBuf[3] = 0x00;        //Reserved
    TxBuf[4] = _ID;         //ID
    // packet Length
    TxBuf[5] = (5+bytes) & 0xff;    //packet length low
    TxBuf[6] = (5+bytes) >> 8;      //packet length high
    // Instruction
    if (flag == 1) {
        TxBuf[7]=0x04;
    } else {
        TxBuf[7]=0x03;
    }
    // Start Address
    TxBuf[8] = start & 0xFF;
    TxBuf[9] = start >> 8;
    // data
    for (int i = bytes-1; i>=0 ; i--) {      //little endian
        TxBuf[10+i] = data[i];
    }
   /*****************CRC***********************/
    uint16_t crc16 ;
    int dataSize = sizeof(TxBuf)-2;
    crc16 = update_crc(0, TxBuf, dataSize /*5+bytes*/);
  
    TxBuf[10+bytes] = (crc16 & 0x00FF);
    TxBuf[11+bytes] = (crc16>>8) & 0x00FF; 
// Build the TxPacket first in RAM, then we'll send in one go
    _pCommLayer->flush();
    _pCommLayer->write(TxBuf,bytes+12); // UART-write 
    _pCommLayer->read_timeout(Status, 11, 2.0);

 
#if SENDPACKET_DEBUG
    printf("\nWRITE input parameters:\n");
    printf(" (ID: %d, Address: 0x%x, Bytes: %d, flag: %d)\n",_ID,start,bytes,flag); 
    printf(" Data written:\n");   
    for (int i=0; i < bytes ; i++) {
            printf("  Data[%d]: 0x%x\n",i,data[i]);
        }
#endif
    
#if SENDPACKET_DEBUG_INSTRUCTION_PKT
    printf("\nINSTRUCTIONS Packet - WRITE_DEBUG \n");
    printf("  H1            : 0x%02x\n",TxBuf[0]);
    printf("  H2            : 0x%02x\n",TxBuf[1]);
    printf("  H3            : 0x%02x\n",TxBuf[2]);
    printf("  Reserved      : 0x%02x\n",TxBuf[3]);
    printf("  ID            : 0x%02x\n",TxBuf[4]);
    printf("  Length L      : 0x%02x\n",TxBuf[5]);
    printf("  Length H      : 0x%02x\n",TxBuf[6]);
    printf("  Instruction   : 0x%02x\n",TxBuf[7]);
    printf("  Cmd L         : 0x%02x\n",TxBuf[8]);
    printf("  Cmd H         : 0x%02x\n",TxBuf[9]);
    for (uint16_t i=0; i<bytes ; i++) {
        printf("  Data          : 0x%02x\n",TxBuf[10+i]);
    }
    printf("  CRC1          : 0x%02x\n",TxBuf[10+bytes]);
    printf("  CRC2          : 0x%02x\n",TxBuf[11+bytes]);
    printf("  TxBuf = ");
    for (int i = 0; i < sizeof(TxBuf) ; i++) {               
        printf("  [0x%02x]",TxBuf[i]);
    }
    printf("\n");
#endif
    
#if SENDPACKET_DEBUG_STATUS_PKT
    printf("\nSTATUS Packet - WRITE_DEBUG\n");
    printf("  H1            : 0x%02x\n",Status[0]);
    printf("  H2            : 0x%02x\n",Status[1]);
    printf("  H3            : 0x%02x\n",Status[2]);
    printf("  Reserved      : 0x%02x\n",Status[3]);
    printf("  ID            : 0x%02x\n",Status[4]);
    printf("  Length L      : 0x%02x\n",Status[5]);
    printf("  Length H      : 0x%02x\n",Status[6]);
    printf("  Instruction   : 0x%02x\n",Status[7]);
    printf("  Error         : 0x%02x\n",Status[8]);
    printf("  CRC1          : 0x%02x\n",Status[9]);
    printf("  CRC2          : 0x%02x\n",Status[10]);
    printf("  Status = ");
    for (int i = 0; i < sizeof(Status) ; i++) {               
        printf("  [0x%02x]",Status[i]);
    }
    printf("\n");
#endif

 return(Status[8]); // return error code
}



char* MX::readPacket(int start, int bytes, int flag) {

    char TxBuf[14];
    char Status[11+bytes];
    char* data;
    Status[8] = 0x00;       //The error is set to zero

    // Build the TxPacket (FIXED !) first in RAM, then we'll send in one go
    TxBuf[0] = 0xff;            //H1
    TxBuf[1] = 0xff;            //H2
    TxBuf[2] = 0xfd;            //H3
    TxBuf[3] = 0x00;            //Reserved
    TxBuf[4] = _ID;             //ID
    TxBuf[5] = 0x07;            //packet length low
    TxBuf[6] = 0x00;            //packet length high        
    TxBuf[7] = 0x02;            // Instruction     
    TxBuf[8] = start & 0xFF;    // Start Address
    TxBuf[9] = start >> 8;      
    // N param 
    TxBuf[10] = 0x04;
    TxBuf[11] = 0x00;
   /*****************CRC***********************/
    uint16_t crc16 ;
    int dataSize = sizeof(TxBuf)-2;
    crc16 = update_crc(0, TxBuf, dataSize);
    TxBuf[12] = (crc16 & 0x00FF);
    TxBuf[13] = (crc16>>8) & 0x00FF; 

    _pCommLayer->flush();
    _pCommLayer->write(TxBuf,sizeof(TxBuf));   // UART-write 
    wait(0.0002);
    _pCommLayer->read_timeout(Status, 11+bytes, 2.0);
   
   
#if MX_READPACKET_DEBUG
    printf("\nREAD input parameters:\n");
    printf(" (ID: %d, Address: 0x%x, Bytes: %d, flag: %d)\n",_ID,start,bytes,flag); 
    printf(" Data written:\n");   
    for (int i=0; i < bytes ; i++) {
            printf("  Data[%d]: 0x%x\n",i,data[i]);
        }
#endif
    
#if MX_READPACKET_DEBUG_INSTRUCTION_PKT
    printf("\nINSTRUCTIONS Packet - READ_DEBUG \n");
    printf("  H1 - Header       : 0x%02x\n",TxBuf[0]);
    printf("  H2 - Header       : 0x%02x\n",TxBuf[1]);
    printf("  H3 - Header       : 0x%02x\n",TxBuf[2]);
    printf("  RESERVED          : 0x%02x\n",TxBuf[3]);
    printf("  ID                : 0x%02x\n",TxBuf[4]);
    printf("  Length L          : 0x%02x\n",TxBuf[5]);
    printf("  Length H          : 0x%02x\n",TxBuf[6]);
    printf("  Instruction       : 0x%02x\n",TxBuf[7]);
    printf("  Param1 - Cmd L    : 0x%02x\n",TxBuf[8]);
    printf("  Param2 - Cmd H    : 0x%02x\n",TxBuf[9]);
    printf("  Param3            : 0x%02x\n",TxBuf[10]);
    printf("  Param4            : 0x%02x\n",TxBuf[11]);
    printf("  CRC1              : 0x%02x\n",TxBuf[12]);
    printf("  CRC2              : 0x%02x\n",TxBuf[13]);
    printf("  TxBuf = ");
    for (int i = 0; i < 14 ; i++) {               
        printf("  [0x%02x]",TxBuf[i]);
    }
    printf("\n\n");
#endif

#if MX_READPACKET_DEBUG_STATUS_PKT
    printf("\nSTATUS Packet - READ_DEBUG \n");
    printf("  H1 - Header   : 0x%02x\n",Status[0]);
    printf("  H2 - Header   : 0x%02x\n",Status[1]);
    printf("  H3 - Header   : 0x%02x\n",Status[2]);
    printf("  Reserved      : 0x%02x\n",Status[3]);
    printf("  ID            : 0x%02x\n",Status[4]);
    printf("  Length L      : 0x%02x\n",Status[5]);
    printf("  Length H      : 0x%02x\n",Status[6]);
    printf("  Instruction   : 0x%02x\n",Status[7]);
    printf("  Error         : 0x%02x\n",Status[8]);
    for (uint16_t i=0; i<bytes ; i++) {
        printf("  Param%d        : 0x%02x\n",(i+1),Status[9+i]);
    }
    printf("  Crc1          : 0x%02x\n",Status[13]);
    printf("  Crc2          : 0x%02x\n",Status[14]);
    printf("  Status = ");    
        for (int i = 0; i < sizeof(Status) ; i++) {               
        printf("  [0x%02x]",Status[i]);
    }
    printf("\n");
#endif
    for (uint16_t i=0; i<bytes ; i++) {
        data[i] = Status[9+i];
    }
    return(data); // return error code
}

unsigned short MX::update_crc(unsigned short crc_accum,  char *data_blk_ptr, unsigned short data_blk_size)
{
    unsigned short i, j;
    unsigned short crc_table[256] = {
        0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
        0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
        0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
        0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
        0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
        0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
        0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
        0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
        0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
        0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
        0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
        0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
        0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
        0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
        0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
        0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
        0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
        0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
        0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
        0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
        0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
        0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
        0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
        0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
        0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
        0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
        0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
        0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
        0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
        0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
        0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
        0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
    };
    for(j = 0; j < data_blk_size; j++)
    {
        i = ((unsigned short)(crc_accum >> 8) ^ data_blk_ptr[j]) & 0xFF;
        crc_accum = (crc_accum << 8) ^ crc_table[i];
    }
    return crc_accum;
}