LIGHT2

Dependencies:   FastPWM mbed

main.cpp

Committer:
Lightvalve
Date:
2020-12-20
Revision:
198:bc4dfecb8e32
Parent:
197:50e95ba0ade2
Child:
199:ee79b4692e3b

File content as of revision 198:bc4dfecb8e32:

//201220_1_with_delay
#include "mbed.h"
#include "FastPWM.h"
#include "INIT_HW.h"
#include "function_CAN.h"
#include "SPI_EEP_ENC.h"
#include "I2C_AS5510.h"
#include "setting.h"
#include "function_utilities.h"
#include "stm32f4xx_flash.h"
#include "FlashWriter.h"
#include <string>
#include <iostream>
#include <cmath>

using namespace std;
Timer t;

///191008////

// dac & check ///////////////////////////////////////////
DigitalOut check(PC_2);
DigitalOut check_2(PC_3);
AnalogOut dac_1(PA_4);
AnalogOut dac_2(PA_5);
AnalogIn adc1(PC_4); //pressure_1
AnalogIn adc2(PB_0); //pressure_2
AnalogIn adc3(PC_1); //current


// PWM ///////////////////////////////////////////
float dtc_v=0.0f;
float dtc_w=0.0f;

// I2C ///////////////////////////////////////////
I2C i2c(PC_9,PA_8); // SDA, SCL (for K22F)
const int i2c_slave_addr1 =  0x56;
unsigned int value; // 10bit output of reading sensor AS5510

// SPI ///////////////////////////////////////////
SPI eeprom(PB_15, PB_14, PB_13); // EEPROM //(SPI_MOSI, SPI_MISO, SPI_SCK);
DigitalOut eeprom_cs(PB_12);
//FlashWriter writer(6);//2부터 7까지 되는듯 아마 sector
SPI enc(PC_12,PC_11,PC_10);
DigitalOut enc_cs(PD_2);
DigitalOut LED(PA_15);

// UART ///////////////////////////////////////////
Serial pc(PA_9,PA_10); //  _ UART

// CAN ///////////////////////////////////////////
CAN can(PB_8, PB_9, 1000000);
CANMessage msg;
void onMsgReceived()
{
    CAN_RX_HANDLER();
}

// Variables ///////////////////////////////////////////
State pos;
State vel;
State Vout;
State torq;
State pres_A;
State pres_B;
State cur;
State valve_pos;

State INIT_Vout;
State INIT_Valve_Pos;
State INIT_Pos;
State INIT_torq;

extern int CID_RX_CMD;
extern int CID_RX_REF_POSITION;
extern int CID_RX_REF_VALVE_POS;
extern int CID_RX_REF_PWM;

extern int CID_TX_INFO;
extern int CID_TX_POSITION;
extern int CID_TX_TORQUE;
extern int CID_TX_PRES;
extern int CID_TX_VOUT;
extern int CID_TX_VALVE_POSITION;




// =============================================================================
// =============================================================================
// =============================================================================

/*******************************************************************************
 *  REFERENCE MODE
 ******************************************************************************/
enum _REFERENCE_MODE {
    MODE_REF_NO_ACT = 0,                                //0
    MODE_REF_DIRECT,                                //1
    MODE_REF_COS_INC,                                  //2
    MODE_REF_LINE_INC,                                 //3
    MODE_REF_SIN_WAVE,                                  //4
    MODE_REF_SQUARE_WAVE,                                  //5
};

/*******************************************************************************
 *  CONTROL MODE
 ******************************************************************************/
enum _CONTROL_MODE {
    //control mode
    MODE_NO_ACT = 0,                                    //0
    MODE_VALVE_POSITION_CONTROL,                        //1
    MODE_JOINT_CONTROL,                                 //2

    MODE_VALVE_OPEN_LOOP,                               //3
    MODE_JOINT_ADAPTIVE_BACKSTEPPING,                   //4
    MODE_RL,                                            //5

    MODE_JOINT_POSITION_PRES_CONTROL_PWM,               //6
    MODE_JOINT_POSITION_PRES_CONTROL_VALVE_POSITION,    //7
    MODE_VALVE_POSITION_PRES_CONTROL_LEARNING,          //8

    MODE_TEST_CURRENT_CONTROL,                          //9
    MODE_TEST_PWM_CONTROL,                              //10

    MODE_CURRENT_CONTROL,                               //11
    MODE_JOINT_POSITION_TORQUE_CONTROL_CURRENT,         //12
    MODE_JOINT_POSITION_PRES_CONTROL_CURRENT,           //13
    MODE_VALVE_POSITION_TORQUE_CONTROL_LEARNING,                                            //14

    //utility
    MODE_TORQUE_SENSOR_NULLING = 20,                    //20
    MODE_VALVE_NULLING_AND_DEADZONE_SETTING,            //21
    MODE_FIND_HOME,                                     //22
    MODE_VALVE_GAIN_SETTING,                            //23
    MODE_PRESSURE_SENSOR_NULLING,                       //24
    MODE_PRESSURE_SENSOR_CALIB,                         //25
    MODE_ROTARY_FRICTION_TUNING,                        //26

    MODE_DDV_POS_VS_PWM_ID = 30,                           //30
    MODE_DDV_DEADZONE_AND_CENTER,                       //31
    MODE_DDV_POS_VS_FLOWRATE,                           //32
    MODE_SYSTEM_ID,                                     //33
    MODE_FREQ_TEST,                                     //34
    MODE_SEND_BUFFER,                                   //35
    MODE_SEND_OVER,                                     //36
    MODE_STEP_TEST,                                     //37
};

void SystemClock_Config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

    /** Configure the main internal regulator output voltage
    */
    __HAL_RCC_PWR_CLK_ENABLE();
    __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
    /** Initializes the CPU, AHB and APB busses clocks
    */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
    RCC_OscInitStruct.PLL.PLLM = 8;//8
    RCC_OscInitStruct.PLL.PLLN = 180; //180
    RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
    RCC_OscInitStruct.PLL.PLLQ = 2;
    RCC_OscInitStruct.PLL.PLLR = 2;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
        //Error_Handler();
    }
    /** Activate the Over-Drive mode
    */
    if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
        //Error_Handler();
    }
    /** Initializes the CPU, AHB and APB busses clocks
    */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                                  |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) {
        //Error_Handler();
    }
}

float u_past[num_array_u_past] = {0.0f};
float x_past[num_array_x_past] = {0.0f};
float x_future[num_array_x_future] = {0.0f};
float f_past[num_array_f_past] = {0.0f};
float f_future[num_array_f_future] = {0.0f};

float input_NN[num_input] = { 0.0f };

const float h1[num_input][16] = {
    {-2.492051839828491f,2.4516725540161133f,0.12903714179992676f,-2.490757465362549f,-2.6756582260131836f,2.4281091690063477f,-0.25895145535469055f,-0.2330438494682312f,-0.3288726806640625f,1.7969430685043335f,0.33044230937957764f,-2.8259778022766113f,-2.8330631256103516f,0.2416958063840866f,-0.2571594715118408f,2.2232203483581543f},
{-1.3854602575302124f,1.5994855165481567f,-0.3927857577800751f,-1.091575026512146f,-1.0983558893203735f,1.2194273471832275f,-0.48985767364501953f,0.4625398814678192f,-0.4161548912525177f,0.5750619173049927f,0.15368761122226715f,-1.7419500350952148f,-0.9391921162605286f,-0.31723925471305847f,-0.20967772603034973f,1.1359047889709473f},
{-1.0888410806655884f,1.1380627155303955f,0.36391180753707886f,-0.8528419137001038f,-0.5124239325523376f,1.0754810571670532f,0.20260077714920044f,0.02969699166715145f,-0.11756117641925812f,-0.3696632981300354f,-0.27259182929992676f,-1.1658742427825928f,-0.43726029992103577f,0.14137530326843262f,0.05590221285820007f,0.6036397814750671f},
{-0.5521246790885925f,0.10764690488576889f,0.39742106199264526f,0.14577916264533997f,-0.3091053068637848f,0.17434029281139374f,-0.20044343173503876f,-0.68796306848526f,0.6097877621650696f,-0.42812103033065796f,0.050127483904361725f,0.2115311473608017f,-0.007273299619555473f,0.029505113139748573f,-0.2961459457874298f,0.5710861682891846f},
{1.207394003868103f,-1.1674365997314453f,-0.0051451027393341064f,1.0202738046646118f,0.7490691542625427f,-0.9034024477005005f,0.04487033560872078f,-0.9898844957351685f,0.7452301979064941f,-0.47734594345092773f,0.24034416675567627f,1.5481359958648682f,1.1834068298339844f,0.14985936880111694f,-0.3865056037902832f,-0.9457556009292603f},
{4.191114902496338f,-4.077197074890137f,0.21773302555084229f,3.4757556915283203f,4.026125907897949f,-4.04514217376709f,0.0805748701095581f,1.4911282062530518f,-0.10712718218564987f,-0.8101842999458313f,-0.6279340982437134f,4.144664287567139f,3.1387953758239746f,0.27788639068603516f,-0.4132833778858185f,-3.7526161670684814f},
{0.05604593828320503f,-0.5269882678985596f,-0.2501986622810364f,0.8053929209709167f,-0.508767306804657f,1.2673035860061646f,0.1702369749546051f,0.41742753982543945f,3.923818349838257f,2.9203224182128906f,4.625209808349609f,0.8557388782501221f,0.5013881325721741f,0.2669181227684021f,-0.15618428587913513f,-1.7190253734588623f},
{-0.29786035418510437f,-0.6146117448806763f,-0.26619744300842285f,-0.35863757133483887f,-0.8377414345741272f,-0.29022303223609924f,-0.078120656311512f,-5.662913799285889f,-3.735013008117676f,-3.5222713947296143f,0.5320702791213989f,-0.01984715275466442f,-0.2300022393465042f,0.02583559788763523f,0.04303058981895447f,2.2264418601989746f},
{-0.005315178073942661f,0.4084877669811249f,0.10248100757598877f,-0.049130890518426895f,-0.10337845981121063f,0.180928573012352f,0.02361851930618286f,-2.048043727874756f,-3.8224282264709473f,-0.7895442247390747f,-0.5650206208229065f,0.23716439306735992f,2.640312433242798f,0.10206064581871033f,-0.30555272102355957f,0.07618159055709839f},
{0.10099751502275467f,-0.398851603269577f,0.18462657928466797f,0.40458497405052185f,0.5282383561134338f,0.2875088155269623f,-0.20621144771575928f,0.8464758396148682f,-2.340078592300415f,3.711749792098999f,-6.100204944610596f,-0.5303384065628052f,3.87209153175354f,-0.31372106075286865f,0.3484981060028076f,-0.9589624404907227f},
{0.3724943995475769f,0.2132701277732849f,0.37182438373565674f,1.3321770429611206f,0.3190871775150299f,0.08779194951057434f,-0.11073392629623413f,0.04808827489614487f,4.836231708526611f,1.5474936962127686f,2.618411064147949f,-0.7479416728019714f,-2.667581081390381f,-0.07993866503238678f,0.26688337326049805f,0.20610198378562927f},
{-0.21814200282096863f,-0.21748900413513184f,-0.40320003032684326f,0.39444229006767273f,0.3996942639350891f,-0.23974381387233734f,0.24927140772342682f,0.42778199911117554f,-1.496774673461914f,-0.9519236087799072f,-0.2538074254989624f,-0.045760106295347214f,-0.03449362516403198f,-0.08651508390903473f,0.10493969917297363f,-0.2107759714126587f},
{-0.10616457462310791f,0.05422089993953705f,0.19847965240478516f,0.3579346239566803f,0.19547772407531738f,-0.13439396023750305f,-0.14413191378116608f,-0.09275151789188385f,-0.12082389742136002f,-3.9278764724731445f,-0.8460808396339417f,-0.00010032631689682603f,-0.6260793209075928f,-0.05694044753909111f,-0.22268100082874298f,-0.3159164488315582f},
{-0.06967504322528839f,0.18296405673027039f,0.4127817749977112f,0.21173477172851562f,0.03739193454384804f,-0.2718232572078705f,-0.22765624523162842f,0.0479109026491642f,-0.8458966016769409f,-2.188527822494507f,-0.5611924529075623f,0.03390118479728699f,-0.6283928155899048f,-0.14168457686901093f,0.0479682981967926f,0.0000061300816014409065f},
{0.05417802184820175f,0.03646376356482506f,0.20282304286956787f,0.14569750428199768f,0.0335032157599926f,-0.05122561752796173f,0.13000749051570892f,-0.057157427072525024f,0.7048590779304504f,2.26005220413208f,0.2068970799446106f,-0.133168026804924f,0.2436632364988327f,-0.13851526379585266f,0.0668090283870697f,0.3664224445819855f},
{0.06464312970638275f,-0.045170340687036514f,-0.40439701080322266f,-0.11053092777729034f,-0.015158046968281269f,0.16447672247886658f,-0.07142936438322067f,0.15182127058506012f,-0.13264119625091553f,-0.23641446232795715f,0.4588874280452728f,-0.011651065200567245f,0.040492258965969086f,-0.09876388311386108f,-0.08245879411697388f,0.03925871476531029f},
{-0.02269779145717621f,0.059974778443574905f,0.16706281900405884f,0.46414104104042053f,-0.21328707039356232f,-0.45228299498558044f,0.041288089007139206f,0.06836040318012238f,-0.32144632935523987f,0.8764961957931519f,-0.4899333417415619f,-0.17487938702106476f,-0.3217511773109436f,0.24882397055625916f,0.29427415132522583f,-0.017587721347808838f},
};

const float h2[16][16] = {
    {3.0738728046417236f,1.559771180152893f,-0.19042335450649261f,0.3914716839790344f,-0.21907491981983185f,1.6640474796295166f,0.13948610424995422f,-0.08634524047374725f,-0.5460954904556274f,-0.2652187943458557f,0.06963741779327393f,-3.5057811737060547f,-0.0956161767244339f,-5.765225887298584f,-0.46290507912635803f,5.082071304321289f},
{-2.4444243907928467f,1.0142027139663696f,-0.07617853581905365f,-2.0465540885925293f,-0.35503754019737244f,0.25830844044685364f,-0.33918139338493347f,-0.42322224378585815f,-0.4216797351837158f,0.22551164031028748f,0.9671986103057861f,0.11130780726671219f,0.07124756276607513f,1.1827691793441772f,-2.5495834350585938f,-2.0869014263153076f},
{-0.22745239734649658f,0.003037691116333008f,-0.061119019985198975f,0.35696902871131897f,0.05568113923072815f,0.011741191148757935f,-0.20225946605205536f,-0.08465918898582458f,0.3489862382411957f,0.0687277615070343f,0.31964078545570374f,0.3004753887653351f,0.36063823103904724f,-0.42892736196517944f,0.08652284741401672f,0.027493387460708618f},
{0.23199157416820526f,-1.7880792617797852f,-0.2894435524940491f,1.9215139150619507f,0.08946844935417175f,0.49931082129478455f,-0.38759845495224f,0.12227743119001389f,0.18804843723773956f,0.08531558513641357f,-0.34142476320266724f,1.4358174800872803f,-0.5422481894493103f,-0.29128965735435486f,1.0840681791305542f,-0.26147159934043884f},
{0.3284909129142761f,0.8169353604316711f,-0.3847824037075043f,0.16119417548179626f,0.036378175020217896f,2.1914660930633545f,-0.23565807938575745f,-0.4117702841758728f,-0.08101971447467804f,-0.5542977452278137f,1.027921438217163f,-0.36246106028556824f,-0.14990541338920593f,-1.1903846263885498f,-0.23719990253448486f,0.7545689344406128f},
{1.9852561950683594f,1.632697582244873f,-0.4675808250904083f,1.9349418878555298f,-0.3015052080154419f,-0.8486825227737427f,-0.581864058971405f,-0.35089632868766785f,-0.3620368242263794f,0.12058626860380173f,0.7981455326080322f,-1.856131911277771f,-0.4701657295227051f,1.799214482307434f,1.8555665016174316f,-2.1990392208099365f},
{-0.24421502649784088f,0.046817418187856674f,-0.3260969817638397f,0.1517666131258011f,-0.38453540205955505f,-0.17000475525856018f,0.285016268491745f,0.12387624382972717f,-0.0982072651386261f,0.13111665844917297f,0.04020293802022934f,-0.32796353101730347f,-0.21546880900859833f,-0.023107079789042473f,-0.3091234266757965f,-0.3402748107910156f},
{0.57220059633255f,0.29739347100257874f,0.19632335007190704f,0.008231665939092636f,-0.14358049631118774f,0.15171869099140167f,-0.09043094515800476f,-0.33494824171066284f,0.17879262566566467f,-0.37898191809654236f,-0.6580735445022583f,0.7165367603302002f,-0.4525156617164612f,0.18532223999500275f,-3.5652143955230713f,-0.3483140468597412f},
{-0.2703920006752014f,-0.9304926991462708f,-0.24047645926475525f,0.7930152416229248f,0.041274964809417725f,-0.2867431938648224f,-0.10284432768821716f,-0.11999508738517761f,-0.003526973305270076f,-0.38046833872795105f,-0.7273960709571838f,-1.1637976169586182f,-0.527924656867981f,-0.1207299679517746f,-7.605639934539795f,0.2445993423461914f},
{0.7996191382408142f,0.2623150646686554f,-0.13502129912376404f,-0.9202054142951965f,0.12987366318702698f,0.021906832233071327f,0.11923511326313019f,-0.4247411787509918f,0.006385833024978638f,0.16225893795490265f,0.4018360376358032f,0.06512869894504547f,0.09138336032629013f,0.0027437149547040462f,0.7030954360961914f,-0.19797562062740326f},
{-0.2666815221309662f,-1.1443369388580322f,0.0457797646522522f,-0.4290945529937744f,-0.03321319818496704f,0.20285262167453766f,0.032027360051870346f,-0.18001338839530945f,-0.15919113159179688f,-0.10972582548856735f,-2.9048874378204346f,1.0889835357666016f,-0.5255591869354248f,0.11027144640684128f,-0.26261255145072937f,0.13390804827213287f},
{1.5477468967437744f,0.9449147582054138f,0.26128989458084106f,-2.6026813983917236f,0.0033026933670043945f,-0.4747174382209778f,-0.33315056562423706f,-0.19110865890979767f,0.20550130307674408f,-0.5178285837173462f,-1.4446262121200562f,-2.590667963027954f,-0.1823829710483551f,-2.3793771266937256f,0.9905255436897278f,1.8419498205184937f},
{-0.7309730052947998f,-2.024406909942627f,-0.15798500180244446f,-0.25766730308532715f,-0.37393757700920105f,0.033240195363759995f,-0.03676166385412216f,-0.41733694076538086f,-0.3764709532260895f,0.058458827435970306f,-0.8576257228851318f,-0.20987293124198914f,0.28012609481811523f,-0.1621398627758026f,-1.3118759393692017f,0.440889447927475f},
{-0.2527315020561218f,0.2273571640253067f,-0.2018718123435974f,-0.22529835999011993f,0.07545611262321472f,-0.08787805587053299f,-0.11297860741615295f,-0.25671717524528503f,-0.24509364366531372f,0.19522181153297424f,0.24586385488510132f,-0.28716936707496643f,-0.04067717865109444f,0.3425101041793823f,-0.1104995459318161f,-0.12887412309646606f},
{0.4138670265674591f,0.1604653298854828f,0.056746453046798706f,0.036025404930114746f,0.3228367865085602f,-0.07083973288536072f,0.018455177545547485f,0.0059362053871154785f,0.40515169501304626f,0.014240056276321411f,-0.07738298177719116f,0.1407785713672638f,-0.13024571537971497f,-0.29546058177948f,-0.11976784467697144f,-0.35825538635253906f},
{-2.6995644569396973f,0.1426059901714325f,-0.003839129814878106f,-0.6525433659553528f,0.29976895451545715f,0.08217727392911911f,-0.25857430696487427f,0.20994558930397034f,-0.5427520871162415f,-0.17481258511543274f,-0.4742678105831146f,0.7741270661354065f,-0.46939387917518616f,0.4754415452480316f,-0.05948866903781891f,0.06004064157605171f},
};

const float h3[16][16] = {
    {-0.36079341173171997f,0.19902901351451874f,-0.017479311674833298f,-0.7806128263473511f,-1.826728105545044f,0.23857304453849792f,0.740174412727356f,0.2017861008644104f,0.3792732059955597f,-1.0531911849975586f,-0.7588154673576355f,-0.015846818685531616f,-0.8501541018486023f,-0.30473095178604126f,0.007871723733842373f,-0.09860346466302872f},
{0.047732532024383545f,0.021063050255179405f,0.12808172404766083f,0.03686954081058502f,-3.398327112197876f,-0.12904098629951477f,-0.9065544009208679f,-0.0603376105427742f,0.09683269262313843f,-0.9680567383766174f,0.3885401785373688f,-0.40745434165000916f,0.13621456921100616f,0.45660361647605896f,-2.057027816772461f,-0.7064571976661682f},
{0.07903262972831726f,0.2473522275686264f,-0.058172356337308884f,0.04248586297035217f,-0.1806681901216507f,-0.22005361318588257f,-0.4038352966308594f,0.015906542539596558f,0.1806468516588211f,0.030178606510162354f,0.2488909661769867f,0.13805970549583435f,-0.0650925561785698f,-0.22163918614387512f,-0.3036302626132965f,0.054825395345687866f},
{-0.30922991037368774f,-1.023395299911499f,0.2052631825208664f,-4.644917011260986f,-3.3489151000976562f,0.24621817469596863f,-2.0494141578674316f,-0.1963813304901123f,-0.9766215682029724f,-8.70325756072998f,-2.0176901817321777f,-0.005141889210790396f,-0.008450114168226719f,0.03865490108728409f,-0.17401503026485443f,-0.44327670335769653f},
{-0.39607733488082886f,-0.05481579899787903f,0.1976260244846344f,0.022423356771469116f,0.16892847418785095f,-0.27518749237060547f,0.16012099385261536f,0.3626593053340912f,-0.08640444278717041f,-0.11053556203842163f,-0.10529157519340515f,-0.31317979097366333f,-0.1530032455921173f,-0.1336749792098999f,0.22959044575691223f,0.19986507296562195f},
{-0.37449589371681213f,0.7347820997238159f,-0.7467658519744873f,-0.7454975843429565f,0.5573446750640869f,0.4857249855995178f,0.522062361240387f,-0.0946974977850914f,-0.48451560735702515f,-0.027926772832870483f,-0.34000688791275024f,-0.22794345021247864f,0.551361083984375f,0.3427993655204773f,0.9183679223060608f,-0.6474935412406921f},
{0.4110594093799591f,0.2715781033039093f,-0.23423463106155396f,0.37246426939964294f,0.192606121301651f,-0.08329644799232483f,-0.08670487999916077f,-0.25336313247680664f,0.04357413947582245f,-0.06259563565254211f,-0.1344406008720398f,0.35313835740089417f,0.2678389847278595f,0.05402490124106407f,0.24188868701457977f,-0.28574222326278687f},
{-0.40892091393470764f,0.13580100238323212f,-0.5269189476966858f,0.24296578764915466f,0.1986200511455536f,0.08784182369709015f,-0.23312048614025116f,-0.390264093875885f,0.38584989309310913f,-0.1559126079082489f,-0.14134526252746582f,-0.0003446042537689209f,-0.3474012613296509f,-0.19688887894153595f,0.22498734295368195f,-0.03074646182358265f},
{0.10697010159492493f,-0.032194703817367554f,-0.18512000143527985f,0.11056272685527802f,-0.457832396030426f,-0.08291787654161453f,-0.1382003128528595f,0.3493293821811676f,-0.1379433423280716f,-0.18000167608261108f,0.42142823338508606f,-0.3482915461063385f,-0.4284936785697937f,-0.09961219877004623f,0.20204155147075653f,-0.18239720165729523f},
{0.2847062647342682f,0.018552124500274658f,0.1271415501832962f,0.36562982201576233f,-0.09210338443517685f,0.2671583592891693f,0.2430230677127838f,0.2909286320209503f,-0.2802048921585083f,0.18043199181556702f,0.41849127411842346f,-0.287167489528656f,0.30147701501846313f,-0.09805309772491455f,0.1475500762462616f,0.2664158046245575f},
{0.15459725260734558f,0.8468127250671387f,0.5192074775695801f,0.3231939673423767f,-8.05964183807373f,-0.3391801416873932f,1.1652286052703857f,-0.3086276054382324f,0.5984497666358948f,-1.6198935508728027f,2.087207317352295f,-0.5538924932479858f,-0.3962406814098358f,-0.048027459532022476f,0.5870500206947327f,0.09704883396625519f},
{-0.408692330121994f,0.243210107088089f,-0.013073918409645557f,0.5256465077400208f,-0.3921836316585541f,-0.3010461926460266f,-1.416528582572937f,0.21378983557224274f,0.48517918586730957f,-1.8187716007232666f,-0.5715388655662537f,-0.12979117035865784f,-1.0657424926757812f,-0.6168913245201111f,-0.037499845027923584f,0.7113023400306702f},
{-0.2991822361946106f,0.13201937079429626f,0.045195113867521286f,-0.05932474136352539f,0.24825486540794373f,0.07833488285541534f,-0.0513191744685173f,0.34576353430747986f,0.21296781301498413f,-0.35770976543426514f,-0.044228196144104004f,-0.36229726672172546f,0.13522203266620636f,-0.2606737017631531f,0.36124154925346375f,-0.019244026392698288f},
{-0.2675279378890991f,0.9919194579124451f,0.4967791736125946f,0.42134350538253784f,0.4525410234928131f,0.7671056985855103f,-19.65119171142578f,-0.35019630193710327f,0.0774022787809372f,-0.9777984023094177f,0.30070915818214417f,-0.7200683355331421f,0.4576717019081116f,-3.745297908782959f,0.08763853460550308f,-0.12950114905834198f},
{-0.015470266342163086f,-0.663902759552002f,-0.26218274235725403f,-0.9686974287033081f,-1.2697144746780396f,-1.2993874549865723f,-0.368642657995224f,-0.11653367429971695f,0.2285005748271942f,0.8276209831237793f,-1.812983512878418f,-0.3129367232322693f,0.5683643817901611f,0.6947913765907288f,0.2220814824104309f,0.7217218279838562f},
{0.1863725483417511f,1.1391031742095947f,-3.1924281120300293f,-0.17470817267894745f,0.32248324155807495f,-0.45596322417259216f,1.3157312870025635f,-0.0976204127073288f,-0.049222759902477264f,-0.3381028473377228f,-3.256610631942749f,-0.09532349556684494f,0.0486641451716423f,-0.03208383917808533f,0.4447547495365143f,0.9656800031661987f},
};

const float hout[16] = { 0.45773375034332275f,0.12560291588306427f,-0.11175110936164856f,-0.1076873317360878f,-0.22688986361026764f,0.0996299684047699f,-0.1165262907743454f,-0.06413542479276657f,-0.08547917008399963f,-0.10551206022500992f,0.11794675886631012f,-0.051283299922943115f,-0.07513727247714996f,0.10889608412981033f,0.10124985873699188f,-0.09357111901044846f };

const float b1[16] = { 0.2962568402290344f,1.0064163208007812f,-1.7145336866378784f,-0.5373859405517578f,0.8944404125213623f,0.48690545558929443f,-0.14995934069156647f,3.185513973236084f,0.3992059826850891f,-0.3432198166847229f,0.0617363266646862f,0.8845642805099487f,-1.8659136295318604f,-0.9155887365341187f,-1.087764859199524f,0.5785734057426453f };

const float b2[16] = { -0.755774736404419f,-0.5792715549468994f,-1.5842629671096802f,-0.8578898310661316f,-0.6939148902893066f,-0.02991844341158867f,0.30195581912994385f,-0.6438045501708984f,-1.2855838537216187f,-2.1527836322784424f,0.730652928352356f,0.1157657578587532f,-0.3448236882686615f,2.148630142211914f,-0.6408219933509827f,0.5441248416900635f };

const float b3[16] = { -1.963319182395935f,-1.9574757814407349f,2.004293918609619f,2.199665069580078f,-0.4670379161834717f,0.34952792525291443f,-3.200674295425415f,-1.0005841255187988f,0.7618258595466614f,2.12058162689209f,-0.7590987682342529f,-0.37147605419158936f,-0.6215092539787292f,-0.03694118186831474f,-1.5954755544662476f,1.2799572944641113f };

const float bout[1] = { -0.17161530256271362f };


float valve_ref_pos_buffer[10] = {0.0f};

/////////////////////////////////////////////////////////////////////////////////////////////RL
float input_RL[num_input_RL] = { 0.0f };

//Critic Networks
float hc1[num_input_RL][num_hidden_unit1] = {0.0f};
float bc1[num_hidden_unit1] = {0.0f};
float hc2[num_hidden_unit1][num_hidden_unit2] = {0.0f};
float bc2[num_hidden_unit2] = {0.0f};
float hc3[num_hidden_unit2] = {0.0f};
float bc3 = 0.0f;

//Critic Networks Temporary
float hc1_temp[num_input_RL][num_hidden_unit1] = {0.0f};
float bc1_temp[num_hidden_unit1] = {0.0f};
float hc2_temp[num_hidden_unit1][num_hidden_unit2] = {0.0f};
float bc2_temp[num_hidden_unit2] = {0.0f};
float hc3_temp[num_hidden_unit2] = {0.0f};
float bc3_temp = 0.0f;

//Actor Networks
float ha1[num_input_RL][num_hidden_unit1] = {0.0f};
float ba1[num_hidden_unit1] = {0.0f};
float ha2[num_hidden_unit1][num_hidden_unit2] = {0.0f};
float ba2[num_hidden_unit2] = {0.0f};
float ha3[num_hidden_unit2][2] = {0.0f};
float ba3[2] = {0.0f};

//Actor Networks Temporary
float ha1_temp[num_input_RL][num_hidden_unit1] = {0.0f};
float ba1_temp[num_hidden_unit1] = {0.0f};
float ha2_temp[num_hidden_unit1][num_hidden_unit2] = {0.0f};
float ba2_temp[num_hidden_unit2] = {0.0f};
float ha3_temp[num_hidden_unit2][2] = {0.0f};
float ba3_temp[2] = {0.0f};

float VALVE_POS_RAW_NN = 0.0f;
float DDV_JOINT_POS_FF(float REF_JOINT_VEL);

/////////////////////////////////////////////RL tuning
float Gradient_Limit = 0.5f;
float gradient_rate_actor = 0.001f;
float gradient_rate_critic = 0.001f;
//////////////////////////////////////////////////////////////////////////////

float Critic_Network_Temp(float *arr)
{
    float output1[num_hidden_unit1] = { 0.0f };
    float output2[num_hidden_unit2] = { 0.0f };
    float output = 0.0f;
    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            output1[index2] = output1[index2] + hc1_temp[index1][index2] * arr[index1];
        }
        //ReLU
        output1[index2] = output1[index2] + bc1_temp[index2];
        hx_c_sum[index2] = output1[index2];
        if (output1[index2] < 0) {
            output1[index2] = 0;
        }
        //tanh
        //output1[index2] = tanh(output1[index2] + bc1_temp[index2]);
    }
    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            output2[index2] = output2[index2] + hc2_temp[index1][index2] * output1[index1];
        }
        //ReLU
        output2[index2] = output2[index2] + bc2_temp[index2];
        hxh_c_sum[index2] = output2[index2];
        if (output2[index2] < 0) {
            output2[index2] = 0;
        }
        //tanh
        //output2[index2] = tanh(output2[index2] + bc2_temp[index2]);
    }
    for (int index2 = 0; index2 < 1; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit2; index1++) {
            output = output + hc3_temp[index1] * output2[index1];
        }
        output = output + bc3_temp;
        hxhh_c_sum = output;
    }
    return output;
}


void Actor_Network(float *arr)
{
    float output1[num_hidden_unit1] = {0.0f};
    float output2[num_hidden_unit2] = {0.0f};
    float output[2] = {0.0f};

    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            output1[index2] = output1[index2] + ha1_temp[index1][index2] * arr[index1];
        }
        output1[index2] = output1[index2] + ba1_temp[index2];
        hx_a_sum[index2] = output1[index2];
        if (output1[index2] < 0) {
            output1[index2] = 0;
        }
    }
    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            output2[index2] = output2[index2] + ha2_temp[index1][index2] * output1[index1];
        }
        output2[index2] = output2[index2] + ba2_temp[index2];
        hxh_a_sum[index2] = output2[index2];
        if (output2[index2] < 0) {
            output2[index2] = 0;
        }
    }
    for (int index2 = 0; index2 < 2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit2; index1++) {
            output[index2] = output[index2] + ha3_temp[index1][index2] * output2[index1];
        }
        hxhh_a_sum[index2] = output[index2] + ba3_temp[index2];
    }

    mean_before_SP = output[0] + ba3_temp[0];    //SP = softplus
    deviation_before_SP = output[1] + ba3_temp[1];
    //Softplus
    mean = log(1.0f+exp(mean_before_SP));
    deviation = log(1.0f+exp(deviation_before_SP));
    logging2 = mean;
    logging4 = deviation;
}


void Actor_Network_Old(float *arr)
{
    float output1[num_hidden_unit1] = {0.0f};
    float output2[num_hidden_unit2] = {0.0f};
    float output[2] = {0.0f};

    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            output1[index2] = output1[index2] + ha1[index1][index2] * arr[index1];
        }
        output1[index2] = output1[index2] + ba1[index2];
        if (output1[index2] < 0) {
            output1[index2] = 0;
        }
    }
    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            output2[index2] = output2[index2] + ha2[index1][index2] * output1[index1];
        }
        output2[index2] = output2[index2] + ba2[index2];
        if (output2[index2] < 0) {
            output2[index2] = 0;
        }
    }
    for (int index2 = 0; index2 < 2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit2; index1++) {
            output[index2] = output[index2] + ha3[index1][index2] * output2[index1];
        }
    }
    mean_old = output[0] + ba3[0];
    deviation_old = output[1] + ba3[1];
    //Softplus
    mean_old = log(1.0f+exp(mean_old));
    deviation_old = log(1.0f+exp(deviation_old));
}

float Grad_Normal_Dist_Mean(float mean, float deviation, float action)
{
    float grad_mean = 0.0f;
    grad_mean = (action-mean)*exp(-(action-mean)*(action-mean)/(2.0f*deviation*deviation))/(sqrt(2.0f*PI)*deviation*deviation*deviation);
    return grad_mean;
}

float Grad_Normal_Dist_Deviation(float mean, float deviation, float action)
{
    float grad_dev = 0.0f;
    grad_dev = exp(-(action-mean)*(action-mean)/(2.0f*deviation*deviation))*(-1.0f/(sqrt(2.0f*PI)*deviation*deviation) + (action-mean)*(action-mean)/(sqrt(2.0f*PI)*deviation*deviation*deviation*deviation));
    return grad_dev;
}

float ReLU(float x)
{
    if (x >= 0) {
        return x;
    } else {
        return 0.0f;
    }
}

void update_Critic_Networks(float (*arr)[num_input_RL])
{
    float G_hc1[num_input_RL][num_hidden_unit1] = {0.0f};
    float G_bc1[num_hidden_unit1] = {0.0f};
    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            for (int n=0; n<batch_size; n++) {
                float d_V_d_hc1 = 0.0f;
                for(int k=0; k<num_hidden_unit2; k++) {
                    if (hxh_c_sum_array[n][k] >= 0) {
                        if (hx_c_sum_array[n][index2] > 0) {
                            d_V_d_hc1 = d_V_d_hc1 + arr[n][index1]*hc2_temp[index2][k]*hc3_temp[k];
                        }
                    }
                }
                G_hc1[index1][index2] = G_hc1[index1][index2] + 2.0f*(return_G[n]-V[n])*(-d_V_d_hc1);
            }
            G_hc1[index1][index2] = G_hc1[index1][index2] / batch_size;
            if(G_hc1[index1][index2] > Gradient_Limit) G_hc1[index1][index2] = Gradient_Limit;
            else if (G_hc1[index1][index2] < -Gradient_Limit) G_hc1[index1][index2] = -Gradient_Limit;
            //hc1_temp[index1][index2] = hc1_temp[index1][index2] - gradient_rate_critic * G_hc1[index1][index2];
        }
        for (int n=0; n<batch_size; n++) {
            float d_V_d_bc1 = 0.0f;
            for(int k=0; k<num_hidden_unit2; k++) {
                if (hxh_c_sum_array[n][k] >= 0) {
                    if (hx_c_sum_array[n][index2] > 0) {
                        d_V_d_bc1 = d_V_d_bc1 + hc2_temp[index2][k]*hc3_temp[k];
                    }
                }
            }
            G_bc1[index2] = G_bc1[index2] + 2.0f*(return_G[n]-V[n])*(-d_V_d_bc1);
        }
        G_bc1[index2] = G_bc1[index2] / batch_size;
        if(G_bc1[index2] > Gradient_Limit) G_bc1[index2] = Gradient_Limit;
        else if (G_bc1[index2] < -Gradient_Limit) G_bc1[index2] = -Gradient_Limit;
        //bc1_temp[index2] = bc1_temp[index2] - gradient_rate_critic * G_bc1[index2];
    }


    float G_hc2[num_hidden_unit1][num_hidden_unit2] = {0.0f};
    float G_bc2[num_hidden_unit2] = {0.0f};
    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            for (int n=0; n<batch_size; n++) {
                float d_V_d_hc2 = 0.0f;
                if (hxh_c_sum_array[n][index2] >= 0) {
                    if (hx_c_sum_array[n][index1] > 0) {
                        d_V_d_hc2 = hx_c_sum_array[n][index1]*hc3_temp[index2];
                    }
                }
                G_hc2[index1][index2] = G_hc2[index1][index2] + 2.0f*(return_G[n]-V[n])*(-d_V_d_hc2);
            }
            G_hc2[index1][index2] = G_hc2[index1][index2] / batch_size;
            if(G_hc2[index1][index2] > Gradient_Limit) G_hc2[index1][index2] = Gradient_Limit;
            else if (G_hc2[index1][index2] < -Gradient_Limit) G_hc2[index1][index2] = -Gradient_Limit;
            //hc2_temp[index1][index2] = hc2_temp[index1][index2] - gradient_rate_critic * G_hc2[index1][index2];
        }
        for (int n=0; n<batch_size; n++) {
            float d_V_d_bc2 = 0.0f;
            if (hxh_c_sum_array[n][index2] >= 0) {
                d_V_d_bc2 = hc3_temp[index2];
            }
            G_bc2[index2] = G_bc2[index2] + 2.0f*(return_G[n]-V[n])*(-d_V_d_bc2);
        }
        G_bc2[index2] = G_bc2[index2] / batch_size;
        if(G_bc2[index2] > Gradient_Limit) G_bc2[index2] = Gradient_Limit;
        else if (G_bc2[index2] < -Gradient_Limit) G_bc2[index2] = -Gradient_Limit;
        //bc2_temp[index2] = bc2_temp[index2] - gradient_rate_critic * G_bc2[index2];
    }

    float G_hc3[num_hidden_unit2]= {0.0f};
    float G_bc3 = 0.0f;
    for (int index2 = 0; index2 < 1; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit2; index1++) {
            for (int n=0; n<batch_size; n++) {
                float d_V_d_hc3 = 0.0f;
                if (hxh_c_sum_array[n][index1] >= 0) {
                    d_V_d_hc3 = d_V_d_hc3 + hxh_c_sum_array[n][index1];
                }
                G_hc3[index1] = G_hc3[index1] + 2.0f*(return_G[n]-V[n])*(-d_V_d_hc3);
            }
            G_hc3[index1] = G_hc3[index1] / batch_size;
            if(G_hc3[index1] > Gradient_Limit) G_hc3[index1] = Gradient_Limit;
            else if (G_hc3[index1] < -Gradient_Limit) G_hc3[index1] = -Gradient_Limit;
            //hc3_temp[index1] = hc3_temp[index1] - gradient_rate_critic * G_hc3[index1];
        }
        for (int n=0; n<batch_size; n++) {
            float d_V_d_bc3 = 0.0f;
            d_V_d_bc3 = 1.0f;
            G_bc3 = G_bc3 + 2.0f*(return_G[n]-V[n])*(-d_V_d_bc3);
        }
        G_bc3 = G_bc3 / batch_size;
        if(G_bc3 > Gradient_Limit) G_bc3 = Gradient_Limit;
        else if (G_bc3 < -Gradient_Limit) G_bc3 = -Gradient_Limit;
        //bc3_temp = bc3_temp - gradient_rate_critic * G_bc3;
    }

    // Simultaneous Update
    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            hc1_temp[index1][index2] = hc1_temp[index1][index2] - gradient_rate_critic * G_hc1[index1][index2];
        }
        bc1_temp[index2] = bc1_temp[index2] - gradient_rate_critic * G_bc1[index2];
    }
    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            hc2_temp[index1][index2] = hc2_temp[index1][index2] - gradient_rate_critic * G_hc2[index1][index2];
        }
        bc2_temp[index2] = bc2_temp[index2] - gradient_rate_critic * G_bc2[index2];
    }
    for (int index2 = 0; index2 < 1; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit2; index1++) {
            hc3_temp[index1] = hc3_temp[index1] - gradient_rate_critic * G_hc3[index1];
        }
        bc3_temp = bc3_temp - gradient_rate_critic * G_bc3;
    }
}

///////////////////////////Softplus//////////////////////////////////
void update_Actor_Networks(float (*arr)[num_input_RL])
{
    

    float G_ha1[num_input_RL][num_hidden_unit1] = {0.0f};
    float G_ba1[num_hidden_unit1] = {0.0f};

    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            for (int n=0; n<batch_size; n++) {
                float d_x_d_ha1 = 0.0f;
                float d_y_d_ha1 = 0.0f;
                if((advantage[n] >= 0.0f && ratio[n] >= 1.0f + epsilon) || (advantage[n] < 0.0f && ratio[n] < 1.0f - epsilon)) {
                    G_ha1[index1][index2] = G_ha1[index1][index2];
                } else {
                    for(int k=0; k<num_hidden_unit2; k++) {
                        if (hxh_a_sum_array[n][k] >= 0) {
                            if (hx_a_sum_array[n][index2] > 0) {
                                d_x_d_ha1 = d_x_d_ha1 + arr[n][index1]*ha2_temp[index2][k]*ha3_temp[k][0];
                                d_y_d_ha1 = d_y_d_ha1 + arr[n][index1]*ha2_temp[index2][k]*ha3_temp[k][1];
                            }
                        }
                    }
                    float d_mean_d_ha1 = 0.0f;
                    float d_dev_d_ha1 = 0.0f;
                    d_mean_d_ha1 = exp(hxhh_a_sum_array[n][0])/(1.0f+exp(hxhh_a_sum_array[n][0]))*d_x_d_ha1;
                    d_dev_d_ha1 = exp(hxhh_a_sum_array[n][1])/(1.0f+exp(hxhh_a_sum_array[n][1]))*d_y_d_ha1;

                    G_ha1[index1][index2] = G_ha1[index1][index2] + advantage[n]/pi_old[n]*(d_mean_d_ha1*Grad_Normal_Dist_Mean(mean_array[n],deviation_array[n],action_array[n])+d_dev_d_ha1*Grad_Normal_Dist_Deviation(mean_array[n],deviation_array[n],action_array[n]));
                }
            }
            G_ha1[index1][index2] = -G_ha1[index1][index2] / batch_size;
            if(G_ha1[index1][index2] > Gradient_Limit) G_ha1[index1][index2] = Gradient_Limit;
            else if (G_ha1[index1][index2] < -Gradient_Limit) G_ha1[index1][index2] = -Gradient_Limit;
            //ha1_temp[index1][index2] = ha1_temp[index1][index2] - gradient_rate_actor * G_ha1[index1][index2];
        }

        for (int n=0; n<batch_size; n++) {
            float d_x_d_ba1 = 0.0f;
            float d_y_d_ba1 = 0.0f;
            if((advantage[n] >= 0.0f && ratio[n] >= 1.0f + epsilon) || (advantage[n] < 0.0f && ratio[n] < 1.0f - epsilon))  {
                G_ba1[index2] = G_ba1[index2];
            } else {
                for(int k=0; k<num_hidden_unit2; k++) {
                    if (hxh_a_sum_array[n][k] >= 0) {
                        if (hx_a_sum_array[n][index2] > 0) {
                            d_x_d_ba1 = d_x_d_ba1 + ha2_temp[index2][k]*ha3_temp[k][0];
                            d_y_d_ba1 = d_y_d_ba1 + ha2_temp[index2][k]*ha3_temp[k][1];
                        }
                    }
                }
                float d_mean_d_ba1 = 0.0f;
                float d_dev_d_ba1 = 0.0f;
                d_mean_d_ba1 = exp(hxhh_a_sum_array[n][0])/(1.0f+exp(hxhh_a_sum_array[n][0]))*d_x_d_ba1;
                d_dev_d_ba1 = exp(hxhh_a_sum_array[n][1])/(1.0f+exp(hxhh_a_sum_array[n][1]))*d_y_d_ba1;

                G_ba1[index2] = G_ba1[index2] + advantage[n]/pi_old[n]*(d_mean_d_ba1*Grad_Normal_Dist_Mean(mean_array[n],deviation_array[n],action_array[n])+d_dev_d_ba1*Grad_Normal_Dist_Deviation(mean_array[n],deviation_array[n],action_array[n]));
            }
        }
        G_ba1[index2] = -G_ba1[index2] / batch_size;
        if(G_ba1[index2] > Gradient_Limit) G_ba1[index2] = Gradient_Limit;
        else if (G_ba1[index2] < -Gradient_Limit) G_ba1[index2] = -Gradient_Limit;
        //ba1_temp[index2] = ba1_temp[index2] - gradient_rate_actor * G_ba1[index2];
    }

    float G_ha2[num_hidden_unit1][num_hidden_unit2] = {0.0f};
    float G_ba2[num_hidden_unit2] = {0.0f};

    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            for (int n=0; n<batch_size; n++) {
                float d_x_d_ha2 = 0.0f;
                float d_y_d_ha2 = 0.0f;
                if((advantage[n] >= 0.0f && ratio[n] >= 1.0f + epsilon) || (advantage[n] < 0.0f && ratio[n] < 1.0f - epsilon)) {
                    G_ha2[index1][index2] = G_ha2[index1][index2];
                } else {
                    if (hxh_a_sum_array[n][index2] >= 0) {
                        if (hx_a_sum_array[n][index1] > 0) {
                            d_x_d_ha2 = hx_a_sum_array[n][index1]*ha3_temp[index2][0];
                            d_y_d_ha2 = hx_a_sum_array[n][index1]*ha3_temp[index2][1];
                        }
                    }

                    float d_mean_d_ha2 = 0.0f;
                    float d_dev_d_ha2 = 0.0f;
                    d_mean_d_ha2 = exp(hxhh_a_sum_array[n][0])/(1.0f+exp(hxhh_a_sum_array[n][0]))*d_x_d_ha2;
                    d_dev_d_ha2 = exp(hxhh_a_sum_array[n][1])/(1.0f+exp(hxhh_a_sum_array[n][1]))*d_y_d_ha2;

                    G_ha2[index1][index2] = G_ha2[index1][index2] + advantage[n]/pi_old[n]*(d_mean_d_ha2*Grad_Normal_Dist_Mean(mean_array[n],deviation_array[n],action_array[n])+d_dev_d_ha2*Grad_Normal_Dist_Deviation(mean_array[n],deviation_array[n],action_array[n]));
                }
            }
            G_ha2[index1][index2] = -G_ha2[index1][index2] / batch_size;
            if(G_ha2[index1][index2] > Gradient_Limit) G_ha2[index1][index2] = Gradient_Limit;
            else if (G_ha2[index1][index2] < -Gradient_Limit) G_ha2[index1][index2] = -Gradient_Limit;
            //ha2_temp[index1][index2] = ha2_temp[index1][index2] - gradient_rate_actor * G_ha2[index1][index2];
        }

        for (int n=0; n<batch_size; n++) {
            float d_x_d_ba2 = 0.0f;
            float d_y_d_ba2 = 0.0f;
            if((advantage[n] >= 0.0f && ratio[n] >= 1.0f + epsilon) || (advantage[n] < 0.0f && ratio[n] < 1.0f - epsilon))  {
                G_ba2[index2] = G_ba2[index2];
            } else {

                if (hxh_a_sum_array[n][index2] >= 0) {
                    d_x_d_ba2 = ha3_temp[index2][0];
                    d_y_d_ba2 = ha3_temp[index2][1];
                }
                float d_mean_d_ba2= 0.0f;
                float d_dev_d_ba2= 0.0f;
                d_mean_d_ba2 = exp(hxhh_a_sum_array[n][0])/(1.0f+exp(hxhh_a_sum_array[n][0]))*d_x_d_ba2;
                d_dev_d_ba2 = exp(hxhh_a_sum_array[n][1])/(1.0f+exp(hxhh_a_sum_array[n][1]))*d_y_d_ba2;

                G_ba2[index2] = G_ba2[index2] + advantage[n]/pi_old[n]*(d_mean_d_ba2*Grad_Normal_Dist_Mean(mean_array[n],deviation_array[n],action_array[n])+d_dev_d_ba2*Grad_Normal_Dist_Deviation(mean_array[n],deviation_array[n],action_array[n]));
            }
        }
        G_ba2[index2] = -G_ba2[index2] / batch_size;
        if(G_ba2[index2] > Gradient_Limit) G_ba2[index2] = Gradient_Limit;
        else if (G_ba2[index2] < -Gradient_Limit) G_ba2[index2] = -Gradient_Limit;
        //ba2_temp[index2] = ba2_temp[index2] - gradient_rate_actor * G_ba2[index2];
    }

    float G_ha3[num_hidden_unit2][2] = {0.0f};
    float G_ba3[2] = {0.0f};

    for (int index2 = 0; index2 < 2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit2; index1++) {
            for (int n=0; n<batch_size; n++) {
                float d_x_d_ha3 = 0.0f;
                float d_y_d_ha3 = 0.0f;
                if((advantage[n] >= 0.0f && ratio[n] >= 1.0f + epsilon) || (advantage[n] < 0.0f && ratio[n] < 1.0f - epsilon)) {
                    G_ha3[index1][index2] = G_ha3[index1][index2];
                } else {
                    if (hxh_a_sum_array[n][index1] >= 0) {
                        if (hx_a_sum_array[n][index1] > 0) {
                            d_x_d_ha3 = hxh_a_sum_array[n][index1];
                            d_y_d_ha3 = hxh_a_sum_array[n][index1];
                        }
                    }
                    float d_mean_d_ha3 = 0.0f;
                    float d_dev_d_ha3 = 0.0f;
                    d_mean_d_ha3 = exp(hxhh_a_sum_array[n][0])/(1.0f+exp(hxhh_a_sum_array[n][0]))*d_x_d_ha3;
                    d_dev_d_ha3 = exp(hxhh_a_sum_array[n][1])/(1.0f+exp(hxhh_a_sum_array[n][1]))*d_y_d_ha3;

                    G_ha3[index1][index2] = G_ha3[index1][index2] + advantage[n]/pi_old[n]*(d_mean_d_ha3*Grad_Normal_Dist_Mean(mean_array[n],deviation_array[n],action_array[n])+d_dev_d_ha3*Grad_Normal_Dist_Deviation(mean_array[n],deviation_array[n],action_array[n]));
                }
            }
            G_ha3[index1][index2] = -G_ha3[index1][index2] / batch_size;
            if(G_ha3[index1][index2] > Gradient_Limit) G_ha3[index1][index2] = Gradient_Limit;
            else if (G_ha3[index1][index2] < -Gradient_Limit) G_ha3[index1][index2] = -Gradient_Limit;
            //ha3_temp[index1][index2] = ha3_temp[index1][index2] - gradient_rate_actor * G_ha3[index1][index2];
        }

        for (int n=0; n<batch_size; n++) {
            float d_x_d_ba3 = 0.0f;
            float d_y_d_ba3 = 0.0f;
            if((advantage[n] >= 0.0f && ratio[n] >= 1.0f + epsilon) || (advantage[n] < 0.0f && ratio[n] < 1.0f - epsilon))  {
                G_ba3[index2] = G_ba3[index2];
            } else {

                d_x_d_ba3 = 1.0f;
                d_y_d_ba3 = 1.0f;

                float d_mean_d_ba3= 0.0f;
                float d_dev_d_ba3= 0.0f;
                d_mean_d_ba3 = exp(hxhh_a_sum_array[n][0])/(1.0f+exp(hxhh_a_sum_array[n][0]))*d_x_d_ba3;
                d_dev_d_ba3 = exp(hxhh_a_sum_array[n][1])/(1.0f+exp(hxhh_a_sum_array[n][1]))*d_y_d_ba3;

                G_ba3[index2] = G_ba3[index2] + advantage[n]/pi_old[n]*(d_mean_d_ba3*Grad_Normal_Dist_Mean(mean_array[n],deviation_array[n],action_array[n])+d_dev_d_ba3*Grad_Normal_Dist_Deviation(mean_array[n],deviation_array[n],action_array[n]));
            }
        }
        G_ba3[index2] = -G_ba3[index2] / batch_size;
        if(G_ba3[index2] > Gradient_Limit) G_ba3[index2] = Gradient_Limit;
        else if (G_ba3[index2] < -Gradient_Limit) G_ba3[index2] = -Gradient_Limit;
        //ba3_temp[index2] = ba3_temp[index2] - gradient_rate_actor * G_ba3[index2];
    }

    // Simultaneous Update
    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            ha1_temp[index1][index2] = ha1_temp[index1][index2] - gradient_rate_actor * G_ha1[index1][index2];
        }
        ba1_temp[index2] = ba1_temp[index2] - gradient_rate_actor * G_ba1[index2];
    }
    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            ha2_temp[index1][index2] = ha2_temp[index1][index2] - gradient_rate_actor * G_ha2[index1][index2];
        }
        ba2_temp[index2] = ba2_temp[index2] - gradient_rate_actor * G_ba2[index2];
    }
    for (int index2 = 0; index2 < 2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit2; index1++) {
            ha3_temp[index1][index2] = ha3_temp[index1][index2] - gradient_rate_actor * G_ha3[index1][index2];
        }
        ba3_temp[index2] = ba3_temp[index2] - gradient_rate_actor * G_ba3[index2];
    }
}

float rand_normal(double mean, double stddev)
{
    //Box muller method
    static double n2 = 0.0f;
    static int n2_cached = 0;
    if (!n2_cached) {
        double x, y, r;
        do {
            x = 2.0f*rand()/RAND_MAX - 1;
            y = 2.0f*rand()/RAND_MAX - 1;

            r = x*x + y*y;
        } while (r == 0.0f || r > 1.0f);
        {
            double d = sqrt(-2.0f*log(r)/r);
            double n1 = x*d;
            n2 = y*d;
            double result = n1*stddev + mean;
            n2_cached = 1;
            return result;
        }
    } else {
        n2_cached = 0;
        return n2*stddev + mean;
    }
}

float mean_adv(float x[], int size)
{
    float add = 0.0f;
    float result;
    
    for (int i=0; i<size; i++)
    {
        add += x[i];
    }
    result = (float) add/size;
    return result;
}
float deviation_adv(float x[], int size)
{
    float sigma = 0.0f;
    float resultDeb = 0.0f;
    
    for (int k=0; k<size; k++)
    {
        sigma = pow((float)x[k]-mean_adv(x,size), (float)2.0f)/(size-1);
        resultDeb += sqrt(sigma);
    }
    return resultDeb;
}    
     

void Overwirte_Critic_Networks()
{
    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            hc1[index1][index2] = hc1_temp[index1][index2];
        }
        bc1[index2] = bc1_temp[index2];
    }
    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            hc2[index1][index2] = hc2_temp[index1][index2];
        }
        bc2[index2] = bc2_temp[index2];
        hc3[index2] = hc3_temp[index2];
    }
    bc3 = bc3_temp;
}
void Overwirte_Actor_Networks()
{
    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            ha1[index1][index2] = ha1_temp[index1][index2];
        }
        ba1[index2] = ba1_temp[index2];
    }
    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            ha2[index1][index2] = ha2_temp[index1][index2];
        }
        ba2[index2] = ba2_temp[index2];
    }
    for (int index2 = 0; index2 < 2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit2; index1++) {
            ha3[index1][index2] = ha3_temp[index1][index2];
        }
        ba3[index2] = ba3_temp[index2];
    }
}


int main()
{

    HAL_Init();
    SystemClock_Config();

    /*********************************
    ***     Initialization
    *********************************/
    LED = 0;
    pc.baud(9600);

    // i2c init
    i2c.frequency(400 * 1000);          // 0.4 mHz
    wait_ms(2);                         // Power Up wait
    look_for_hardware_i2c();            // Hardware present
    init_as5510(i2c_slave_addr1);
    make_delay();

//    // spi init
    eeprom.format(8,3);
    eeprom.frequency(5000000); //5M
    enc.format(8,0);
    enc.frequency(5000000); //5M
    make_delay();

    //rom
    ROM_CALL_DATA();
    make_delay();

    // ADC init
    Init_ADC();
    make_delay();

    // Pwm init
    Init_PWM();
    TIM4->CR1 ^= TIM_CR1_UDIS;
    make_delay();

    // TMR3 init
    Init_TMR3();
    TIM3->CR1 ^= TIM_CR1_UDIS;
    make_delay();

    // TMR2 init
//    Init_TMR2();
//    TIM2->CR1 ^= TIM_CR1_UDIS;
//    make_delay();

    // CAN
    can.attach(&CAN_RX_HANDLER);
    CAN_ID_INIT();
    make_delay();

    //Timer priority
    NVIC_SetPriority(TIM3_IRQn, 2);
    //NVIC_SetPriority(TIM2_IRQn, 3);
    NVIC_SetPriority(TIM4_IRQn, 3);

    //can.reset();
    can.filter(msg.id, 0xFFFFF000, CANStandard);

    // spi _ enc
    spi_enc_set_init();
    make_delay();

    //DAC init
    if (SENSING_MODE == 0) {
        dac_1 = TORQUE_VREF / 3.3f;
        dac_2 = 0.0f;
    } else if (SENSING_MODE == 1) {
        dac_1 = PRES_A_VREF / 3.3f;
        dac_2 = PRES_B_VREF / 3.3f;
    }
    make_delay();

    for (int i=0; i<50; i++) {
        if(i%2==0)
            ID_index_array[i] = - i * 0.5f;
        else
            ID_index_array[i] =  (i+1) * 0.5f;
    }

    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            hc1_temp[index1][index2] = (float) (rand()%100) * 0.007f ;
        }
        bc1_temp[index2] = (float) (rand()%100) * 0.007f;
    }
    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            hc2_temp[index1][index2] = (float) (rand()%100) * 0.007f;
        }
        bc2_temp[index2] = (float) (rand()%100) * 0.007f;
        hc3_temp[index2] = (float) (rand()%100) * 0.007f;
    }
    bc3_temp = (float) (rand()%100) * 0.007f;

    for (int index2 = 0; index2 < num_hidden_unit1; index2++) {
        for (int index1 = 0; index1 < num_input_RL; index1++) {
            ha1_temp[index1][index2] = (float) (rand()%100) * 0.007f;
        }
        ba1_temp[index2] = (float) (rand()%100) * 0.007f;
    }
    for (int index2 = 0; index2 < num_hidden_unit2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit1; index1++) {
            ha2_temp[index1][index2] = (float) (rand()%100) * 0.007f;
        }
        ba2_temp[index2] = (float) (rand()%100) * 0.007f;
    }
    for (int index2 = 0; index2 < 2; index2++) {
        for (int index1 = 0; index1 < num_hidden_unit2; index1++) {
            ha3_temp[index1][index2] = (float) (rand()%100) * 0.007f;
        }
        ba3_temp[index2] = (float) (rand()%100) * 0.007f;
    }

    Overwirte_Critic_Networks();
    Overwirte_Actor_Networks();

    /************************************
    ***     Program is operating!
    *************************************/
    while(1) {

//        if(timer_while==27491) {
//            timer_while = 0;
//            pc.printf("ref : %f     virt_pos : %f  mean : %f    deviation : %f       Last_pos_of_batch : %f      reward_sum : %f\n", pos.sen/(float)(ENC_PULSE_PER_POSITION), logging3, logging2, logging4, logging1, logging5);
//            //pc.printf("%f\n", virt_pos);
//            //pc.printf("%f\n", pos.sen/(float)(ENC_PULSE_PER_POSITION));
//            //pc.printf("ref : %f     virt_pos : %f\n", pos.sen/(float)(ENC_PULSE_PER_POSITION), virt_pos);
//        }


        //i2c
        read_field(i2c_slave_addr1);
        if(DIR_VALVE_ENC < 0) value = 1023 - value;

        //timer_while ++;

        ///////////////////////////////////////////////////////Neural Network

        if(NN_Control_Flag == 0) {
            LED = 0;
        }

        else if(NN_Control_Flag == 1) {

            int ind = 0;
            for(int i=0; i<numpast_u; i++) {
                input_NN[ind] = u_past[time_interval*i];
                ind = ind + 1;
            }

            for(int i=0; i<numpast_x; i++) {
                input_NN[ind] = x_past[time_interval*i] / 60.0f;
                ind = ind + 1;
            }
            input_NN[ind] = (pos.sen / ENC_PULSE_PER_POSITION) / 60.0f;
            ind = ind + 1;

//            for(int i=0; i<numfuture_x; i++) {
//                input_NN[ind] = x_future[time_interval*i+time_interval] / 60.0f;
//                ind = ind + 1;
//            }

            for(int i=0; i<numpast_f; i++) {
                input_NN[ind] = f_past[time_interval*i] / 10000.0f * 8.0f + 0.5f;
                ind = ind + 1;
            }
            input_NN[ind] = torq.sen / 10000.0f * 8.0f + 0.5f;
            ind = ind + 1;
            for(int i=0; i<numfuture_f; i++) {
//                input_NN[ind] = (f_future[time_interval*i+time_interval] - torq.sen)/10000.0f * 8.0f + 0.5f;
                input_NN[ind] = (f_future[time_interval*i+time_interval])/10000.0f*8.0f+0.5f;
                ind = ind + 1;
            }

            float output1[16] = { 0.0f };
            float output2[16] = { 0.0f };
            float output3[16] = { 0.0f };
            float output = 0.0f;

            for (int index2 = 0; index2 < 16; index2++) {
                for (int index1 = 0; index1 < num_input; index1++) {
                    output1[index2] = output1[index2]
                                      + h1[index1][index2] * input_NN[index1];
                }
                output1[index2] = output1[index2] + b1[index2];
                if (output1[index2] < 0) {
                    output1[index2] = 0;
                }
            }

            for (int index2 = 0; index2 < 16; index2++) {
                for (int index1 = 0; index1 < 16; index1++) {
                    output2[index2] = output2[index2]
                                      + h2[index1][index2] * output1[index1];
                }
                output2[index2] = output2[index2] + b2[index2];
                if (output2[index2] < 0) {
                    output2[index2] = 0;
                }
            }

            for (int index2 = 0; index2 < 16; index2++) {
                for (int index1 = 0; index1 < 16; index1++) {
                    output3[index2] = output3[index2]
                                      + h3[index1][index2] * output2[index1];
                }
                output3[index2] = output3[index2] + b3[index2];
                if (output3[index2] < 0) {
                    output3[index2] = 0;
                }
            }

            for (int index2 = 0; index2 < 1; index2++) {
                for (int index1 = 0; index1 < 16; index1++) {
                    output = output + hout[index1] * output3[index1];
                }
                output = output + bout[index2];

            }
            output = 1.0f/(1.0f+exp(-output));
            output_normalized = output;
            output = output * 20000.0f - 10000.0f;

            if(output>=0) {
                valve_pos.ref = output*0.0001f*((double)VALVE_MAX_POS - (double) VALVE_CENTER) + (double) VALVE_CENTER;
            } else {
                valve_pos.ref = -output*0.0001f*((double)VALVE_MIN_POS - (double) VALVE_CENTER) + (double) VALVE_CENTER;
            }


            if(LED==1) {
                LED=0;
            } else
                LED = 1;

        }


        /////////////////////////////////////////////////////////////////////RL
        switch (Update_Case) {
            case 0: {
                break;
            }
            case 1: {
                //Network Update(just update and hold network)
                for (int epoch = 0; epoch < num_epoch; epoch++) {
                    float loss_sum = 0.0f;
                    for (int n=batch_size-1; n>=0; n--) {
                        //Calculate Estimated V
                        //float temp_array[3] = {state_array[n][0], state_array[n][1], state_array[n][2]};
                        float temp_array[2] = {state_array[n][0], state_array[n][1]};
                        V[n] = Critic_Network_Temp(temp_array);
                        for (int i=0; i<num_hidden_unit1; i++) {
                            hx_c_sum_array[n][i] = hx_c_sum[i];
                        }
                        for (int i=0; i<num_hidden_unit2; i++) {
                            hxh_c_sum_array[n][i] = hxh_c_sum[i];
                        }
                        hxhh_c_sum_array[n] = hxhh_c_sum;

                        pi[n] = exp(-(action_array[n]-mean_array[n])*(action_array[n]-mean_array[n])/(2.0f*deviation_array[n]*deviation_array[n]))/(sqrt(2.0f*PI)*deviation_array[n]);
                        Actor_Network_Old(temp_array);
                        pi_old[n] = exp(-(action_array[n]-mean_old)*(action_array[n]-mean_old)/(2.0f*deviation_old*deviation_old))/(sqrt(2.0f*PI)*deviation_old);
                        r[n] = exp(-0.25f * 5.0f * state_array[n][1] * state_array[n][1]);
                        if(n == batch_size-1) return_G[n] = 0.0f;
                        else return_G[n] = gamma * return_G[n+1] + r[n];
                        if(n == batch_size-1) td_target[n] = r[n];
                        else td_target[n] = r[n] + gamma * V[n+1];
                        delta[n] = td_target[n] - V[n];
                        if(n == batch_size-1) advantage[n] = 0.0f;
                        else advantage[n] = gamma * lmbda * advantage[n+1] + delta[n];
//                        return_G[n] = advantage[n] + V[n];
                        ratio[n] = pi[n]/pi_old[n];
                    }
                    float mean_advantage = 0.0f;
                    float dev_advantage = 0.0f;
                    mean_advantage = mean_adv(advantage, batch_size);
                    dev_advantage = deviation_adv(advantage, batch_size);
                    for (int n=batch_size-1; n>=0; n--) {
                        //advantage[n] = (advantage[n]-mean_advantage)/dev_advantage;
                        surr1[n] = ratio[n] * advantage[n];
                        if (ratio[n] > 1.0f + epsilon) {
                            surr2[n] = (1.0f + epsilon)*advantage[n];
                        } else if( ratio[n] < 1.0f - epsilon) {
                            surr2[n] = (1.0f - epsilon)*advantage[n];
                        } else {
                            surr2[n] = ratio[n]*advantage[n];
                        }
                        loss[n] = -min(surr1[n], surr2[n]);
                        loss_sum = loss_sum + loss[n];
                    }
                    reward_sum = 0.0f;
                    for (int i=0; i<batch_size; i++) {
                        reward_sum = reward_sum + r[i];
                    }
                    logging5 = reward_sum;


                    //loss_batch = loss_sum / (float) batch_size;
                    loss_batch = loss_sum;
                    //Update Networks
                    update_Critic_Networks(state_array);
                    update_Actor_Networks(state_array);
                }
                Update_Done_Flag = 1;
                Update_Case = 0;
                //logging1 = V[0];

                break;
            }
            case 2: {
                //Network apply to next Network
                Overwirte_Critic_Networks();
                Overwirte_Actor_Networks();
                virt_pos = 10.0f;
                Update_Done_Flag = 1;
                Update_Case = 0;
                break;
            }

        }
    }
}

float DDV_JOINT_POS_FF(float REF_JOINT_VEL)
{

    int i = 0;
    float Ref_Valve_Pos_FF = 0.0f;
    for(i=0; i<VALVE_POS_NUM; i++) {
        if(REF_JOINT_VEL >= min(JOINT_VEL[i],JOINT_VEL[i+1]) && REF_JOINT_VEL <=  max(JOINT_VEL[i],JOINT_VEL[i+1])) {
            if(i==0) {
                if(JOINT_VEL[i+1] == JOINT_VEL[i]) {
                    Ref_Valve_Pos_FF = (float) VALVE_CENTER;
                } else {
                    Ref_Valve_Pos_FF = ((float) 10/(JOINT_VEL[i+1] - JOINT_VEL[i]) * (REF_JOINT_VEL - JOINT_VEL[i])) + (float) VALVE_CENTER;
                }
            } else {
                if(JOINT_VEL[i+1] == JOINT_VEL[i-1]) {
                    Ref_Valve_Pos_FF = (float) VALVE_CENTER;
                } else {
                    Ref_Valve_Pos_FF = ((float) 10*(ID_index_array[i+1] - ID_index_array[i-1])/(JOINT_VEL[i+1] - JOINT_VEL[i-1]) * (REF_JOINT_VEL - JOINT_VEL[i-1])) + (float) VALVE_CENTER + (float) (10*ID_index_array[i-1]);
                }
            }
            break;
        }
    }
    if(REF_JOINT_VEL > max(JOINT_VEL[VALVE_POS_NUM-1], JOINT_VEL[VALVE_POS_NUM-2])) {
        Ref_Valve_Pos_FF = (float) VALVE_MAX_POS;
    } else if(REF_JOINT_VEL < min(JOINT_VEL[VALVE_POS_NUM-1], JOINT_VEL[VALVE_POS_NUM-2])) {
        Ref_Valve_Pos_FF = (float) VALVE_MIN_POS;
    }

    Ref_Valve_Pos_FF = (float) VELOCITY_COMP_GAIN * 0.01f * (float) (Ref_Valve_Pos_FF - (float) VALVE_CENTER);
    return Ref_Valve_Pos_FF;

}


void VALVE_POS_CONTROL(float REF_VALVE_POS)
{
    int i = 0;

    if(REF_VALVE_POS > VALVE_MAX_POS) {
        REF_VALVE_POS = VALVE_MAX_POS;
    } else if(REF_VALVE_POS < VALVE_MIN_POS) {
        REF_VALVE_POS = VALVE_MIN_POS;
    }

    valve_pos_err = (float) (REF_VALVE_POS - value);
    valve_pos_err_diff = valve_pos_err - valve_pos_err_old;
    valve_pos_err_old = valve_pos_err;
    valve_pos_err_sum += valve_pos_err;
    if (valve_pos_err_sum > 1000.0f) valve_pos_err_sum = 1000.0f;
    if (valve_pos_err_sum<-1000.0f) valve_pos_err_sum = -1000.0f;

    VALVE_PWM_RAW_FB = P_GAIN_VALVE_POSITION * valve_pos_err + I_GAIN_VALVE_POSITION * valve_pos_err_sum + D_GAIN_VALVE_POSITION * valve_pos_err_diff;

    for(i=0; i<24; i++) {
        if(REF_VALVE_POS >= min(VALVE_POS_VS_PWM[i],VALVE_POS_VS_PWM[i+1]) && (float) REF_VALVE_POS <=  max(VALVE_POS_VS_PWM[i],VALVE_POS_VS_PWM[i+1])) {
            if(i==0) {
                VALVE_PWM_RAW_FF = (float) 1000.0f / (float) (VALVE_POS_VS_PWM[i+1] - VALVE_POS_VS_PWM[i]) * ((float) REF_VALVE_POS - VALVE_POS_VS_PWM[i]);
            } else {
                VALVE_PWM_RAW_FF = (float) 1000.0f* (float) (ID_index_array[i+1] - ID_index_array[i-1])/(VALVE_POS_VS_PWM[i+1] - VALVE_POS_VS_PWM[i-1]) * ((float) REF_VALVE_POS - VALVE_POS_VS_PWM[i-1]) + 1000.0f * (float) ID_index_array[i-1];
            }
            break;
        }
    }
    Vout.ref = VALVE_PWM_RAW_FF + VALVE_PWM_RAW_FB;
}

#define LT_MAX_IDX  57
float LT_PWM_duty[LT_MAX_IDX] = {-100.0f, -80.0f, -60.0f, -50.0f, -40.0f, -35.0f, -30.0f, -25.0f, -20.0f,
                                 -19.0f, -18.0f, -17.0f, -16.0f, -15.0f, -14.0f, -13.0f, -12.0f, -11.0f, -10.0f,
                                 -9.0f, -8.0f, -7.0f, -6.0f, -5.0f, -4.0f, -3.0f, -2.0f, -1.0f, 0.0f,
                                 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f,
                                 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f, 17.0f, 18.0f, 19.0f, 20.0f,
                                 25.0f, 30.0f, 35.0f, 40.0f, 50.0f, 60.0f, 80.0f, 100.0f
                                };  // duty
float LT_Voltage_Output[LT_MAX_IDX] = {-230.0f, -215.0f, -192.5f, -185.0f, -177.5f, -170.0f, -164.0f, -160.0f, -150.0f,
                                       -150.0f, -145.0f, -145.0f, -145.0f, -135.0f, -135.0f, -135.0f, -127.5f, -127.5f, -115.0f,
                                       -115.0f, -115.0F, -100.0f, -100.0f, -100.0f, -60.0f, -60.0f, -10.0f, -5.0f, 0.0f,
                                       7.5f, 14.0f, 14.0f, 14.0f, 42.5f, 42.5f, 42.5f, 80.0f, 80.0f, 105.0f,
                                       105.0f, 105.0f, 120.0f, 120.0f, 120.0f, 131.0f, 131.0f, 140.0f, 140.0f, 140.0f,
                                       155.0f, 160.0f, 170.0f, 174.0f, 182.0f, 191.0f, 212.0f, 230.0f
                                      }; // mV

float PWM_duty_byLT(float Ref_V)
{
    float PWM_duty = 0.0f;
    if(Ref_V<LT_Voltage_Output[0]) {
        PWM_duty = (Ref_V-LT_Voltage_Output[0])/1.5f+LT_PWM_duty[0];
    } else if (Ref_V>=LT_Voltage_Output[LT_MAX_IDX-1]) {
        PWM_duty = (Ref_V-LT_Voltage_Output[LT_MAX_IDX-1])/1.5f+LT_PWM_duty[LT_MAX_IDX-1];
    } else {
        int idx = 0;
        for(idx=0; idx<LT_MAX_IDX-1; idx++) {
            float ini_x = LT_Voltage_Output[idx];
            float fin_x = LT_Voltage_Output[idx+1];
            float ini_y = LT_PWM_duty[idx];
            float fin_y = LT_PWM_duty[idx+1];
            if(Ref_V>=ini_x && Ref_V<fin_x) {
                PWM_duty = (fin_y-ini_y)/(fin_x-ini_x)*(Ref_V-ini_x) + ini_y;
                break;
            }
        }
    }

    return PWM_duty;
}





/*******************************************************************************
                            TIMER INTERRUPT
*******************************************************************************/

float FREQ_TMR4 = (float)FREQ_20k;
float DT_TMR4 = (float)DT_20k;
long  CNT_TMR4 = 0;
int   TMR4_FREQ_10k = (int)FREQ_10k;
extern "C" void TIM4_IRQHandler(void)
{
    if (TIM4->SR & TIM_SR_UIF ) {

        /*******************************************************
        ***     Sensor Read & Data Handling
        ********************************************************/

        //Encoder
        if (CNT_TMR4 % (int) ((int) FREQ_TMR4/TMR4_FREQ_10k) == 0) {
            ENC_UPDATE();
        }

        ADC1->CR2  |= 0x40000000;
        if (SENSING_MODE == 0) {
            // Torque Sensing (0~210)bar =============================================
            float pres_A_new = (((float) ADC1->DR) - 2047.5f);
            double alpha_update_ft = 1.0f / (1.0f + FREQ_TMR4 / (2.0f * 3.14f * 100.0f)); // f_cutoff : 200Hz
            pres_A.sen = (1.0f - alpha_update_ft) * pres_A.sen + alpha_update_ft * pres_A_new;
            torq.sen = -pres_A.sen / TORQUE_SENSOR_PULSE_PER_TORQUE;


//        float alpha_update_pres_A = 1.0f/(1.0f + FREQ_TMR4/(2.0f*3.14f*100.0f));
////        float pres_A_new = ((float)ADC1->DR - PRES_A_NULL)  / PRES_SENSOR_A_PULSE_PER_BAR;
//        float pres_A_new = ((float)ADC1->DR);
//        pres_A.sen = pres_A.sen*(1.0f-alpha_update_pres_A)+pres_A_new*(alpha_update_pres_A);
//        torq.sen = - (pres_A.sen-2048.0f); //pulse -2047~2047


        } else if (SENSING_MODE == 1) {
            // Pressure Sensing (0~210)bar =============================================
            float pres_A_new = (((float)ADC1->DR) - PRES_A_NULL);
            float pres_B_new = (((float)ADC2->DR) - PRES_B_NULL);
            double alpha_update_pres = 1.0f / (1.0f + FREQ_TMR4 / (2.0f * 3.14f * 200.0f)); // f_cutoff : 500Hz
            pres_A.sen = (1.0f - alpha_update_pres) * pres_A.sen + alpha_update_pres * pres_A_new;
            pres_B.sen = (1.0f - alpha_update_pres) * pres_B.sen + alpha_update_pres * pres_B_new;
            CUR_PRES_A_BAR = pres_A.sen / PRES_SENSOR_A_PULSE_PER_BAR;
            CUR_PRES_B_BAR = pres_B.sen / PRES_SENSOR_B_PULSE_PER_BAR;

            if ((OPERATING_MODE & 0x01) == 0) { // Rotary Actuator
                torq.sen = (PISTON_AREA_A * CUR_PRES_A_BAR - PISTON_AREA_B * CUR_PRES_B_BAR) * 0.0001f; // mm^3*bar >> Nm
            } else if ((OPERATING_MODE & 0x01) == 1) { // Linear Actuator
                torq.sen = (PISTON_AREA_A * CUR_PRES_A_BAR - PISTON_AREA_B * CUR_PRES_B_BAR) * 0.1f; // mm^2*bar >> N
            }
        }

//        //Pressure sensor A
//        ADC1->CR2  |= 0x40000000;                        // adc _ 12bit
//        //while((ADC1->SR & 0b10));
//        float alpha_update_pres_A = 1.0f/(1.0f + FREQ_TMR4/(2.0f*3.14f*100.0f));
//        float pres_A_new = ((float)ADC1->DR);
//        pres_A.sen = pres_A.sen*(1.0f-alpha_update_pres_A)+pres_A_new*(alpha_update_pres_A);
//        torq.sen = - (pres_A.sen-2048.0f); //pulse -2047~2047    //SW just changed the sign to correct the direction of loadcell on LIGHT. Correct later.
//
//
//        //Pressure sensor B
//        float alpha_update_pres_B = 1.0f/(1.0f + FREQ_TMR4/(2.0f*3.14f*100.0f));
//        float pres_B_new = ((float)ADC2->DR);
//        pres_B.sen = pres_B.sen*(1.0f-alpha_update_pres_B)+pres_B_new*(alpha_update_pres_B);
//        //torq.sen = pres_A.sen * (float) PISTON_AREA_A - pres_B.sen * (float) PISTON_AREA_B;


        //Current
        //ADC3->CR2  |= 0x40000000;                        // adc _ 12bit
        //int raw_cur = ADC3->DR;
        //while((ADC3->SR & 0b10));
        float alpha_update_cur = 1.0f/(1.0f + FREQ_TMR4/(2.0f*3.14f*500.0f)); // f_cutoff : 500Hz
        float cur_new = ((float)ADC3->DR-2048.0f)*20.0f/4096.0f; // unit : mA
        cur.sen=cur.sen*(1.0f-alpha_update_cur)+cur_new*(alpha_update_cur);
        //cur.sen = raw_cur;

        CNT_TMR4++;
    }
    TIM4->SR = 0x0;  // reset the status register
}


int j =0;
float FREQ_TMR3 = (float)FREQ_5k;
float DT_TMR3 = (float)DT_5k;
int cnt_trans = 0;
double VALVE_POS_RAW_FORCE_FB_LOGGING = 0.0f;
int can_rest =0;

extern "C" void TIM3_IRQHandler(void)
{
    if (TIM3->SR & TIM_SR_UIF ) {

        if (((OPERATING_MODE&0b110)>>1) == 0) {
            K_v = 0.4f; // Moog (LPM >> mA) , 100bar
            mV_PER_mA = 500.0f; // 5000mV/10mA
            mV_PER_pulse = 0.5f; // 5000mV/10000pulse
            mA_PER_pulse = 0.001f; // 10mA/10000pulse
        } else if (((OPERATING_MODE&0b110)>>1) == 1) {
            K_v = 0.5f; // KNR (LPM >> mA) , 100bar
            mV_PER_mA = 166.6666f; // 5000mV/30mA
            mV_PER_pulse = 0.5f; // 5000mV/10000pulse
            mA_PER_pulse = 0.003f; // 30mA/10000pulse
        }

        if(MODE_POS_FT_TRANS == 1) {
            alpha_trans = (float)(1.0f - cos(3.141592f * (float)cnt_trans * DT_TMR3 /3.0f))/2.0f;
            cnt_trans++;
            torq.err_sum = 0;
            if((float)cnt_trans * DT_TMR3 > 3.0f)
                MODE_POS_FT_TRANS = 2;
        } else if(MODE_POS_FT_TRANS == 3) {
            alpha_trans = (float)(1.0f + cos(3.141592f * (float)cnt_trans * DT_TMR3 /3.0f))/2.0f;
            cnt_trans++;
            torq.err_sum = 0;
            if((float) cnt_trans * DT_TMR3 > 3.0f )
                MODE_POS_FT_TRANS = 0;
        } else if(MODE_POS_FT_TRANS == 2) {
            alpha_trans = 1.0f;
            cnt_trans = 0;
        } else {
            alpha_trans = 0.0f;
            cnt_trans = 0;
        }


        int UTILITY_MODE = 0;
        int CONTROL_MODE = 0;

        if (CONTROL_UTILITY_MODE >= 20 || CONTROL_UTILITY_MODE == 0) {
            UTILITY_MODE = CONTROL_UTILITY_MODE;
            CONTROL_MODE = MODE_NO_ACT;
        } else {
            CONTROL_MODE = CONTROL_UTILITY_MODE;
            UTILITY_MODE = MODE_NO_ACT;
        }



        // UTILITY MODE ------------------------------------------------------------

        switch (UTILITY_MODE) {
            case MODE_NO_ACT: {
                break;
            }

            case MODE_TORQUE_SENSOR_NULLING: {
                // DAC Voltage reference set
                if (TMR3_COUNT_TORQUE_NULL < TMR_FREQ_5k * 2) {
                    CUR_TORQUE_sum += torq.sen;

                    if (TMR3_COUNT_TORQUE_NULL % 10 == 0) {
                        CUR_TORQUE_mean = CUR_TORQUE_sum / 10.0f;
                        CUR_TORQUE_sum = 0;

                        TORQUE_VREF += 0.000003f * (0.0f - CUR_TORQUE_mean);

                        if (TORQUE_VREF > 3.3f) TORQUE_VREF = 3.3f;
                        if (TORQUE_VREF < 0.0f) TORQUE_VREF = 0.0f;

                        //spi_eeprom_write(RID_TORQUE_SENSOR_VREF, (int16_t) (TORQUE_VREF * 1000.0));
                        dac_1 = TORQUE_VREF / 3.3f;
                    }
                } else {
                    CONTROL_UTILITY_MODE = MODE_NO_ACT;
                    TMR3_COUNT_TORQUE_NULL = 0;
                    CUR_TORQUE_sum = 0;
                    CUR_TORQUE_mean = 0;

//                    ROM_RESET_DATA();
                    spi_eeprom_write(RID_TORQUE_SENSOR_VREF, (int16_t) (TORQUE_VREF * 1000.0f));

                    dac_1 = TORQUE_VREF / 3.3f;

                }
                TMR3_COUNT_TORQUE_NULL++;
                break;
            }

//            case MODE_VALVE_NULLING_AND_DEADZONE_SETTING: {
//                if (TMR3_COUNT_DEADZONE == 0) {
//                    if (pos_plus_end == pos_minus_end) need_enc_init = true;
//                    else temp_time = 0;
//                }
//                if (need_enc_init) {
//                    if (TMR3_COUNT_DEADZONE < (int) (0.5f * (float) TMR_FREQ_5k)) {
//                        V_out = VALVE_VOLTAGE_LIMIT * 1000.0f;
//                        pos_plus_end = pos.sen;
//                    } else if (TMR3_COUNT_DEADZONE < TMR_FREQ_5k) {
//                        V_out = -VALVE_VOLTAGE_LIMIT * 1000.0f;
//                        pos_minus_end = pos.sen;
//                    } else if (TMR3_COUNT_DEADZONE == TMR_FREQ_5k) need_enc_init = false;
//                    temp_time = TMR_FREQ_5k;
//                }
//
//                if (temp_time <= TMR3_COUNT_DEADZONE && TMR3_COUNT_DEADZONE < (temp_time + TMR_FREQ_5k)) {
//                    V_out = (float) P_GAIN_JOINT_POSITION * (0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end - (float) pos.sen);
//                    VALVE_CENTER = VALVE_DEADZONE_PLUS = VALVE_DEADZONE_MINUS = 0;
//
//                } else if (temp_time <= TMR3_COUNT_DEADZONE && TMR3_COUNT_DEADZONE < (temp_time + (int) (1.9f * (float) TMR_FREQ_5k))) {
//                    V_out = 0;
//                    CUR_VELOCITY_sum += CUR_VELOCITY;
//                } else if (TMR3_COUNT_DEADZONE == (temp_time + 2 * TMR_FREQ_5k)) {
//                    if (CUR_VELOCITY_sum == 0) DZ_dir = 1;
//                    else if (CUR_VELOCITY_sum > 0) DZ_dir = 1;
//                    else if (CUR_VELOCITY_sum < 0) DZ_dir = -1;
//                    else DZ_temp_cnt2 = DZ_end;
//                    CUR_VELOCITY_sum = 0;
//                } else if (TMR3_COUNT_DEADZONE > (temp_time + 2 * TMR_FREQ_5k)) {
//                    if (TMR3_COUNT_DEADZONE > (temp_time + 10 * TMR_FREQ_5k)) DZ_temp_cnt2 = DZ_end;
//
//                    // Position of Dead Zone
//                    //  (CUR_VELOCITY < 0)  (CUR_VELOCITY == 0)  (CUR_VELOCITY > 0)
//                    //     |        /                 |    /                      |/
//                    //     | ______/               ___|___/                ______/|
//                    //     |/                     /   |                   /       |
//                    //    /|                     /    |                  /        |
//                    //     0V                         0V                          0V
//
//                    if (DZ_temp_cnt2 < DZ_end) {
//                        if (TMR3_COUNT_DEADZONE % 20 != 0) {
//                            CUR_VELOCITY_sum += CUR_VELOCITY;
//                        } else {
//                            V_out -= DZ_dir;
//                            if (CUR_VELOCITY_sum * DZ_dir < 0) DZ_temp_cnt++;
//                            CUR_VELOCITY_sum = 0;
//                        }
//                        if (DZ_temp_cnt == 5) {
//                            if (DZ_dir >= 0) VALVE_DEADZONE_MINUS = (int16_t) V_out;
//                            else VALVE_DEADZONE_PLUS = (int16_t) V_out;
//                            DZ_dir = -DZ_dir;
//                            DZ_temp_cnt = 0;
//                            DZ_temp_cnt2++;
//                        }
//                    } else {
//                        TMR3_COUNT_DEADZONE = -1;
//                        VALVE_CENTER = VALVE_DEADZONE_PLUS / 2 + VALVE_DEADZONE_MINUS / 2;
//                        if (VALVE_DEADZONE_PLUS < VALVE_DEADZONE_MINUS) {
//                            VALVE_DEADZONE_PLUS = VALVE_CENTER;
//                            VALVE_DEADZONE_MINUS = VALVE_CENTER;
//                        }
//                        V_out = 0;
//
//                        ROM_RESET_DATA();
//
//                        //spi_eeprom_write(RID_VALVE_DEADZONE_PLUS, VALVE_DEADZONE_PLUS);
//                        //spi_eeprom_write(RID_VALVE_DEADZONE_MINUS, VALVE_DEADZONE_MINUS);
//
//                        CONTROL_MODE = MODE_NO_ACT;
//                        DZ_temp_cnt2 = 0;
//                    }
//                }
//                TMR3_COUNT_DEADZONE++;
//                break;
//            }

            case MODE_FIND_HOME: {
                if (FINDHOME_STAGE == FINDHOME_INIT) {
                    cnt_findhome = 0;
                    cnt_vel_findhome = 0;
                    //REFERENCE_MODE = MODE_REF_NO_ACT; // Stop taking reference data from PODO
                    pos.ref = pos.sen;
                    vel.ref = 0.0f;
                    FINDHOME_STAGE = FINDHOME_GOTOLIMIT;
                } else if (FINDHOME_STAGE == FINDHOME_GOTOLIMIT) {
                    int cnt_check_enc = (TMR_FREQ_5k/20);
                    if(cnt_findhome%cnt_check_enc == 0) {
                        FINDHOME_POSITION = pos.sen;
                        FINDHOME_VELOCITY = FINDHOME_POSITION - FINDHOME_POSITION_OLD;
                        FINDHOME_POSITION_OLD = FINDHOME_POSITION;
                    }
                    cnt_findhome++;

                    if (abs(FINDHOME_VELOCITY) <= 1) {
                        cnt_vel_findhome = cnt_vel_findhome + 1;
                    } else {
                        cnt_vel_findhome = 0;
                    }

                    if ((cnt_vel_findhome < 3*TMR_FREQ_5k) &&  cnt_findhome < 10*TMR_FREQ_5k) { // wait for 3sec
                        //REFERENCE_MODE = MODE_REF_NO_ACT;
                        if (HOMEPOS_OFFSET > 0) pos.ref = pos.ref + 12.0f;
                        else pos.ref = pos.ref - 12.0f;

//                        pos.err = pos.ref_home_pos - pos.sen;
//                        float VALVE_POS_RAW_POS_FB = 0.0f;
//                        VALVE_POS_RAW_POS_FB = (float) P_GAIN_JOINT_POSITION * pos.err/(float) ENC_PULSE_PER_POSITION * 0.01f;
//                        valve_pos.ref = VALVE_POS_RAW_POS_FB + (float) VALVE_CENTER;
//                        VALVE_POS_CONTROL(valve_pos.ref);

                        CONTROL_MODE = MODE_JOINT_CONTROL;
                        alpha_trans = 0.0f;


                    } else {
                        ENC_SET(HOMEPOS_OFFSET);
//                        ENC_SET_ZERO();
                        INIT_REF_POS = HOMEPOS_OFFSET;
                        REF_POSITION = 0;
                        REF_VELOCITY = 0;
                        FINDHOME_POSITION = 0;
                        FINDHOME_POSITION_OLD = 0;
                        FINDHOME_VELOCITY = 0;
                        cnt_findhome = 0;
                        cnt_vel_findhome = 0;
                        FINDHOME_STAGE = FINDHOME_ZEROPOSE;


                        cnt_findhome = 0;
                        pos.ref = 0.0f;
                        vel.ref = 0.0f;
                        pos.ref_home_pos = 0.0f;
                        vel.ref_home_pos = 0.0f;
                        //FINDHOME_STAGE = FINDHOME_INIT;
                        //CONTROL_UTILITY_MODE = MODE_JOINT_CONTROL;


                    }
                } else if (FINDHOME_STAGE == FINDHOME_ZEROPOSE) {
                    int T_move = 2*TMR_FREQ_5k;
                    pos.ref = (0.0f - (float)INIT_REF_POS)*0.5f*(1.0f - cos(3.14159f * (float)cnt_findhome / (float)T_move)) + (float)INIT_REF_POS;
                    //pos.ref = 0.0f;
                    vel.ref = 0.0f;

                    // input for position control

//                    CONTROL_MODE = MODE_JOINT_CONTROL;
                    alpha_trans = 0.0f;

                    double torq_ref = 0.0f;
                    pos.err = (pos.ref - pos.sen)/(float)(ENC_PULSE_PER_POSITION); //[mm]
                    vel.err = (0.0f - vel.sen)/(float)(ENC_PULSE_PER_POSITION); //[mm/s]
                    pos.err_sum += pos.err/(float) TMR_FREQ_5k; //[mm]

                    if (((OPERATING_MODE&0b110)>>1) == 0 || ((OPERATING_MODE&0b110)>>1) == 1) {

                        double I_REF_POS = 0.0f;
                        double I_REF_FORCE_FB = 0.0f; // I_REF by Force Feedback
                        double I_REF_VC = 0.0f; // I_REF for velocity compensation

                        double temp_vel_pos = 0.0f;
                        double temp_vel_torq = 0.0f;
                        double wn_Pos = 2.0f * PI * 5.0f; // f_cut : 5Hz Position Control

                        if ((OPERATING_MODE & 0x01) == 0) { // Rotary Mode
                            temp_vel_pos = (0.01f * (double) P_GAIN_JOINT_POSITION * wn_Pos * pos.err + 0.01f * (double) I_GAIN_JOINT_POSITION * wn_Pos * pos.err_sum + 0.01f * (double) VELOCITY_COMP_GAIN * vel.ref / ENC_PULSE_PER_POSITION) * 3.14159f / 180.0f; // rad/s
                            //                            L when P-gain = 100, f_cut = 10Hz                                 L feedforward velocity
                        } else if ((OPERATING_MODE & 0x01) == 1) {
                            temp_vel_pos = (0.01f * (double) P_GAIN_JOINT_POSITION * wn_Pos * pos.err + 0.01f * (double) I_GAIN_JOINT_POSITION * wn_Pos * pos.err_sum + 0.01f * (double) VELOCITY_COMP_GAIN * vel.ref / ENC_PULSE_PER_POSITION); // mm/s
                            //                            L when P-gain = 100, f_cut = 10Hz                                 L feedforward velocity
                        }
                        if (temp_vel_pos > 0.0f) I_REF_POS = temp_vel_pos * ((double) PISTON_AREA_A * 0.00006f / (K_v * sqrt(2.0f * alpha3 / (alpha3 + 1.0f))));
                        else I_REF_POS = temp_vel_pos * ((double) PISTON_AREA_B * 0.00006f / (K_v * sqrt(2.0f / (alpha3 + 1.0f))));

                        I_REF = I_REF_POS;



                    } else {
                        float VALVE_POS_RAW_FORCE_FB = 0.0f;
                        VALVE_POS_RAW_FORCE_FB = DDV_JOINT_POS_FF(vel.sen) + (P_GAIN_JOINT_POSITION * 0.01f * pos.err + DDV_JOINT_POS_FF(vel.ref));

                        if (VALVE_POS_RAW_FORCE_FB >= 0) {
                            valve_pos.ref = VALVE_POS_RAW_FORCE_FB + VALVE_DEADZONE_PLUS;
                        } else {
                            valve_pos.ref = VALVE_POS_RAW_FORCE_FB + VALVE_DEADZONE_MINUS;
                        }

                        VALVE_POS_CONTROL(valve_pos.ref);

                        V_out = (float) Vout.ref;

                    }




//                    pos.err = pos.ref - (float)pos.sen;
//                    float VALVE_POS_RAW_POS_FB = 0.0f;
//                    VALVE_POS_RAW_POS_FB = (float) P_GAIN_JOINT_POSITION * 0.01f * pos.err/(float) ENC_PULSE_PER_POSITION;
//                    valve_pos.ref = VALVE_POS_RAW_POS_FB + (float) VALVE_CENTER;
//                    VALVE_POS_CONTROL(valve_pos.ref);

                    cnt_findhome++;
                    if (cnt_findhome >= T_move) {
                        //REFERENCE_MODE = MODE_REF_DIRECT;
                        cnt_findhome = 0;
                        pos.ref = 0.0f;
                        vel.ref = 0.0f;
                        pos.ref_home_pos = 0.0f;
                        vel.ref_home_pos = 0.0f;
                        FINDHOME_STAGE = FINDHOME_INIT;
                        CONTROL_UTILITY_MODE = MODE_JOINT_CONTROL;
                    }
                }

                break;
            }

//            case MODE_VALVE_GAIN_SETTING: {
//                if (TMR3_COUNT_FLOWRATE == 0) {
//                    if (pos_plus_end == pos_minus_end) need_enc_init = true;
//                    else {
//                        V_out = -VALVE_VOLTAGE_LIMIT * 1000.0f;
//                        temp_time = (int) (0.5f * (float) TMR_FREQ_5k);
//                    }
//                }
//                if (need_enc_init) {
//                    if (TMR3_COUNT_FLOWRATE < (int) (0.5f * (float) TMR_FREQ_5k)) {
//                        V_out = VALVE_VOLTAGE_LIMIT * 1000.0f;
//                        pos_plus_end = pos.sen;
//                    } else if (TMR3_COUNT_FLOWRATE < TMR_FREQ_5k) {
//                        V_out = -VALVE_VOLTAGE_LIMIT * 1000.0f;
//                        pos_minus_end = pos.sen;
//                    } else if (TMR3_COUNT_FLOWRATE == TMR_FREQ_5k) {
//                        need_enc_init = false;
//                        check_vel_pos_init = (int) (0.9f * (float) (pos_plus_end - pos_minus_end));
//                        check_vel_pos_fin = (int) (0.95f * (float) (pos_plus_end - pos_minus_end));
//                        check_vel_pos_interv = check_vel_pos_fin - check_vel_pos_init;
//                    }
//                    temp_time = TMR_FREQ_5k;
//                }
//                TMR3_COUNT_FLOWRATE++;
//                if (TMR3_COUNT_FLOWRATE > temp_time) {
//                    if (flag_flowrate % 2 == 0) { // (+)
//                        VALVE_VOLTAGE = 1000.0f * (float) (flag_flowrate / 2 + 1);
//                        V_out = VALVE_VOLTAGE;
//                        if (pos.sen > (pos_minus_end + check_vel_pos_init) && pos.sen < (pos_minus_end + check_vel_pos_fin)) {
//                            fl_temp_cnt++;
//                        } else if (pos.sen >= (pos_minus_end + check_vel_pos_fin) && CUR_VELOCITY == 0) {
//                            VALVE_GAIN_LPM_PER_V[flag_flowrate] = 0.95873f * 0.5757f * (float) TMR_FREQ_5k / 10000.0 * (float) check_vel_pos_interv / (float) fl_temp_cnt / VALVE_VOLTAGE; // 0.9587=6*pi/65536*10000 0.5757=0.02525*0.02*0.0095*2*60*1000
//                            //                        VALVE_GAIN_LPM_PER_V[flag_flowrate] = (float) TMR_FREQ_10k * (float) check_vel_pos_interv / (float) fl_temp_cnt / VALVE_VOLTAGE; // PULSE/sec
//                            fl_temp_cnt2++;
//                        }
//                    } else if (flag_flowrate % 2 == 1) { // (-)
//                        VALVE_VOLTAGE = -1. * (float) (flag_flowrate / 2 + 1);
//                        V_out = VALVE_VOLTAGE;
//                        if (pos.sen < (pos_plus_end - check_vel_pos_init) && pos.sen > (pos_plus_end - check_vel_pos_fin)) {
//                            fl_temp_cnt++;
//                        } else if (pos.sen <= (pos_plus_end - check_vel_pos_fin) && CUR_VELOCITY == 0) {
//                            VALVE_GAIN_LPM_PER_V[flag_flowrate] = 0.95873f * 0.5757f * (float) TMR_FREQ_5k / 10000.0f * (float) check_vel_pos_interv / (float) fl_temp_cnt / (-VALVE_VOLTAGE);
//                            //                        VALVE_GAIN_LPM_PER_V[flag_flowrate] = (float) TMR_FREQ_10k * (float) check_vel_pos_interv / (float) fl_temp_cnt / (-VALVE_VOLTAGE); // PULSE/sec
//                            fl_temp_cnt2++;
//                        }
//                    }
//                    if (fl_temp_cnt2 == 100) {
//
//                        ROM_RESET_DATA();
//
//                        //spi_eeprom_write(RID_VALVE_GAIN_PLUS_1 + flag_flowrate, (int16_t) (VALVE_GAIN_LPM_PER_V[flag_flowrate] * 100.0f));
//                        cur_vel_sum = 0;
//                        fl_temp_cnt = 0;
//                        fl_temp_cnt2 = 0;
//                        flag_flowrate++;
//                    }
//                    if (flag_flowrate == 10) {
//                        V_out = 0;
//                        flag_flowrate = 0;
//                        TMR3_COUNT_FLOWRATE = 0;
//                        valve_gain_repeat_cnt++;
//                        if (valve_gain_repeat_cnt >= 1) {
//                            CONTROL_MODE = MODE_NO_ACT;
//                            valve_gain_repeat_cnt = 0;
//                        }
//
//                    }
//                    break;
//                }
//
//            }
            case MODE_PRESSURE_SENSOR_NULLING: {
                // DAC Voltage reference set
                if (TMR3_COUNT_PRES_NULL < TMR_FREQ_5k * 2) {
                    CUR_PRES_A_sum += pres_A.sen;
                    CUR_PRES_B_sum += pres_B.sen;

                    if (TMR3_COUNT_PRES_NULL % 10 == 0) {
                        CUR_PRES_A_mean = CUR_PRES_A_sum / 10.0f;
                        CUR_PRES_B_mean = CUR_PRES_B_sum / 10.0f;
                        CUR_PRES_A_sum = 0;
                        CUR_PRES_B_sum = 0;

                        float VREF_NullingGain = 0.0003f;
                        PRES_A_VREF = PRES_A_VREF + VREF_NullingGain * CUR_PRES_A_mean;
                        PRES_B_VREF = PRES_B_VREF + VREF_NullingGain * CUR_PRES_B_mean;

                        if (PRES_A_VREF > 3.3f) PRES_A_VREF = 3.3f;
                        if (PRES_A_VREF < 0.0f) PRES_A_VREF = 0.0f;
                        if (PRES_B_VREF > 3.3f) PRES_B_VREF = 3.3f;
                        if (PRES_B_VREF < 0.0f) PRES_B_VREF = 0.0f;

                        dac_1 = PRES_A_VREF / 3.3f;
                        dac_2 = PRES_B_VREF / 3.3f;
                    }
                } else {
                    CONTROL_UTILITY_MODE = MODE_NO_ACT;
                    TMR3_COUNT_PRES_NULL = 0;
                    CUR_PRES_A_sum = 0;
                    CUR_PRES_B_sum = 0;
                    CUR_PRES_A_mean = 0;
                    CUR_PRES_B_mean = 0;

//                    ROM_RESET_DATA();
                    spi_eeprom_write(RID_PRES_A_SENSOR_VREF, (int16_t) (PRES_A_VREF * 1000.0f));
                    spi_eeprom_write(RID_PRES_B_SENSOR_VREF, (int16_t) (PRES_B_VREF * 1000.0f));

                    dac_1 = PRES_A_VREF / 3.3f;
                    dac_2 = PRES_B_VREF / 3.3f;
                    //pc.printf("nulling end");
                }
                TMR3_COUNT_PRES_NULL++;
                break;
            }

//            case MODE_PRESSURE_SENSOR_CALIB: {
//                if (TMR3_COUNT_PRES_CALIB < 2 * TMR_FREQ_5k) {
//                    V_out = -VALVE_VOLTAGE_LIMIT * 1000.0f;
//                    if (TMR3_COUNT_PRES_CALIB >= TMR_FREQ_5k) {
//                        CUR_PRES_A_sum += CUR_PRES_A;
//                    }
//                } else if (TMR3_COUNT_PRES_CALIB < 4 * TMR_FREQ_5k) {
//                    V_out = VALVE_VOLTAGE_LIMIT * 1000.0f;
//                    if (TMR3_COUNT_PRES_CALIB >= 3 * TMR_FREQ_5k) {
//                        CUR_PRES_B_sum += CUR_PRES_B;
//                    }
//                } else {
//                    CONTROL_MODE = MODE_NO_ACT;
//                    TMR3_COUNT_PRES_CALIB = 0;
//                    V_out = 0;
//                    PRES_SENSOR_A_PULSE_PER_BAR = CUR_PRES_A_sum / ((float) TMR_FREQ_5k - 1.0f) - PRES_A_NULL;
//                    PRES_SENSOR_A_PULSE_PER_BAR = PRES_SENSOR_A_PULSE_PER_BAR / ((float) PRES_SUPPLY - 1.0f);
//                    PRES_SENSOR_B_PULSE_PER_BAR = CUR_PRES_B_sum / ((float) TMR_FREQ_5k - 1.0f) - PRES_B_NULL;
//                    PRES_SENSOR_B_PULSE_PER_BAR = PRES_SENSOR_B_PULSE_PER_BAR / ((float) PRES_SUPPLY - 1.0f);
//                    CUR_PRES_A_sum = 0;
//                    CUR_PRES_B_sum = 0;
//                    CUR_PRES_A_mean = 0;
//                    CUR_PRES_B_mean = 0;
//
//                    ROM_RESET_DATA();
//
//                    //spi_eeprom_write(RID_PRES_SENSOR_A_PULSE_PER_BAR, (int16_t) (PRES_SENSOR_A_PULSE_PER_BAR * 100.0f));
//                    //spi_eeprom_write(RID_PRES_SENSOR_B_PULSE_PER_BAR, (int16_t) (PRES_SENSOR_B_PULSE_PER_BAR * 100.0f));
//                }
//                TMR3_COUNT_PRES_CALIB++;
//                break;
//            }

//            case MODE_ROTARY_FRICTION_TUNING: {
//                if (TMR3_COUNT_ROTARY_FRIC_TUNE % (5 * TMR_FREQ_5k) == 0) freq_fric_tune = 4.0f + 3.0f * sin(2 * 3.14159f * 0.5f * TMR3_COUNT_ROTARY_FRIC_TUNE * 0.0001f * 0.05f);
//                V_out = PWM_out * sin(2 * 3.14159f * freq_fric_tune * TMR3_COUNT_ROTARY_FRIC_TUNE * 0.0001f);
//                if (V_out > 0) V_out = VALVE_VOLTAGE_LIMIT * 1000.0f;
//                else V_out = -VALVE_VOLTAGE_LIMIT * 1000.0f;
//                TMR3_COUNT_ROTARY_FRIC_TUNE++;
//                if (TMR3_COUNT_ROTARY_FRIC_TUNE > TUNING_TIME * TMR_FREQ_5k) {
//                    TMR3_COUNT_ROTARY_FRIC_TUNE = 0;
//                    V_out = 0.0f;
//                    CONTROL_MODE = MODE_NO_ACT;
//                }
//                break;
//            }

            case MODE_DDV_POS_VS_PWM_ID: {
                CONTROL_MODE = MODE_VALVE_OPEN_LOOP;
                VALVE_ID_timer = VALVE_ID_timer + 1;

                if(VALVE_ID_timer < TMR_FREQ_5k*1) {
                    Vout.ref = 3000.0f * sin(2.0f*3.14f*VALVE_ID_timer/TMR_FREQ_5k * 100.0f);
                } else if(VALVE_ID_timer < TMR_FREQ_5k*2) {
                    Vout.ref = 1000.0f*(ID_index_array[ID_index]);
                } else if(VALVE_ID_timer == TMR_FREQ_5k*2) {
                    VALVE_POS_TMP = 0;
                    data_num = 0;
                } else if(VALVE_ID_timer < TMR_FREQ_5k*3) {
                    data_num = data_num + 1;
                    VALVE_POS_TMP = VALVE_POS_TMP + value;
                } else if(VALVE_ID_timer == TMR_FREQ_5k*3) {
                    Vout.ref = 0.0f;
                } else {
                    VALVE_POS_AVG[ID_index] = VALVE_POS_TMP / data_num;
                    VALVE_ID_timer = 0;
                    ID_index= ID_index +1;
                }

                if(ID_index>=25) {
                    int i;
                    VALVE_POS_AVG_OLD = VALVE_POS_AVG[0];
                    for(i=0; i<25; i++) {
                        VALVE_POS_VS_PWM[i] = (int16_t) (VALVE_POS_AVG[i]);
                        if(VALVE_POS_AVG[i] > VALVE_POS_AVG_OLD) {
                            VALVE_MAX_POS = VALVE_POS_AVG[i];
                            VALVE_POS_AVG_OLD = VALVE_MAX_POS;
                        } else if(VALVE_POS_AVG[i] < VALVE_POS_AVG_OLD) {
                            VALVE_MIN_POS = VALVE_POS_AVG[i];
                            VALVE_POS_AVG_OLD = VALVE_MIN_POS;
                        }
                    }
//                    ROM_RESET_DATA();
                    spi_eeprom_write(RID_VALVE_MAX_POS, (int16_t) VALVE_MAX_POS);
                    spi_eeprom_write(RID_VALVE_MIN_POS, (int16_t) VALVE_MIN_POS);
                    for(int i=0; i<25; i++) {
                        spi_eeprom_write(RID_VALVE_POS_VS_PWM_0 + i, (int16_t) VALVE_POS_VS_PWM[i]);
                    }
                    ID_index = 0;
                    CONTROL_UTILITY_MODE = MODE_NO_ACT;
                }


                break;
            }

            case MODE_DDV_DEADZONE_AND_CENTER: {
                CONTROL_MODE = MODE_VALVE_OPEN_LOOP;
                VALVE_DZ_timer = VALVE_DZ_timer + 1;
                if(first_check == 0) {
                    if(VALVE_DZ_timer < (int) (1.0f * (float) TMR_FREQ_5k)) {
                        Vout.ref = VALVE_VOLTAGE_LIMIT * 1000.0f;
                    } else if(VALVE_DZ_timer == (int) (1.0f * (float) TMR_FREQ_5k)) {
                        Vout.ref = VALVE_VOLTAGE_LIMIT * 1000.0f;
                        pos_plus_end = pos.sen;
                    } else if(VALVE_DZ_timer < (int) (2.0f * (float) TMR_FREQ_5k)) {
                        Vout.ref = -VALVE_VOLTAGE_LIMIT * 1000.0f;
                    } else if(VALVE_DZ_timer == (int) (2.0f * (float) TMR_FREQ_5k)) {
                        Vout.ref = -VALVE_VOLTAGE_LIMIT * 1000.0f;
                        pos_minus_end = pos.sen;
                    } else if(VALVE_DZ_timer < (int) (3.0f * (float) TMR_FREQ_5k)) {
                        Vout.ref = (float) P_GAIN_JOINT_POSITION * (0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end - (float) pos.sen)/(float) ENC_PULSE_PER_POSITION;
                    } else if(VALVE_DZ_timer < (int) (4.0f * (float) TMR_FREQ_5k)) {
                        Vout.ref = (float) P_GAIN_JOINT_POSITION * (0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end - (float) pos.sen)/(float) ENC_PULSE_PER_POSITION;
                        data_num = data_num + 1;
                        VALVE_POS_TMP = VALVE_POS_TMP + value;
                    } else if(VALVE_DZ_timer == (int) (4.0f * (float) TMR_FREQ_5k)) {
                        Vout.ref = (float) P_GAIN_JOINT_POSITION * (0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end - (float) pos.sen)/(float) ENC_PULSE_PER_POSITION;
                        DDV_POS_AVG = VALVE_POS_TMP / data_num;
                        START_POS = pos.sen;
                        VALVE_POS_TMP = 0;
                        data_num = 0;

                    } else if(VALVE_DZ_timer < (int) (5.0f * (float) TMR_FREQ_5k)) {
                        valve_pos.ref = DDV_POS_AVG;
                        VALVE_POS_CONTROL(valve_pos.ref);

                    } else if(VALVE_DZ_timer < (int) (6.0f * (float) TMR_FREQ_5k)) {
                        valve_pos.ref = DDV_POS_AVG;
                        VALVE_POS_CONTROL(valve_pos.ref);

                    } else if(VALVE_DZ_timer == (int) (6.0f * (float) TMR_FREQ_5k)) {
                        valve_pos.ref = DDV_POS_AVG;
                        VALVE_POS_CONTROL(valve_pos.ref);
                        FINAL_POS = pos.sen;

                        if((FINAL_POS - START_POS)>200) {
                            DZ_case = 1;
                        } else if((FINAL_POS - START_POS)<-200) {
                            DZ_case = -1;
                        } else {
                            DZ_case = 0;
                        }

                        CAN_TX_PRES((int16_t) (DZ_case), (int16_t) (6));

                        first_check = 1;
                        DZ_DIRECTION = 1;
                        VALVE_DZ_timer = 0;
                        Ref_Valve_Pos_Old = DDV_POS_AVG;
                        DZ_NUM = 1;
                        DZ_index = 1;

                    }
                } else {
                    if((DZ_case == -1 && DZ_NUM == 1) | (DZ_case == 1 && DZ_NUM == 1)) {
                        if(VALVE_DZ_timer < (int) (1.0 * (float) TMR_FREQ_5k)) {
                            Vout.ref = (float) P_GAIN_JOINT_POSITION * (0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end - (float) pos.sen)/(float) ENC_PULSE_PER_POSITION;
                            //pos.ref = 0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end;
                            //CONTROL_MODE = MODE_JOINT_CONTROL;
                        } else if(VALVE_DZ_timer == (int) (1.0f * (float) TMR_FREQ_5k)) {
                            START_POS = pos.sen;
                        } else if(VALVE_DZ_timer < (int) (2.0f * (float) TMR_FREQ_5k)) {
                            valve_pos.ref = Ref_Valve_Pos_Old  - DZ_case * DZ_DIRECTION * 64 / DZ_index;
                            if(valve_pos.ref <= VALVE_MIN_POS) {
                                valve_pos.ref = VALVE_MIN_POS;
                            } else if(valve_pos.ref >= VALVE_MAX_POS) {
                                valve_pos.ref = VALVE_MAX_POS;
                            }
                            VALVE_POS_CONTROL(valve_pos.ref);

                        } else if(VALVE_DZ_timer == (int) (2.0f * (float) TMR_FREQ_5k)) {
                            Ref_Valve_Pos_Old = valve_pos.ref;
                            FINAL_POS = pos.sen;

                            if((FINAL_POS - START_POS)>100) {
                                DZ_DIRECTION = 1 * DZ_case;
                            } else if((FINAL_POS - START_POS)<-100) {
                                DZ_DIRECTION = -1 * DZ_case;
                            } else {
                                DZ_DIRECTION = 1 * DZ_case;
                            }

                            VALVE_DZ_timer = 0;
                            DZ_index= DZ_index *2;
                            if(DZ_index >= 128) {
                                FIRST_DZ = valve_pos.ref;
                                DZ_NUM = 2;
                                Ref_Valve_Pos_Old = FIRST_DZ;
                                DZ_index = 1;
                                DZ_DIRECTION = 1;
                            }
                        }
                    } else if((DZ_case == -1 && DZ_NUM == 2) | (DZ_case == 1 && DZ_NUM == 2)) {
                        if(VALVE_DZ_timer < (int) (1.0f * (float) TMR_FREQ_5k)) {
                            Vout.ref = (float) P_GAIN_JOINT_POSITION * (0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end - (float) pos.sen)/(float) ENC_PULSE_PER_POSITION;
                            //pos.ref = 0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end;
                            //CONTROL_MODE = MODE_JOINT_CONTROL;
                        } else if(VALVE_DZ_timer == (int) (1.0f * (float) TMR_FREQ_5k)) {
                            START_POS = pos.sen;
                        } else if(VALVE_DZ_timer < (int) (2.0f * (float) TMR_FREQ_5k)) {
                            valve_pos.ref = Ref_Valve_Pos_Old  - DZ_case * DZ_DIRECTION * 64 / DZ_index;
                            if(valve_pos.ref <= VALVE_MIN_POS) {
                                valve_pos.ref = VALVE_MIN_POS;
                            } else if(valve_pos.ref >= VALVE_MAX_POS) {
                                valve_pos.ref = VALVE_MAX_POS;
                            }
                            VALVE_POS_CONTROL(valve_pos.ref);

                        } else if(VALVE_DZ_timer == (int) (2.0f * (float) TMR_FREQ_5k)) {
                            Vout.ref = 0.0f;
                        } else if(VALVE_DZ_timer > (int) (2.0f * (float) TMR_FREQ_5k)) {
                            Ref_Valve_Pos_Old = valve_pos.ref;
                            FINAL_POS = pos.sen;

                            if((FINAL_POS - START_POS)>100) {
                                DZ_DIRECTION = 1 * DZ_case;
                            } else if((FINAL_POS - START_POS)<-100) {
                                DZ_DIRECTION = -1 * DZ_case;
                            } else {
                                DZ_DIRECTION = -1 * DZ_case;
                            }

                            VALVE_DZ_timer = 0;
                            DZ_index= DZ_index * 2;
                            if(DZ_index >= 128) {
                                SECOND_DZ = valve_pos.ref;
                                VALVE_CENTER = (int) (0.5f * (float) (FIRST_DZ) + 0.5f * (float) (SECOND_DZ));
                                first_check = 0;
                                VALVE_DEADZONE_MINUS = (float) FIRST_DZ;
                                VALVE_DEADZONE_PLUS = (float) SECOND_DZ;

//                                ROM_RESET_DATA();
                                spi_eeprom_write(RID_VALVE_CNETER, (int16_t) VALVE_CENTER);
                                spi_eeprom_write(RID_VALVE_MAX_POS, (int16_t) VALVE_MAX_POS);
                                spi_eeprom_write(RID_VALVE_MIN_POS, (int16_t) VALVE_MIN_POS);

                                CONTROL_UTILITY_MODE = MODE_NO_ACT;
                                DZ_index = 1;
                            }
                        }
                    } else if(DZ_case == 0 && DZ_NUM ==1) {
                        if(VALVE_DZ_timer < (int) (1.0f * (float) TMR_FREQ_5k)) {
                            Vout.ref = (float) P_GAIN_JOINT_POSITION * (0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end - (float) pos.sen)/(float) ENC_PULSE_PER_POSITION;
                            //pos.ref = 0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end;
                            //CONTROL_MODE = MODE_JOINT_CONTROL;
                        } else if(VALVE_DZ_timer == (int) (1.0f * (float) TMR_FREQ_5k)) {
                            START_POS = pos.sen;
                        } else if(VALVE_DZ_timer < (int) (2.0f * (float) TMR_FREQ_5k)) {
                            valve_pos.ref = Ref_Valve_Pos_Old  - DZ_DIRECTION * 64 / DZ_index;
                            if(valve_pos.ref <= VALVE_MIN_POS) {
                                valve_pos.ref = VALVE_MIN_POS;
                            } else if(valve_pos.ref >= VALVE_MAX_POS) {
                                valve_pos.ref = VALVE_MAX_POS;
                            }
                            VALVE_POS_CONTROL(valve_pos.ref);

                        } else if(VALVE_DZ_timer == (int) (2.0f * (float) TMR_FREQ_5k)) {
                            Ref_Valve_Pos_Old = valve_pos.ref;
                            FINAL_POS = pos.sen;

                            if((FINAL_POS - START_POS)>100) {
                                DZ_DIRECTION = 1;
                            } else if((FINAL_POS - START_POS)<-100) {
                                DZ_DIRECTION = -1;
                            } else {
                                DZ_DIRECTION = 1;
                            }
                            VALVE_DZ_timer = 0;
                            DZ_index= DZ_index *2;
                            if(DZ_index >= 128) {
                                FIRST_DZ = valve_pos.ref;
                                DZ_NUM = 2;
                                Ref_Valve_Pos_Old = FIRST_DZ;
                                DZ_index = 1;
                                DZ_DIRECTION = 1;
                            }
                        }
                    } else {
                        if(VALVE_DZ_timer < (int) (1.0f * (float) TMR_FREQ_5k)) {
                            Vout.ref = (float) P_GAIN_JOINT_POSITION * (0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end - (float) pos.sen)/(float) ENC_PULSE_PER_POSITION;
                            //pos.ref = 0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end;
                            //CONTROL_MODE = MODE_JOINT_CONTROL;
                        } else if(VALVE_DZ_timer == (int) (1.0f * (float) TMR_FREQ_5k)) {
                            START_POS = pos.sen;
                        } else if(VALVE_DZ_timer < (int) (2.0f * (float) TMR_FREQ_5k)) {
                            valve_pos.ref = Ref_Valve_Pos_Old  + DZ_DIRECTION * 64 / DZ_index;
                            if(valve_pos.ref <= VALVE_MIN_POS) {
                                valve_pos.ref = VALVE_MIN_POS;
                            } else if(valve_pos.ref > VALVE_MAX_POS) {
                                valve_pos.ref = VALVE_MAX_POS - 1;
                            }
                            VALVE_POS_CONTROL(valve_pos.ref);

                        } else if(VALVE_DZ_timer == (int) (2.0f * (float) TMR_FREQ_5k)) {
                            Vout.ref = 0.0f;
                        } else if(VALVE_DZ_timer > (int) (2.0f * (float) TMR_FREQ_5k)) {
                            Ref_Valve_Pos_Old = valve_pos.ref;
                            FINAL_POS = pos.sen;

                            if((FINAL_POS - START_POS)>100) {
                                DZ_DIRECTION = 1;
                            } else if((FINAL_POS - START_POS)<-100) {
                                DZ_DIRECTION = -1;
                            } else {
                                DZ_DIRECTION = 1;
                            }

                            VALVE_DZ_timer = 0;
                            DZ_index= DZ_index *2;
                            if(DZ_index >= 128) {
                                SECOND_DZ = valve_pos.ref;
                                VALVE_CENTER = (int) (0.5f * (float) (FIRST_DZ) + 0.5f * (float) (SECOND_DZ));
                                first_check = 0;
                                VALVE_DEADZONE_MINUS = (float) FIRST_DZ;
                                VALVE_DEADZONE_PLUS = (float) SECOND_DZ;

//                                ROM_RESET_DATA();
                                spi_eeprom_write(RID_VALVE_CNETER, (int16_t) VALVE_CENTER);
                                spi_eeprom_write(RID_VALVE_MAX_POS, (int16_t) VALVE_MAX_POS);
                                spi_eeprom_write(RID_VALVE_MIN_POS, (int16_t) VALVE_MIN_POS);

                                CONTROL_UTILITY_MODE = MODE_NO_ACT;
                                DZ_index = 1;
                            }
                        }
                    }
                }
                break;
            }

            case MODE_DDV_POS_VS_FLOWRATE: {
                CONTROL_MODE = MODE_VALVE_OPEN_LOOP;
                VALVE_FR_timer = VALVE_FR_timer + 1;
                if(first_check == 0) {
                    if(VALVE_FR_timer < (int) (1.0f * (float) TMR_FREQ_5k)) {
                        Vout.ref = VALVE_VOLTAGE_LIMIT * 1000.0f;
                        //CAN_TX_PRES((int16_t) (VALVE_FR_timer), (int16_t) (6));
                    } else if(VALVE_FR_timer == (int) (1.0f * (float) TMR_FREQ_5k)) {
                        Vout.ref = VALVE_VOLTAGE_LIMIT * 1000.0f;
                        pos_plus_end = pos.sen;
                        //                    CAN_TX_PRES((int16_t) (V_out), (int16_t) (7));
                    } else if(VALVE_FR_timer < (int) (2.0f * (float) TMR_FREQ_5k)) {
                        Vout.ref = -VALVE_VOLTAGE_LIMIT * 1000.0f;
                    } else if(VALVE_FR_timer == (int) (2.0f * (float) TMR_FREQ_5k)) {
                        //                    CAN_TX_PRES((int16_t) (V_out), (int16_t) (8));
                        Vout.ref = -VALVE_VOLTAGE_LIMIT * 1000.0f;
                        pos_minus_end = pos.sen;
                        first_check = 1;
                        VALVE_FR_timer = 0;
                        valve_pos.ref = (float) VALVE_CENTER;
                        ID_index = 0;
                        max_check = 0;
                        min_check = 0;
                    }
                } else {
                    if(VALVE_FR_timer < (int) (1.0f * (float) TMR_FREQ_5k)) {
                        //V_out = (float) P_GAIN_JOINT_POSITION * (0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end - (float) pos.sen)/(float) ENC_PULSE_PER_POSITION;
                        pos.ref = 0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end;
                        CONTROL_MODE = MODE_JOINT_CONTROL;
                    } else if(VALVE_FR_timer == (int) (1.0f * (float) TMR_FREQ_5k)) {
                        data_num = 0;
                        valve_pos.ref = 10.0f*((float) ID_index_array[ID_index]) + (float) VALVE_CENTER;

                        VALVE_POS_CONTROL(valve_pos.ref);
                        START_POS = pos.sen;
                    } else if(VALVE_FR_timer < (int) (5.0f * (float) TMR_FREQ_5k)) {
                        valve_pos.ref = 10.0f*((float) ID_index_array[ID_index]) + (float) VALVE_CENTER;
                        VALVE_POS_CONTROL(valve_pos.ref);
                        data_num = data_num + 1;
                        if(abs(0.5f * (float) pos_plus_end + 0.5f * (float) pos_minus_end - (float) pos.sen) > 20000.0f) {
                            FINAL_POS = pos.sen;
                            one_period_end = 1;
                        }
                    } else if(VALVE_FR_timer == (int) (5.0f * (float) TMR_FREQ_5k)) {
                        FINAL_POS = pos.sen;
                        one_period_end = 1;
                        V_out = 0.0f;
                    }

                    if(one_period_end == 1) {
                        if(valve_pos.ref > VALVE_MAX_POS) {
                            max_check = 1;
                        } else if(valve_pos.ref < VALVE_MIN_POS) {
                            min_check = 1;
                        }
                        JOINT_VEL[ID_index] = (FINAL_POS - START_POS) / data_num * TMR_FREQ_5k;   //  pulse/sec

                        VALVE_FR_timer = 0;
                        one_period_end = 0;
                        ID_index= ID_index +1;
                        V_out = 0.0f;
                    }

                    if(max_check == 1 && min_check == 1) {

                        VALVE_POS_NUM = ID_index;
//                        ROM_RESET_DATA();
                        for(int i=0; i<100; i++) {
                            spi_eeprom_write(RID_VALVE_POS_VS_FLOWRATE_0 + i, (int16_t) (JOINT_VEL[i] & 0xFFFF));
                            spi_eeprom_write(RID_VALVE_POS_VS_FLOWRATE_0_1 + i, (int16_t) ((JOINT_VEL[i] >> 16) & 0xFFFF));
                        }
                        ID_index = 0;
                        first_check = 0;
                        VALVE_FR_timer = 0;
                        CONTROL_UTILITY_MODE = MODE_NO_ACT;
//                        CAN_TX_PRES((int16_t) (VALVE_FR_timer), (int16_t) (6));
                    }
                }
                break;
            }

            case MODE_SYSTEM_ID: {
                freq_sysid_Iref = (double) cnt_sysid * DT_TMR3 * 3.0f;
                valve_pos.ref = 2500.0f * sin(2.0f * 3.14159f * freq_sysid_Iref * (double) cnt_sysid * DT_TMR3);
                CONTROL_MODE = MODE_VALVE_OPEN_LOOP;
                cnt_sysid++;
                if (freq_sysid_Iref >= 300) {
                    cnt_sysid = 0;
                    CONTROL_UTILITY_MODE = MODE_NO_ACT;
                }
                break;
            }

            case MODE_FREQ_TEST: {
                float valve_pos_ref = 2500.0f * sin(2.0f * 3.141592f * freq_test_valve_ref * (float) cnt_freq_test * DT_TMR3);
                if(valve_pos_ref >= 0) {
                    valve_pos.ref = (double)VALVE_CENTER + (double)valve_pos_ref * ((double)VALVE_MAX_POS-(double)VALVE_CENTER)/10000.0f;
                } else {
                    valve_pos.ref = (double)VALVE_CENTER - (double)valve_pos_ref * ((double)VALVE_MIN_POS-(double)VALVE_CENTER)/10000.0f;
                }
                ref_array[cnt_freq_test] = valve_pos_ref;
                if(value>=(float) VALVE_CENTER) {
                    pos_array[cnt_freq_test] = 10000.0f*((double)value - (double)VALVE_CENTER)/((double)VALVE_MAX_POS - (double)VALVE_CENTER);
                } else {
                    pos_array[cnt_freq_test] = -10000.0f*((double)value - (double)VALVE_CENTER)/((double)VALVE_MIN_POS - (double)VALVE_CENTER);
                }

                CONTROL_MODE = MODE_VALVE_POSITION_CONTROL;
                cnt_freq_test++;
                if (freq_test_valve_ref * (float) cnt_freq_test * DT_TMR3 > 2) {
                    buffer_data_size = cnt_freq_test;
                    cnt_freq_test = 0;
                    cnt_send_buffer = 0;
                    freq_test_valve_ref = freq_test_valve_ref * 1.05f;
                    if (freq_test_valve_ref >= 400) {
                        CONTROL_UTILITY_MODE = MODE_NO_ACT;
                        CONTROL_MODE = MODE_NO_ACT;
                        CAN_TX_PWM((int16_t) (1)); //1300
                    }
                    CONTROL_MODE = MODE_NO_ACT;
                    CONTROL_UTILITY_MODE = MODE_SEND_OVER;

                }
                break;
            }
            case MODE_SEND_BUFFER: {
//                if (TMR2_COUNT_CAN_TX % (int) ((int) TMR_FREQ_5k/CAN_FREQ) == 0) {
//                    CAN_TX_PRES((int16_t) (pos_array[cnt_send_buffer]), (int16_t) (ref_array[cnt_send_buffer])); // 1400
//                    if(cnt_send_buffer>=buffer_data_size) {
//                        CONTROL_UTILITY_MODE = MODE_FREQ_TEST;
//                    }
//                    cnt_send_buffer++;
//                }

                break;
            }
            case MODE_SEND_OVER: {
                CAN_TX_TORQUE((int16_t) (buffer_data_size)); //1300
                CONTROL_UTILITY_MODE = MODE_NO_ACT;
                CONTROL_MODE = MODE_NO_ACT;
                break;
            }

            case MODE_STEP_TEST: {
                float valve_pos_ref = 0.0f;
                if (cnt_step_test < (int) (1.0f * (float) TMR_FREQ_5k)) {
                    valve_pos_ref = 0.0f;
                } else {
                    valve_pos_ref = 10000.0f;
                }
                if(valve_pos_ref >= 0) {
                    valve_pos.ref = (double)VALVE_CENTER + (double)valve_pos_ref * ((double)VALVE_MAX_POS-(double)VALVE_CENTER)/10000.0f;
                } else {
                    valve_pos.ref = (double)VALVE_CENTER - (double)valve_pos_ref * ((double)VALVE_MIN_POS-(double)VALVE_CENTER)/10000.0f;
                }
                ref_array[cnt_step_test] = valve_pos_ref;
                if(value>=(float) VALVE_CENTER) {
                    pos_array[cnt_step_test] = 10000.0f*((double)value - (double)VALVE_CENTER)/((double)VALVE_MAX_POS - (double)VALVE_CENTER);
                } else {
                    pos_array[cnt_step_test] = -10000.0f*((double)value - (double)VALVE_CENTER)/((double)VALVE_MIN_POS - (double)VALVE_CENTER);
                }

                CONTROL_MODE = MODE_VALVE_POSITION_CONTROL;
                cnt_step_test++;
                if (cnt_step_test > (int) (2.0f * (float) TMR_FREQ_5k)) {
                    buffer_data_size = cnt_step_test;
                    cnt_step_test = 0;
                    cnt_send_buffer = 0;
                    CONTROL_UTILITY_MODE = MODE_SEND_OVER;
                    CONTROL_MODE = MODE_NO_ACT;
                }
//                if (cnt_step_test > (int) (2.0f * (float) TMR_FREQ_5k))
//                {
//                    CONTROL_UTILITY_MODE = MODE_NO_ACT;
//                    CONTROL_MODE = MODE_NO_ACT;
//                    CAN_TX_PWM((int16_t) (1)); //1300
//                }

                break;
            }

            default:
                break;
        }

        // CONTROL MODE ------------------------------------------------------------

        switch (CONTROL_MODE) {
            case MODE_NO_ACT: {
                V_out = 0.0f;
                break;
            }

            case MODE_VALVE_POSITION_CONTROL: {
                if (OPERATING_MODE == 5) { //SW Valve
                    VALVE_POS_CONTROL(valve_pos.ref);
                    V_out = Vout.ref;
                } else if (CURRENT_CONTROL_MODE == 0) { //PWM
                    V_out = valve_pos.ref;
                } else {
                    I_REF = valve_pos.ref * 0.001f;
                }
                break;
            }

            case MODE_JOINT_CONTROL: {

                double torq_ref = 0.0f;
                pos.err = (pos.ref - pos.sen)/(float)(ENC_PULSE_PER_POSITION); //[mm]
                vel.err = (0.0f - vel.sen)/(float)(ENC_PULSE_PER_POSITION); //[mm/s]
                pos.err_sum += pos.err/(float) TMR_FREQ_5k; //[mm]

                //K & D Low Pass Filter
                float alpha_K_D = 1.0f/(1.0f + 5000.0f/(2.0f*3.14f*30.0f)); // f_cutoff : 30Hz
                K_LPF = K_LPF*(1.0f-alpha_K_D)+K_SPRING*(alpha_K_D);
                D_LPF = D_LPF*(1.0f-alpha_K_D)+D_DAMPER*(alpha_K_D);

//                torq_ref = torq.ref + K_LPF * pos.err - D_LPF * vel.sen / ENC_PULSE_PER_POSITION; //[N]
                torq_ref = torq.ref;

                // torque feedback
                torq.err = torq_ref - torq.sen; //[N]
                torq.err_sum += torq.err/(float) TMR_FREQ_5k; //[N]

                if (((OPERATING_MODE&0b110)>>1) == 0 || ((OPERATING_MODE&0b110)>>1) == 1) {

                    double I_REF_POS = 0.0f;
                    double I_REF_FORCE_FB = 0.0f; // I_REF by Force Feedback
                    double I_REF_VC = 0.0f; // I_REF for velocity compensation

                    double temp_vel_pos = 0.0f;
                    double temp_vel_torq = 0.0f;
                    double wn_Pos = 2.0f * PI * 5.0f; // f_cut : 5Hz Position Control

                    if ((OPERATING_MODE & 0x01) == 0) { // Rotary Mode
                        temp_vel_pos = (0.01f * (double) P_GAIN_JOINT_POSITION * wn_Pos * pos.err + 0.01f * (double) I_GAIN_JOINT_POSITION * wn_Pos * pos.err_sum + 0.01f * (double) VELOCITY_COMP_GAIN * vel.ref / ENC_PULSE_PER_POSITION) * PI / 180.0f; // rad/s
                        //                            L when P-gain = 100, f_cut = 10Hz                                 L feedforward velocity
                    } else if ((OPERATING_MODE & 0x01) == 1) {
                        temp_vel_pos = (0.01f * (double) P_GAIN_JOINT_POSITION * wn_Pos * pos.err + 0.01f * (double) I_GAIN_JOINT_POSITION * wn_Pos * pos.err_sum + 0.01f * (double) VELOCITY_COMP_GAIN * vel.ref / ENC_PULSE_PER_POSITION); // mm/s
                        //                            L when P-gain = 100, f_cut = 10Hz                                 L feedforward velocity
                    }
                    if (temp_vel_pos > 0.0f) I_REF_POS = temp_vel_pos * ((double) PISTON_AREA_A * 0.00006f / (K_v * sqrt(2.0f * alpha3 / (alpha3 + 1.0f))));
                    else I_REF_POS = temp_vel_pos * ((double) PISTON_AREA_B * 0.00006f / (K_v * sqrt(2.0f / (alpha3 + 1.0f))));

                    // velocity compensation for torque control
                    if ((OPERATING_MODE & 0x01) == 0) { // Rotary Mode
                        I_REF_FORCE_FB = 0.001f * ((double) P_GAIN_JOINT_TORQUE * torq.err + (double) I_GAIN_JOINT_TORQUE * torq.err_sum);
                        //                temp_vel_torq = (0.01 * (double) VELOCITY_COMP_GAIN * (double) CUR_VELOCITY / (double) ENC_PULSE_PER_POSITION) * PI / 180.0; // rad/s
                        temp_vel_torq = (0.01f * (double) VELOCITY_COMP_GAIN * vel.ref / (double) ENC_PULSE_PER_POSITION) * PI / 180.0f; // rad/s
                        //                                                          L feedforward velocity
                    } else if ((OPERATING_MODE & 0x01) == 1) {
                        I_REF_FORCE_FB = 0.001f * 0.01f*((double) P_GAIN_JOINT_TORQUE * torq.err + (double) I_GAIN_JOINT_TORQUE * torq.err_sum); // Linear Actuators are more sensitive.
                        //                temp_vel_torq = (0.01 * (double) VELOCITY_COMP_GAIN * (double) CUR_VELOCITY / (double) ENC_PULSE_PER_POSITION); // mm/s
                        temp_vel_torq = (0.01f * (double) VELOCITY_COMP_GAIN * vel.ref / (double) ENC_PULSE_PER_POSITION); // mm/s
                        //                                                          L feedforward velocity
                    }
                    if (temp_vel_torq > 0.0f) I_REF_VC = temp_vel_torq * ((double) PISTON_AREA_A * 0.00006f / (K_v * sqrt(2.0f * alpha3 / (alpha3 + 1.0f))));
                    else I_REF_VC = temp_vel_torq * ((double) PISTON_AREA_B * 0.00006f / (K_v * sqrt(2.0f / (alpha3 + 1.0f))));
                    //                                                  L   velocity(rad/s or mm/s) >> I_ref(mA)
                    //            Ref_Joint_FT_dot = (Ref_Joint_FT_Nm - Ref_Joint_FT_Nm_old) / TMR_DT_5k;
                    //            Ref_Joint_FT_Nm_old = Ref_Joint_FT_Nm;

                    I_REF = (1.0f - alpha_trans) * I_REF_POS + alpha_trans * (I_REF_VC + I_REF_FORCE_FB);

                    // Anti-windup for FT
                    if (I_GAIN_JOINT_TORQUE != 0) {
                        double I_MAX = 10.0f; // Maximum Current : 10mV
                        double Ka = 2.0f / ((double) I_GAIN_JOINT_TORQUE * 0.001f);
                        if (I_REF > I_MAX) {
                            double I_rem = I_REF - I_MAX;
                            I_rem = Ka*I_rem;
                            I_REF = I_MAX;
                            torq.err_sum = torq.err_sum - I_rem /(float) TMR_FREQ_5k;
                        } else if (I_REF < -I_MAX) {
                            double I_rem = I_REF - (-I_MAX);
                            I_rem = Ka*I_rem;
                            I_REF = -I_MAX;
                            torq.err_sum = torq.err_sum - I_rem /(float) TMR_FREQ_5k;
                        }
                    }

                } else {
                    float VALVE_POS_RAW_FORCE_FB = 0.0f;
                    float VALVE_POS_RAW_FORCE_FF = 0.0f;
                    float VALVE_POS_RAW = 0.0f;

                    VALVE_POS_RAW_FORCE_FB = alpha_trans*(((float) P_GAIN_JOINT_TORQUE * torq.err + (float) I_GAIN_JOINT_TORQUE * torq.err_sum) * 0.01f
                                                          + DDV_JOINT_POS_FF(vel.sen))+ (1.0f-alpha_trans) * (P_GAIN_JOINT_POSITION * 0.01f * pos.err + DDV_JOINT_POS_FF(vel.ref));

                    VALVE_POS_RAW_FORCE_FF = P_GAIN_JOINT_TORQUE_FF * torq_ref * 0.001f + D_GAIN_JOINT_TORQUE_FF * (torq_ref - torq_ref_past) * 0.0001f;

                    VALVE_POS_RAW = VALVE_POS_RAW_FORCE_FB + VALVE_POS_RAW_FORCE_FF;


                    if (VALVE_POS_RAW >= 0) {
                        valve_pos.ref = VALVE_POS_RAW + VALVE_DEADZONE_PLUS;
                    } else {
                        valve_pos.ref = VALVE_POS_RAW + VALVE_DEADZONE_MINUS;
                    }

                    if(I_GAIN_JOINT_TORQUE != 0) {
                        double Ka = 2.0f / (double) I_GAIN_JOINT_TORQUE * 100.0f;
                        if(valve_pos.ref>VALVE_MAX_POS) {
                            double valve_pos_rem = valve_pos.ref - VALVE_MAX_POS;
                            valve_pos_rem = valve_pos_rem * Ka;
                            valve_pos.ref = VALVE_MAX_POS;
                            torq.err_sum = torq.err_sum - valve_pos_rem/(float) TMR_FREQ_5k;
                        } else if(valve_pos.ref < VALVE_MIN_POS) {
                            double valve_pos_rem = valve_pos.ref - VALVE_MIN_POS;
                            valve_pos_rem = valve_pos_rem * Ka;
                            valve_pos.ref = VALVE_MIN_POS;
                            torq.err_sum = torq.err_sum - valve_pos_rem/(float) TMR_FREQ_5k;
                        }
                    }
                    
                    ///////////For Test LIMC///////////////////////////////////////////////////////////////////////////////////////////////////
                    for(int i=0; i<9; i++) {
                        valve_ref_pos_buffer[i] = valve_ref_pos_buffer[i+1];
                    }
                    valve_ref_pos_buffer[9] = valve_pos.ref;
                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    
                    ///////////For Test LIMC///////////////////////////////////////////////////////////////////////////////////////////////////
                    //VALVE_POS_CONTROL(valve_pos.ref);
                    VALVE_POS_CONTROL(valve_ref_pos_buffer[0]);
                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//                    Vout.ref = (float) P_GAIN_JOINT_POSITION * 0.01f * ((float) pos.err);
                    V_out = (float) Vout.ref;

                }

                torq_ref_past = torq_ref;


                break;
            }

            case MODE_VALVE_OPEN_LOOP: {
                V_out = (float) Vout.ref;
                break;
            }

            case MODE_JOINT_ADAPTIVE_BACKSTEPPING: {


                float Va = (1256.6f + Amm * pos.sen/(float)(ENC_PULSE_PER_POSITION)) * 0.000000001f; // 4mm pipe * 100mm + (25mm Cylinder 18mm Rod) * x,      unit : m^3
                float Vb = (1256.6f + Amm  * (79.0f - pos.sen/(float)(ENC_PULSE_PER_POSITION))) * 0.000000001f; // 4mm pipe * 100mm + (25mm Cylinder 18mm Rod) * (79.0mm-x),      unit : m^3

//                float Va = (1256.6f + Amm * 39.5f) * 0.000000001f; // 4mm pipe * 100mm + (25mm Cylinder 18mm Rod) * x,      unit : m^3
//                float Vb = (1256.6f + Amm  * 39.5f) * 0.000000001f; // 4mm pipe * 100mm + (25mm Cylinder 18mm Rod) * (79.0mm-x),      unit : m^3
                V_adapt = 1.0f / (1.0f/Va + 1.0f/Vb); //initial 0.0000053f


                float f3 = -Amm*Amm*beta*0.000001f*0.000001f/V_adapt * vel.sen/(float)(ENC_PULSE_PER_POSITION)*0.001f; // unit : N/s    //xdot=10mm/s일때 -137076

                float g3_prime = 0.0f;
                if (torq.sen > Amm*(Ps-Pt)*0.000001f) {
                    g3_prime = 1.0f;
                } else if (torq.sen < -Amm*(Ps-Pt)*0.000001f) {
                    g3_prime = -1.0f;
                } else {
                    if ((value-VALVE_CENTER) > 0) {
                        g3_prime = sqrt(Ps-Pt-torq.sen/Amm*1000000.0f);
//                        g3_prime = sqrt(Ps-Pt);
                    } else {
                        g3_prime = sqrt(Ps-Pt+torq.sen/Amm*1000000.0f);
//                        g3_prime = sqrt(Ps-Pt);
                    }
                }
                float tau = 0.01f;
                float K_valve = 0.0004f;

                float x_v = 0.0f;   //x_v : -1~1
                if(value>=VALVE_CENTER) {
                    x_v = 1.0f*((double)value - (double)VALVE_CENTER)/((double)VALVE_MAX_POS - (double)VALVE_CENTER);
                } else {
                    x_v = -1.0f*((double)value - (double)VALVE_CENTER)/((double)VALVE_MIN_POS - (double)VALVE_CENTER);
                }
                float f4 = -x_v/tau;
                float g4 = K_valve/tau;

                float torq_ref_dot = torq.ref_diff * 500.0f;

                pos.err = (pos.ref - pos.sen)/(float)(ENC_PULSE_PER_POSITION); //[mm]
                vel.err = (0.0f - vel.sen)/(float)(ENC_PULSE_PER_POSITION); //[mm/s]
                pos.err_sum += pos.err/(float) TMR_FREQ_5k; //[mm]

                torq.err = torq.ref - torq.sen; //[N]
                torq.err_sum += torq.err/(float) TMR_FREQ_5k; //[N]

                float k3 = 20000.0f; //2000
                float k4 = 10.0f;
                float rho3 = 3.2f;
                float rho4 = 25000000.0f;
                float x_4_des = (-f3 + torq_ref_dot - k3*(-torq.err))/(gamma_hat*g3_prime);
                if (x_4_des > 1) x_4_des = 1;
                else if (x_4_des < -1) x_4_des = -1;

                if (x_4_des > 0) {
                    valve_pos.ref = x_4_des * (float)(VALVE_MAX_POS - VALVE_CENTER) + (float) VALVE_CENTER;
                } else {
                    valve_pos.ref = x_4_des * (float)(VALVE_CENTER - VALVE_MIN_POS) + (float) VALVE_CENTER;
                }


                float x_4_des_dot = (x_4_des - x_4_des_old)*(float) TMR_FREQ_5k;
                x_4_des_old = x_4_des;

                V_out = (-f4 + x_4_des_dot - k4*(x_v-x_4_des)- rho3/rho4*gamma_hat*g3_prime*(-torq.err))/g4;

                float rho_gamma = 50000.0f;//5000
                float gamma_hat_dot = rho3*(-torq.err)/rho_gamma*((-f3+torq_ref_dot-k3*(-torq.err))/gamma_hat + g3_prime*(x_v-x_4_des));
                gamma_hat = gamma_hat + gamma_hat_dot / (float) TMR_FREQ_5k;
                break;
            }

            case MODE_RL: {
                //t.reset();
                //t.start();

//                if(LED == 0) LED = 1;
//                else LED = 0;

                if (Update_Done_Flag == 1) {
                    //Gather Data on each loop
//                  pos.err = (pos.ref - pos.sen)/(float)(ENC_PULSE_PER_POSITION); //[mm]
//                  train_set_x[RL_timer] = pos.sen/(float)(ENC_PULSE_PER_POSITION)/35.0f - 1.0f;   //-1.0~1.0
//                  train_set_error[RL_timer] = pos.err/70.0f;      //-1.0~1.0
                    pos.err = pos.sen/(float)(ENC_PULSE_PER_POSITION)  - virt_pos; //[mm]
                    train_set_x[RL_timer] = virt_pos/70.0f;   //-1.0~1.0
                    train_set_error[RL_timer] = pos.err/70.0f;      //-1.0~1.0
                    //train_set_count[RL_timer] = (float) RL_timer / (batch_size *num_batch);  //-1.0~1.0
                    //float temp_array[3] = {train_set_x[RL_timer], train_set_error[RL_timer], train_set_count[RL_timer]};
                    float temp_array[2] = {train_set_x[RL_timer], train_set_error[RL_timer]};
                    Actor_Network(temp_array);
                    for (int i=0; i<num_hidden_unit1; i++) {
                        hx_a_sum_array[RL_timer][i] = hx_a_sum[i];
                    }
                    for (int i=0; i<num_hidden_unit2; i++) {
                        hxh_a_sum_array[RL_timer][i] = hxh_a_sum[i];
                    }
                    hxhh_a_sum_array[RL_timer][0] = hxhh_a_sum[0];
                    hxhh_a_sum_array[RL_timer][1] = hxhh_a_sum[1];
                    mean_array[RL_timer] = mean;
                    deviation_array[RL_timer] = deviation;
                    action_array[RL_timer] = rand_normal(mean_array[RL_timer], deviation_array[RL_timer]);

                    virt_pos = virt_pos + (action_array[RL_timer] - 5.0f) * 1000.0f * 0.0002f;
                    if (virt_pos > 70 ) {
                        virt_pos = 70.0f;
                    }else if(virt_pos < -70) {
                        virt_pos = -70.0f;
                    }

                    RL_timer++;


                    if (RL_timer >= batch_size) {
                        RL_timer = 0;
                        batch++;
                        for(int i=0; i<batch_size; i++) {
                            state_array[i][0] = train_set_x[i];
                            state_array[i][1] = train_set_error[i];
                            //state_array[i][2] = train_set_count[i];
                        }
                        Update_Case = 1;
                        Update_Done_Flag = 0;
                        logging1 = virt_pos;

                        if(batch >= num_batch) {
                            batch = 0;
                            RL_timer = 0;
                            Update_Case = 2;
                            Update_Done_Flag = 0;
                            virt_pos = 10.0f;
                        }
                    }
                }

                else {
                    pos.err = pos.sen/(float)(ENC_PULSE_PER_POSITION) - virt_pos; //[mm]
                    float temp_array[3] = {0.0f};
                    temp_array[0] = virt_pos/70.0f;   //-1.0~1.0
                    temp_array[1] = pos.err/70.0f;      //-1.0~1.0
                    //temp_array[2] = (float) RL_timer / (batch_size *num_batch);  //-1.0~1.0
                    Actor_Network(temp_array);
                    action = rand_normal(mean, deviation);
                    //logging1 = action;
                    //logging2 = mean;
                    //logging4 = deviation;
                    virt_pos = virt_pos + (action-5.0f) * 1000.0f * 0.0002f;
                    if (virt_pos > 70) {
                        virt_pos = 70.0f;
                    }else if(virt_pos < -70) {
                        virt_pos = -70.0f;
                    }

                    logging3 = virt_pos;
                }

                //t.stop();
                //logging1 = t.read()*1000.0f;    //msec

                break;
            }

            default:
                break;
        }


        if (((OPERATING_MODE&0b110)>>1) == 0 || ((OPERATING_MODE&0b110)>>1) == 1) { //Moog Valve or KNR Valve

            ////////////////////////////////////////////////////////////////////////////
            ////////////////////////////  CURRENT CONTROL //////////////////////////////
            ////////////////////////////////////////////////////////////////////////////
            if (CURRENT_CONTROL_MODE) {
                double alpha_update_Iref = 1.0f / (1.0f + 5000.0f / (2.0f * 3.14f * 300.0f)); // f_cutoff : 500Hz
                I_REF_fil = (1.0f - alpha_update_Iref) * I_REF_fil + alpha_update_Iref*I_REF;

                I_ERR = I_REF_fil - cur.sen;
                I_ERR_INT = I_ERR_INT + (I_ERR) * 0.0002f;


                // Moog Valve Current Control Gain
                double R_model = 500.0f; // ohm
                double L_model = 1.2f;
                double w0 = 2.0f * 3.14f * 150.0f;
                double KP_I = 0.1f * L_model*w0;
                double KI_I = 0.1f * R_model*w0;

                // KNR Valve Current Control Gain
                if (((OPERATING_MODE & 0b110)>>1) == 1) { // KNR Valve
                    R_model = 163.0f; // ohm
                    L_model = 1.0f;
                    w0 = 2.0f * 3.14f * 80.0f;
                    KP_I = 1.0f * L_model*w0;
                    KI_I = 0.08f * R_model*w0;
                }

                double FF_gain = 1.0f;

                VALVE_PWM_RAW = KP_I * 2.0f * I_ERR + KI_I * 2.0f* I_ERR_INT;
                //        VALVE_PWM_RAW = VALVE_PWM_RAW + FF_gain * (R_model*I_REF); // Unit : mV
                I_REF_fil_diff = I_REF_fil - I_REF_fil_old;
                I_REF_fil_old = I_REF_fil;
//                VALVE_PWM_RAW = VALVE_PWM_RAW + FF_gain * (R_model * I_REF_fil + L_model * I_REF_fil_diff * 5000.0f); // Unit : mV
                VALVE_PWM_RAW = VALVE_PWM_RAW + FF_gain * (R_model * I_REF_fil); // Unit : mV
                double V_MAX = 12000.0f; // Maximum Voltage : 12V = 12000mV

                double Ka = 3.0f / KP_I;
                if (VALVE_PWM_RAW > V_MAX) {
                    V_rem = VALVE_PWM_RAW - V_MAX;
                    V_rem = Ka*V_rem;
                    VALVE_PWM_RAW = V_MAX;
                    I_ERR_INT = I_ERR_INT - V_rem * 0.0002f;
                } else if (VALVE_PWM_RAW < -V_MAX) {
                    V_rem = VALVE_PWM_RAW - (-V_MAX);
                    V_rem = Ka*V_rem;
                    VALVE_PWM_RAW = -V_MAX;
                    I_ERR_INT = I_ERR_INT - V_rem * 0.0002f;
                }
                Cur_Valve_Open_pulse = cur.sen / mA_PER_pulse;
            } else {
                VALVE_PWM_RAW = I_REF * mV_PER_mA;
                Cur_Valve_Open_pulse = I_REF / mA_PER_pulse;
            }

            ////////////////////////////////////////////////////////////////////////////
            /////////////////  Dead Zone Cancellation & Linearization //////////////////
            ////////////////////////////////////////////////////////////////////////////
            // Dead Zone Cancellation (Mechanical Valve dead-zone)
            if (FLAG_VALVE_DEADZONE) {
                if (VALVE_PWM_RAW > 0) VALVE_PWM_RAW = VALVE_PWM_RAW + VALVE_DEADZONE_PLUS * mV_PER_pulse; // unit: mV
                else if (VALVE_PWM_RAW < 0) VALVE_PWM_RAW = VALVE_PWM_RAW + VALVE_DEADZONE_MINUS * mV_PER_pulse; // unit: mV

                VALVE_PWM_VALVE_DZ = VALVE_PWM_RAW + (double)VALVE_CENTER * mV_PER_pulse; // unit: mV

            } else {
                VALVE_PWM_VALVE_DZ = VALVE_PWM_RAW;
            }

            // Output Voltage Linearization
            double CUR_PWM_nonlin = VALVE_PWM_VALVE_DZ; // Unit : mV
            double CUR_PWM_lin = PWM_duty_byLT(CUR_PWM_nonlin);  // -8000~8000

            // Dead Zone Cancellation (Electrical dead-zone)
            if (CUR_PWM_lin > 0) V_out = (float) (CUR_PWM_lin + 169.0f);
            else if (CUR_PWM_lin < 0) V_out = (float) (CUR_PWM_lin - 174.0f);
            else V_out = (float) (CUR_PWM_lin);
        } else {            //////////////////////////sw valve
            // Output Voltage Linearization
//            double CUR_PWM_nonlin = V_out; // Unit : mV
//            double CUR_PWM_lin = PWM_duty_byLT(CUR_PWM_nonlin);  // -8000~8000

            // Dead Zone Cancellation (Electrical dead-zone)
//            if (CUR_PWM_lin > 0) V_out = (float) (CUR_PWM_lin + 169.0f);
//            else if (CUR_PWM_lin < 0) V_out = (float) (CUR_PWM_lin - 174.0f);
//            else V_out = (float) (CUR_PWM_lin);

            if (V_out > 0 ) V_out = (V_out + 180.0f)/0.8588f;
            else if (V_out < 0) V_out = (V_out - 200.0f)/0.8651f;
            else V_out = 0.0f;
        }

//        if(V_out > 0.0f) V_out = (float) (V_out + 169.0f);
//        else if(V_out < 0.0f) V_out = (float) (V_out - 174.0f);
//        else V_out = V_out;

        /*******************************************************
        ***     PWM
        ********************************************************/
        if(DIR_VALVE<0) {
            V_out = -V_out;
        }

        if (V_out >= VALVE_VOLTAGE_LIMIT*1000.0f) {
            V_out = VALVE_VOLTAGE_LIMIT*1000.0f;
        } else if(V_out<=-VALVE_VOLTAGE_LIMIT*1000.0f) {
            V_out = -VALVE_VOLTAGE_LIMIT*1000.0f;
        }
        PWM_out= V_out/(SUPPLY_VOLTAGE*1000.0f); // Full duty : 12000.0mV

        // Saturation of output voltage to 12.0V
        if(PWM_out > 1.0f) PWM_out=1.0f;
        else if (PWM_out < -1.0f) PWM_out=-1.0f;

        if (PWM_out>0.0f) {
            dtc_v=0.0f;
            dtc_w=PWM_out;
        } else {
            dtc_v=-PWM_out;
            dtc_w=0.0f;
        }

        //pwm
        TIM4->CCR2 = (PWM_ARR)*(1.0f-dtc_v);
        TIM4->CCR1 = (PWM_ARR)*(1.0f-dtc_w);


        if (TMR2_COUNT_CAN_TX % (int) ((int) TMR_FREQ_5k/CAN_FREQ) == 0) {

            // Position, Velocity, and Torque (ID:1200)
            if (flag_data_request[0] == HIGH) {
                if ((OPERATING_MODE & 0b01) == 0) { // Rotary Actuator
                    if (SENSING_MODE == 0) {
                        CAN_TX_POSITION_FT((int16_t) (pos.sen), (int16_t) (vel.sen/10.0f), (int16_t) (torq.sen*10.0f));
                    } else if (SENSING_MODE == 1) {
                        CAN_TX_POSITION_PRESSURE((int16_t) (pos.sen), (int16_t) (vel.sen/10.0f), (int16_t) ((pres_A.sen)*5.0f), (int16_t) ((pres_B.sen)*5.0f));
                    }
                } else if ((OPERATING_MODE & 0b01) == 1) { // Linear Actuator
                    if (SENSING_MODE == 0) {
                        CAN_TX_POSITION_FT((int16_t) (pos.sen/10.0f), (int16_t) (vel.sen/256.0f), (int16_t) (torq.sen * 10.0f * (float)(TORQUE_SENSOR_PULSE_PER_TORQUE)));
                    } else if (SENSING_MODE == 1) {
                        CAN_TX_POSITION_PRESSURE((int16_t) (pos.sen/10.0f), (int16_t) (vel.sen/256.0f), (int16_t) ((pres_A.sen)*5.0f), (int16_t) ((pres_B.sen)*5.0f));
                    }
                }
            }
            if (flag_data_request[1] == HIGH) {
                CAN_TX_TORQUE((int16_t) (return_G[0]*100.0f)); //1300
            }


            if (flag_data_request[2] == HIGH) {
                double t_value = 0.0f;
                if(value>=(float) VALVE_CENTER) {
                    t_value = 10000.0f*((double)value - (double)VALVE_CENTER)/((double)VALVE_MAX_POS - (double)VALVE_CENTER);
                } else {
                    t_value = -10000.0f*((double)value - (double)VALVE_CENTER)/((double)VALVE_MIN_POS - (double)VALVE_CENTER);
                }
                double t_value_ref = 0.0f;
                if(valve_pos.ref>=(float) VALVE_CENTER) {
                    t_value_ref = 10000.0f*((double)valve_pos.ref - (double)VALVE_CENTER)/((double)VALVE_MAX_POS - (double)VALVE_CENTER);
                } else {
                    t_value_ref = -10000.0f*((double)valve_pos.ref - (double)VALVE_CENTER)/((double)VALVE_MIN_POS - (double)VALVE_CENTER);
                }
                CAN_TX_PRES((int16_t) (t_value), (int16_t) (t_value_ref)); // 1400
            }

            //If it doesn't rest, below can can not work.
            for (can_rest = 0; can_rest < 10000; can_rest++) {
                ;
            }

            if (flag_data_request[3] == HIGH) {
                //PWM
                //CAN_TX_PWM((int16_t) (V[0]*100.0f)); //1500
                CAN_TX_PWM((int16_t) (f_future[1])); //1500
            }

            if (flag_data_request[4] == HIGH) {
                //valve position
                CAN_TX_VALVE_POSITION((int16_t) pos.sen/(float)(ENC_PULSE_PER_POSITION), (int16_t) virt_pos, (int16_t) (logging2*1000.0f), (int16_t) (logging4*1000.0f)); //1600
                //CAN_TX_VALVE_POSITION((int16_t) action_array[20], (int16_t) virt_pos, (int16_t) Update_Case*1000, (int16_t) (logging4*1000.0f)); //1600
            }

            // Others : Reference position, Reference FT, PWM, Current  (ID:1300)
//        if (flag_data_request[1] == HIGH) {
//            CAN_TX_SOMETHING((int) (FORCE_VREF), (int16_t) (1), (int16_t) (2), (int16_t) (3));
//        }
            //if (flag_delay_test == 1){
            //CAN_TX_PRES((int16_t) (0),(int16_t) torq_ref);
            //}

            TMR2_COUNT_CAN_TX = 0;
        }
        TMR2_COUNT_CAN_TX++;

    }
    TIM3->SR = 0x0;  // reset the status register

}