#include <adc_tools.h>
#include <alg_simple_scalar.h>
#include <alg_uf_const.h>
#include <break_regul.h>
#include <calc_rms_vals.h>
#include <control_station_project.h>    //22.06
#include <detect_errors_adc.h>
#include <detect_overload.h>
#include <edrk_main.h>
#include <f281xpwm.h>
//#include <log_to_mem.h>
#include <master_slave.h>
#include <math.h>
#include <message_modbus.h>             //22.06
#include <optical_bus.h>
#include <params.h>
#include <params_norma.h>
#include <params_pwm24.h>
#include <project.h>
#include <PWMTMSHandle.h>
#include <PWMTools.h>
#include <sync_tools.h>
#include <v_pwm24_v2.h>
#include <v_pwm24_v2.h>
#include <v_rotor.h>
#include <vector.h>
#include "f281xpwm.h"

//#include "SpaceVectorPWM.h"
#include "CAN_Setup.h"
#include "global_time.h"
#include "IQmathLib.h"
#include "mathlib.h"
#include "oscil_can.h"
#include "rmp_cntl_v1.h"
#include "uf_alg_ing.h"
#include "vhzprof.h"
#include "vector_control.h"
#include "MemoryFunctions.h"
#include "RS_Functions.h"
#include "TuneUpPlane.h"
#include "xp_write_xpwm_time.h"
#include "pwm_test_lines.h"
#include "detect_errors.h"
#include "modbus_table_v2.h"
#include "params_alg.h"
#include "v_rotor_22220.h"
#include "log_to_memory.h"
#include "log_params.h"
#include "limit_power.h"
#include "pwm_logs.h"
#include "optical_bus_tools.h"
#include "ramp_zadanie_tools.h"
#include "pll_tools.h"


/////////////////////////////////////
#if (_SIMULATE_AC==1)
#include "sim_model.h"
#endif

//#pragma DATA_SECTION(freq1,".fast_vars1");
//_iq freq1;

//#pragma DATA_SECTION(k1,".fast_vars1");
//_iq k1 = 0;

#define ENABLE_LOG_INTERRUPTS   0 //1


#if (ENABLE_LOG_INTERRUPTS)

#pragma DATA_SECTION(log_interrupts,".slow_vars");
#define MAX_COUNT_LOG_INTERRUPTS  100
unsigned int log_interrupts[MAX_COUNT_LOG_INTERRUPTS+2] = {0};




/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////


void add_log_interrupts(int cmd)
{
    static int count_log_interrupst = 0;

    if (count_log_interrupst>=MAX_COUNT_LOG_INTERRUPTS)
        count_log_interrupst = 0;


    log_interrupts[count_log_interrupst++] = cmd;
    log_interrupts[count_log_interrupst++] = EvbRegs.T3CNT;


//#if (ENABLE_LOG_INTERRUPTS)
//    add_log_interrupts(0);
//#endif

}

#endif //if (ENABLE_LOG_INTERRUPTS)



#pragma DATA_SECTION(iq_U_1_save,".fast_vars1");
_iq iq_U_1_save = 0;
#pragma DATA_SECTION(iq_U_2_save,".fast_vars1");
_iq iq_U_2_save = 0;


unsigned int enable_calc_vector = 0;



//WINDING winding1 = WINDING_DEFAULT;

//#define COUNT_SAVE_LOG_OFF 50 //Сколько тактов ШИМ сохранЯетсЯ после остановки
#define COUNT_START_IMP  5 //10

#define CONST_005   838860
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////


#pragma CODE_SECTION(global_time_interrupt,".fast_run2");
void global_time_interrupt(void)
{

//    inc_RS_timeout_cicle();
//    inc_CAN_timeout_cicle();

#if(_ENABLE_PWM_LINES_FOR_TESTS)
//    PWM_LINES_TK_18_ON;
#endif

    if (edrk.disable_interrupt_timer3)
        return;

//i_led1_on_off(1);


    if (sync_data.latch_interrupt && sync_data.enabled_interrupt)
    {
        // перезапуск прерывания тут!
        // для исключения дребезга
        start_sync_interrupt();
    }

#if (ENABLE_LOG_INTERRUPTS)
    add_log_interrupts(1);
#endif

   global_time.calc(&global_time);

#if (ENABLE_LOG_INTERRUPTS)
    add_log_interrupts(101);
#endif

/*
static unsigned int oldest_time = 0, time_pause = TIME_PAUSE_MODBUS_REMOUTE;
control_station_test_alive_all_control();
       if (detect_pause_milisec(time_pause,&oldest_time))
               modbusNetworkSharing(0);

       RS232_WorkingWith(0,1);
*/


//i_led1_on_off(0);
#if(_ENABLE_PWM_LINES_FOR_TESTS)
 //   PWM_LINES_TK_18_OFF;
#endif
}

///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//#define get_tics_timer_pwm2(k) {time_buf2[k] = (EvbRegs.T3CNT-start_tics_4timer);k++;}
//unsigned int time_buf2[10] = {0};


///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
#define PAUSE_INC_TIMEOUT_CICLE     10 // FREQPWM/10
void pwm_inc_interrupt(void)
{
    static unsigned int t_inc = 0;

    if (t_inc>=PAUSE_INC_TIMEOUT_CICLE)
    {
        inc_RS_timeout_cicle();
        inc_CAN_timeout_cicle();
        t_inc = 0;
    }
    else
        t_inc++;
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////

#pragma CODE_SECTION(pwm_analog_ext_interrupt,".fast_run2");
void pwm_analog_ext_interrupt(void)
{
//    static int count_timer_buf2=0, start_tics_4timer = 0, c_rms = 0;
//    static _iq prev_Iu=0, prev_Ua=0;
    //static _iq iq_50hz_norma = _IQ(50.0/NORMA_FROTOR);

//    i_led2_on();

    // подготовка подсчета времени работы в прерывании
//    start_tics_4timer = EvaRegs.T1CNT;

//    count_timer_buf2 = 0;
//    get_tics_timer_pwm2(count_timer_buf2);

    if (edrk.SumSbor == 1) {
//        detect_protect_adc(uf_alg.tetta_bs, uf_alg.tetta_bs);
    }



    calc_pll_50hz();

//
//    if (c_rms>=9)
//    {
//     edrk.test_rms_Iu = calc_rms(analog.iqIu,prev_Iu,edrk. f_stator);
//     edrk.test_rms_Ua = calc_rms(analog.iqUin_A1B1,prev_Ua, iq_50hz_norma);
//
//     prev_Iu = analog.iqIu;
//     prev_Ua = analog.iqUin_A1B1;
//     c_rms = 0;
//    }
//    else
//        c_rms++;

//    fill_RMS_buff_interrupt(uf_alg.tetta_bs, uf_alg.tetta_bs);

 //   get_tics_timer_pwm2(count_timer_buf2);
//    i_led2_off();


//    global_time.calc(&global_time);

}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////

inline void init_regulators()
{
//	if(f.Mode != 0)
//	{
////		pwm_vector_model_titov(0, 0, /*rotor.iqW*/0, 0);
//	}
}

#define select_working_channels(go_a, go_b)		{go_a = !f.Obmotka1; \
												go_b = !f.Obmotka2;}

#define MAX_COUNT_WAIT_GO_0     FREQ_PWM // 1 сек.


#define PAUSE_ERROR_DETECT_UPDATE_OPTBUS_DATA   900//  ((unsigned int)(1*FREQ_PWM*2)) // ~1sec //50
#define MAX_TIMER_WAIT_SET_TO_ZERO_ZADANIE      27000 //((unsigned int)(30*FREQ_PWM*2)) // 60 sec
//#define MAX_TIMER_WAIT_BOTH_READY2              108000 //(120*FREQ_PWM*2) // 120 sec
#define MAX_TIMER_WAIT_BOTH_READY2              216000 //(120*FREQ_PWM*2) // 240 sec
#define MAX_TIMER_WAIT_MASTER_SLAVE             4500 // 5 sec

///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//#define _ENABLE_PWM_LED2_PROFILE    1


#if (_ENABLE_PWM_LED2_PROFILE)
unsigned int profile_pwm[30]={0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0};
unsigned int pos_profile_pwm = 0;
#endif

///////////////////////////////////////////////////////////////////
#define _ENABLE_LOG_TICS_PWM            0//1
#define _ENABLE_SLOW_PWM                0//1
#define _ENABLE_INTERRUPT_PWM_LED2      0//1

#if (_ENABLE_LOG_TICS_PWM==1)

static int c_run=0;
static int c_run_start=0;
static int i_log;


#pragma DATA_SECTION(time_buf,".slow_vars");
#define MAX_COUNT_TIME_BUF  50
int time_buf[MAX_COUNT_TIME_BUF] = {0};

//#define get_tics_timer_pwm(flag,k) {if (flag)  {time_buf[k] = (unsigned int)(EvbRegs.T3CNT-start_tics_4timer);k++;}else{time_buf[k] = -1; k++;}}

#define set_tics_timer_pwm(flag,k)   { time_buf[k] = flag;k++; }

//#define get_tics_timer_pwm(flag,k) if (flag) ?  {time_buf[k] = (EvbRegs.T3CNT-start_tics_4timer);k++;} : {time_buf[k] = -1; k++;};
static int count_timer_buf=0;

#else

#define get_tics_timer_pwm(flag)   asm(" NOP;")
#define set_tics_timer_pwm(flag,k)   asm(" NOP;")
//static int count_timer_buf=0;

#endif


#if(_ENABLE_SLOW_PWM)
static int slow_pwm_pause = 0;
#endif

unsigned int count_time_buf = 0;
int stop_count_time_buf=0;
unsigned int log_wait;

unsigned int end_tics_4timer, start_tics_4timer;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////
#if (_ENABLE_LOG_TICS_PWM==1)
//#pragma CODE_SECTION(get_tics_timer_pwm,".fast_run");
void get_tics_timer_pwm(unsigned int flag)
{
    unsigned int delta;

    if (flag)
    {
        delta = (unsigned int)(EvbRegs.T3CNT-start_tics_4timer);
        if (count_timer_buf>=3)
            time_buf[count_timer_buf] =  delta - time_buf[count_timer_buf-2];
        else
            time_buf[count_timer_buf] =  delta;
        time_buf[count_timer_buf] = time_buf[count_timer_buf]*33/1000;
        count_timer_buf++;
    }
    else
    {
        time_buf[count_timer_buf] = -1;
        count_timer_buf++;
    }
}
#else

#endif

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////
// получаем данные с датчика оборотов
///////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#pragma CODE_SECTION(calc_rotors,".fast_run");
void calc_rotors(int flag)
{

#if(_ENABLE_PWM_LINES_FOR_TESTS_ROTOR)
    PWM_LINES_TK_17_ON;
#endif

        update_rot_sensors();



        set_tics_timer_pwm(6,count_timer_buf);
        get_tics_timer_pwm(flag);


#if(C_cds_in_number>=1)
           project.cds_in[0].read_pbus(&project.cds_in[0]);

#if(_ENABLE_PWM_LINES_FOR_TESTS_ROTOR)
    PWM_LINES_TK_17_OFF;
#endif

#if (_ENABLE_PWM_LED2_PROFILE)
        if (profile_pwm[pos_profile_pwm++])
            i_led2_on_off(1);
        else
            i_led2_on_off(0);
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_ROTOR)
    PWM_LINES_TK_19_ON;
#endif

#if(SENSOR_ALG==SENSOR_ALG_23550)
// 23550
           RotorMeasureDetectDirection();
           RotorMeasure();// измеритель
#endif

#if(SENSOR_ALG==SENSOR_ALG_22220)
// 22220
     Rotor_measure_22220();

#if (_ENABLE_PWM_LED2_PROFILE)
        if (profile_pwm[pos_profile_pwm++])
            i_led2_on_off(1);
        else
            i_led2_on_off(0);
#endif

#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_ROTOR)
    PWM_LINES_TK_19_OFF;
#endif

           set_tics_timer_pwm(7,count_timer_buf);
           get_tics_timer_pwm(flag);

#if(_ENABLE_PWM_LINES_FOR_TESTS_ROTOR)
    PWM_LINES_TK_20_ON;
#endif

//           RotorMeasurePBus();
#if(SENSOR_ALG==SENSOR_ALG_23550)
// 23550
        RotorDirectionFilter(WRotorPBus.RotorDirectionInstant, &WRotorPBus.RotorDirectionSlow, &WRotorPBus.RotorDirectionSlow2, &WRotorPBus.RotorDirectionCount);
#endif

#if(SENSOR_ALG==SENSOR_ALG_22220)
 // 22220 
 // nothing
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_ROTOR)
    PWM_LINES_TK_20_OFF;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_ROTOR)
    PWM_LINES_TK_20_ON;
#endif

#if(SENSOR_ALG==SENSOR_ALG_23550)
// 23550
           select_values_wrotor();
#endif
#if(SENSOR_ALG==SENSOR_ALG_22220)
// 22220 
           select_values_wrotor_22220();

#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_ROTOR)
    PWM_LINES_TK_20_OFF;
#endif

           set_tics_timer_pwm(8,count_timer_buf);
           get_tics_timer_pwm(flag);

#endif //(C_cds_in_number>=1)


           edrk.rotor_direction = WRotor.RotorDirectionSlow;

#if(SENSOR_ALG==SENSOR_ALG_23550)
// 23550
           edrk.iq_f_rotor_hz = WRotor.iqWRotorSumFilter;
#endif

#if(SENSOR_ALG==SENSOR_ALG_22220)
// 22220
           edrk.iq_f_rotor_hz = WRotor.iqWRotorSum;
#endif

}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#pragma CODE_SECTION(calc_zadanie_rampa,".fast_run");
void calc_zadanie_rampa(void)
{
#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_19_ON;
#endif


    // подхват при смене режима
    load_current_ramp_oborots_power();

        if (edrk.StartGEDfromControl==0)
          ramp_all_zadanie(2); //  форсируем в ноль
        else
            if (edrk.flag_wait_set_to_zero_zadanie || edrk.flag_block_zadanie || edrk.Status_Ready.bits.ready_final==0 || /*edrk.StartGEDfromControl==0 ||*/ edrk.run_razbor_shema == 1)
                ramp_all_zadanie(1);  // стремим рампы в ноль, ка ктолько они доедут в ноль, то снимается edrk.StartGEDfromZadanie
            else
                ramp_all_zadanie(0);  // тут все по штатному

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_19_OFF;
#endif

}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
#pragma CODE_SECTION(async_pwm_ext_interrupt,".fast_run2");
void async_pwm_ext_interrupt(void)
{

#if(_ENABLE_PWM_LINES_FOR_TESTS_SYNC)
    PWM_LINES_TK_19_ON;
#endif
    if (edrk.run_to_pwm_async)
    {
        PWM_interrupt();
        edrk.run_to_pwm_async = 0;
    }


#if(_ENABLE_PWM_LINES_FOR_TESTS_SYNC)
    PWM_LINES_TK_19_OFF;
#endif

}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
void run_detect_fast_error(void)
{

    detect_error_u_zpt_fast();
    detect_error_u_in();

}
////////////////////////////////////////////////////////////////////////////////

#pragma CODE_SECTION(PWM_interrupt_main,".fast_run");
void PWM_interrupt_main(void)
{

#if(_ENABLE_PWM_LINES_FOR_TESTS_SYNC)
    PWM_LINES_TK_16_ON;
#endif

    norma_adc_nc(0);

    edrk.run_to_pwm_async = 1;

#if(_ENABLE_PWM_LINES_FOR_TESTS_SYNC)
    PWM_LINES_TK_16_OFF;
#endif

}
////////////////////////////////////////////////////////////////////////////////


#define MAX_COUNT_COUNTSTARTGEDFROMZADANIE  FREQ_PWM //3000        // задержка в тактах появления единицы в edrk.StartGEDfromZadanie



#pragma CODE_SECTION(PWM_interrupt,".fast_run");
void PWM_interrupt(void)
{

	static unsigned int pwm_run = 0;
	static _iq Uzad1=0, Fzad=0, Uzad2=0, Izad_out = 0, Uzad_from_master = 0;

//	static int count_step_ram_off = 0;
//	static int count_start_impuls = 0;

	static int prevGo = -1;
	static volatile unsigned int go_a = 0;
	static volatile unsigned int go_b = 0;
	
	static int prev_go_a = 0;
	static int prev_go_b = 0;

    static _iq iq_U_1_prev = 0;
    static _iq iq_U_2_prev = 0;
	static unsigned int prev_timer = 0;
	unsigned int cur_timer;
	static unsigned int count_lost_interrupt=0;
	static int en_rotor = 1;//1;

	static unsigned long timer_wait_set_to_zero_zadanie = 0;
    static unsigned long timer_wait_both_ready2 = 0;

	static unsigned int prev_error_controller = 0,error_controller=0;

	static unsigned long time_delta = 0;

	static unsigned int run_calc_uf = 0, prev_run_calc_uf = 0, count_wait_go_0 = 0;

	int pwm_enable_calc_main = 0, pwm_up_down = 0, err_interr = 0, slow_error = 0;

	static unsigned int count_err_read_opt_bus = 0, prev_edrk_Kvitir = 0;

	static unsigned int count_wait_read_opt_bus = 0, old_count_ok = 0, data_ready_optbus = 0, count_ok_read_opt_bus = 0;

//	static T_cds_optical_bus_data_in buff[25]={0};
	static unsigned int flag_last_error_read_opt_bus = 0, sum_count_err_read_opt_bus1=0;

	static unsigned int count_read_slave = 0, flag1_change_moment_read_optbus = 0, flag2_change_moment_read_optbus = 0;

	static unsigned int count_updated_sbus = 0, prev_ManualDischarge = 0;

	static unsigned int prev_flag_detect_update_optbus_data=0, flag_detect_update_optbus_data = 0, pause_error_detect_update_optbus_data = 0;
	static unsigned int timer_wait_to_master_slave = 0;
	static unsigned int prev_master = 0;

	static int pwm_enable_calc_main_log  = 1;

	static int what_pwm = 0;

    int localStartGEDfromZadanie;
    static unsigned int countStartGEDfromZadanie = 0;


//	OPTICAL_BUS_CODE_STATUS optbus_status = {0};
	static STATUS_DATA_READ_OPT_BUS optbus_status;
	_iq wd;

//   if (edrk.disable_interrupt_sync==0)
//       start_sync_interrupt();


#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_16_ON;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_ROTOR)
    PWM_LINES_TK_16_ON;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS)
//    PWM_LINES_TK_16_ON;
#endif



#if (_ENABLE_INTERRUPT_PWM_LED2)
i_led2_on_off(1);
#endif

   if (edrk.disable_interrupt_pwm)
   {
       pwm_inc_interrupt();
       return;
   }

   if (flag_special_mode_rs==1)
   {
     calc_norm_ADC_0(1);
     calc_norm_ADC_1(1);
     pwm_inc_interrupt();

     return;
   }

#if (_ENABLE_PWM_LED2_PROFILE)
   pos_profile_pwm = 0;
#endif



#if (_ENABLE_PWM_LED2_PROFILE)
        if (profile_pwm[pos_profile_pwm++])
            i_led2_on_off(1);
        else
            i_led2_on_off(0);
#endif


//   if (xpwm_time.what_next_interrupt==PWM_LOW_LEVEL_INTERRUPT)
//   {
//#if(_ENABLE_PWM_LINES_FOR_TESTS_SYNC)
//    PWM_LINES_TK_17_ON;
//#endif
//
//       i_sync_pin_on();
//
//   }
//   else
//   {
//#if(_ENABLE_PWM_LINES_FOR_TESTS_SYNC)
//    PWM_LINES_TK_17_OFF;
//#endif
//
//       i_sync_pin_off();
//   }



////////////////
//PWN_COUNT_RUN_PER_INTERRUPT   PWM_TWICE_INTERRUPT_RUN
   err_interr = detect_level_interrupt(edrk.flag_second_PCH);

   if (err_interr)
       edrk.errors.e3.bits.ERR_INT_PWM_LONG |=1;

   if (xpwm_time.one_or_two_interrupts_run == PWM_ONE_INTERRUPT_RUN)
       pwm_up_down = 2;
   else
   if (xpwm_time.where_interrupt == PWM_LOW_LEVEL_INTERRUPT)
   {
       pwm_up_down = 0;
   }
   else
       pwm_up_down = 1;

   // sync line
   if (pwm_up_down==2 || pwm_up_down==0)
   {
//       what_pwm = 0;
 //     i_sync_pin_on();
       calculate_sync_detected();
   }

/////////////////
#if (ENABLE_LOG_INTERRUPTS)
    add_log_interrupts(3);
#endif


#if (_ENABLE_LOG_TICS_PWM==1)

   count_timer_buf = 0;
 //  optical_read_data.timer=0;
#endif


#if (_FLOOR6==0)
//   if (edrk.Stop==0)
//     i_led1_on_off(1);
#else
 //    i_led1_on_off(1);
#endif


   edrk.into_pwm_interrupt = 1;

   // подготовка подсчета времени работы в прерывании
   start_tics_4timer = EvbRegs.T3CNT;
   cur_timer = global_time.pwm_tics;
   if (prev_timer>cur_timer)
   {
		if ((prev_timer-cur_timer)<2)
		{
//		  stop_pwm();
		  edrk.count_lost_interrupt++;
		}
   }
   else
   {
	   if ((cur_timer==prev_timer) || (cur_timer-prev_timer)>2)
	   {
//			stop_pwm();
			edrk.count_lost_interrupt++;
	   }
   }
   prev_timer = cur_timer;	
   // закончили подготовку подсчета времени работы в прерывании

   set_tics_timer_pwm(1,count_timer_buf);
   get_tics_timer_pwm(1);

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_17_ON;
#endif

#if (_SIMULATE_AC==1)
    calc_norm_ADC_0_sim(0);
#else
    calc_norm_ADC_0(0); // читаем АЦП а norma была запущена в Pwm_main()
#endif
    run_detect_fast_error(); //быстрые защиты



   /////////////////////////////////////////////////////////////
   /////////////////////////////////////////////////////////////
   /////////////////////////////////////////////////////////////
   /////////////////////////////////////////////////////////////
   if (edrk.Kvitir==0 && prev_edrk_Kvitir==1)
   {
       count_err_read_opt_bus = 0;
       edrk.sum_count_err_read_opt_bus = 0;
   }

   set_tics_timer_pwm(2,count_timer_buf);
   get_tics_timer_pwm(1);

   //////////////////////////////
//   inc_RS_timeout_cicle();
   ////////////////////////////////
   ////////////////////////////////////////////
   ////////////////////////////////////////////
//   inc_CAN_timeout_cicle();
   ////////////////////////////////////////////

   if (edrk.ms.another_bs_maybe_on==1 &&
       (edrk.auto_master_slave.local.bits.master || edrk.auto_master_slave.local.bits.slave) )
   {

     flag_detect_update_optbus_data = 1;

     if (prev_flag_detect_update_optbus_data == 0)
         pause_error_detect_update_optbus_data = 0;


     count_updated_sbus = optical_read_data.data_was_update_between_pwm_int;

     // даем задержку PAUSE_ERROR_DETECT_UPDATE_OPTBUS_DATA после входа в обмен по OPT_BUS
     // после которой начинаем ловить ошибки по своевременному обновлению данных по OPT_BUS
     if (pause_error_detect_update_optbus_data<PAUSE_ERROR_DETECT_UPDATE_OPTBUS_DATA)
         pause_error_detect_update_optbus_data++;
     else
     {
         if (optical_read_data.error_wdog || (optical_read_data.data_was_update_between_pwm_int==0))
         {
             if (optical_read_data.error_wdog)
                 edrk.errors.e8.bits.WDOG_OPTICAL_BUS |= 1;

             if (optical_read_data.data_was_update_between_pwm_int==0)
                 edrk.errors.e7.bits.ANOTHER_PCH_NOT_ANSWER |= 1;
         }
         else
         {
             edrk.ms.ready3 = 1;
             optical_read_data.data_was_update_between_pwm_int = 0;
         }

     }
//               sum_count_err_read_opt_bus++;
   }
   else
   {
       pause_error_detect_update_optbus_data = 0;
       flag_detect_update_optbus_data = 0;
       edrk.ms.ready3 = 0;
   }
   prev_flag_detect_update_optbus_data = flag_detect_update_optbus_data;

   optical_read_data.flag_clear = 1;


    if (xpwm_time.where_interrupt == PWM_LOW_LEVEL_INTERRUPT ||
            xpwm_time.one_or_two_interrupts_run == PWM_ONE_INTERRUPT_RUN)
    {
        pwm_enable_calc_main = 1;

        if (sync_data.what_main_pch)
        {
            if (sync_data.what_main_pch==2)
            {
                if (edrk.flag_second_PCH==1) // только на втором БС
                {
                    fix_pwm_freq_synchro_ain();
                }
            }

            if (sync_data.what_main_pch==1)
            {
                if (edrk.flag_second_PCH==0) // только на втором БС
                {
                    fix_pwm_freq_synchro_ain();
                }
            }
        }
        else
            fix_pwm_freq_synchro_ain();

    }
    else
    {
        pwm_enable_calc_main = 0;
    }

    /////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////

//#if(C_cds_in_number>=1)
//    project.cds_in[0].read_pbus(&project.cds_in[0]);
//#endif

#if(C_cds_in_number>=2)
    project.cds_in[1].read_pbus(&project.cds_in[1]);
#endif


#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_17_OFF;
#endif



    set_tics_timer_pwm(10,count_timer_buf);
    get_tics_timer_pwm(pwm_enable_calc_main_log);

	if (pwm_run == 1)
	{
	    // зашли в прерывание но почему-то мы уже были тут, повторный заход?
		soft_stop_x24_pwm_all();
		edrk.errors.e9.bits.ERR_INT_PWM_VERY_LONG |=1;
	}
	else
	{
		pwm_run = 1;

//		detect_I_M_overload();
//	if (edrk.from_rs.bits.ACTIVE)
//	  edrk.Go = edrk.StartGEDRS;

//	project_read_errors_controller(); // чтение ADR_ERRORS_TOTAL_INFO

		if (  (edrk.errors.e0.all)
		       || (edrk.errors.e1.all)
		       || (edrk.errors.e2.all)
		       || (edrk.errors.e3.all)
		       || (edrk.errors.e4.all)
		       || (edrk.errors.e5.all)
		       || (edrk.errors.e6.all)
		       || (edrk.errors.e7.all)
		       || (edrk.errors.e8.all)
		       || (edrk.errors.e9.all)
		       || (edrk.errors.e10.all)
		       || (edrk.errors.e11.all)
		       || (edrk.errors.e12.all)
		)
		    edrk.Stop |= 1;
		else
		    edrk.Stop = 0;



		project.read_errors_controller();
		error_controller = (project.controller.read.errors.all | project.controller.read.errors_buses.bit.slave_addr_error | project.controller.read.errors_buses.bit.count_error_pbus);
//		project.controller.read.errors.all = error_controller;



		if(error_controller && prev_error_controller==0)
		{
		    edrk.errors.e11.bits.ERROR_CONTROLLER_BUS |= 1;
			svgen_set_time_keys_closed(&svgen_pwm24_1);
			svgen_set_time_keys_closed(&svgen_pwm24_2);

			write_swgen_pwm_times(PWM_MODE_RELOAD_FORCE);

//			xerror(main_er_ID(1),(void *)0);
		}
		prev_error_controller = error_controller;//project.controller.read.errors.all;


	  if (pwm_enable_calc_main==0)// заходим в расчет только раз за период шима - вторая часть
	  {

	        if (en_rotor)
	        {
#if (_SIMULATE_AC==1)
//	            calc_rotors_sim();
#else
    calc_rotors(pwm_enable_calc_main_log);      // получаем данные с датчика оборотов
#endif



	        }

#if (_ENABLE_PWM_LED2_PROFILE)
        if (profile_pwm[pos_profile_pwm++])
            i_led2_on_off(1);
        else
            i_led2_on_off(0);
#endif
	        calc_zadanie_rampa();

#if (_ENABLE_PWM_LED2_PROFILE)
        if (profile_pwm[pos_profile_pwm++])
            i_led2_on_off(1);
        else
            i_led2_on_off(0);
#endif
	        calc_norm_ADC_1(1);      // замер температур

	        calc_power_full();

	        calc_all_limit_koeffs();

	  }

	  /////////////////////////////////////////////////////////////
	  /////////////////////////////////////////////////////////////


	  if (pwm_enable_calc_main)// заходим в расчет только раз за период шима
	  {

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_18_ON;
#endif

        if (edrk.Obmotka1 == 0)
            go_a = 1;
        else
            go_a = 0;

        if (edrk.Obmotka2 == 0)
            go_b = 1;
        else
            go_b = 0;

        //////////////////////////

        if (optical_read_data.data.cmd.bit.start_pwm && edrk.auto_master_slave.local.bits.slave )
          edrk.StartGEDfromSyncBus = 1;
        else
            edrk.StartGEDfromSyncBus = 0;

        edrk.master_Uzad  = _IQ15toIQ(  optical_read_data.data.pzad_or_wzad);
        edrk.master_theta = _IQ12toIQ(  optical_read_data.data.angle_pwm);
        edrk.master_Izad  = _IQ15toIQ(  optical_read_data.data.iq_zad_i_zad);
        edrk.master_Iq    = _IQ15toIQ(  optical_read_data.data.iq_zad_i_zad);

        set_tics_timer_pwm(11,count_timer_buf);
        get_tics_timer_pwm(pwm_enable_calc_main_log);

        /////////////////////////

        if ((edrk.auto_master_slave.local.bits.slave==1 && edrk.auto_master_slave.local.bits.master==0)
            || (edrk.auto_master_slave.local.bits.slave==0 && edrk.auto_master_slave.local.bits.master==1) )
        {

            if (edrk.auto_master_slave.local.bits.master != prev_master)
                timer_wait_to_master_slave = 0;

            // после выбора ждем еще некоторое время.
            if (timer_wait_to_master_slave>MAX_TIMER_WAIT_MASTER_SLAVE)
            {
                edrk.Status_Ready.bits.MasterSlaveActive = 1;

                if (edrk.auto_master_slave.local.bits.master)
                  edrk.MasterSlave = MODE_MASTER;
                else
                  edrk.MasterSlave = MODE_SLAVE;
            }
            else
            {
                edrk.Status_Ready.bits.MasterSlaveActive = 0;
                edrk.MasterSlave = MODE_DONTKNOW;
                timer_wait_to_master_slave++;
            }
            prev_master = edrk.auto_master_slave.local.bits.master;
        }
        else
        {

            edrk.Status_Ready.bits.MasterSlaveActive = 0;
            edrk.MasterSlave = MODE_DONTKNOW;

            timer_wait_to_master_slave = 0;
        }


        set_tics_timer_pwm(12,count_timer_buf);
        get_tics_timer_pwm(pwm_enable_calc_main_log);


        if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_OBOROTS || edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_POWER) {
            if (edrk.MasterSlave == MODE_MASTER) {
                if (get_start_ged_from_zadanie()) {
                    edrk.prepare_stop_PWM = 0;
                    //edrk.StartGEDfromZadanie = 1;
                    localStartGEDfromZadanie = 1;
                } else {
                    edrk.prepare_stop_PWM = 1;
                    if (edrk.k_stator1 < 41943) {  //335544 ~ 2%
                        //edrk.StartGEDfromZadanie = 0;
                        localStartGEDfromZadanie = 0;
                    }
                }
            } else {
                if (get_start_ged_from_zadanie()) {
                    //edrk.StartGEDfromZadanie = 1;
                    localStartGEDfromZadanie = 1;
                } else {
                    if (edrk.k_stator1 < 41943) {  //335544 ~ 2%
                        //edrk.StartGEDfromZadanie = 0;
                        localStartGEDfromZadanie = 0;
                    }
                }
                edrk.prepare_stop_PWM = optical_read_data.data.cmd.bit.prepare_stop_PWM;
            }
        } else {
            //edrk.StartGEDfromZadanie =
            localStartGEDfromZadanie = get_start_ged_from_zadanie();
        }

        // задержка прохождения localStartGEDfromZadanie=1 в edrk.StartGEDfromZadanie
        if (localStartGEDfromZadanie && edrk.prevStartGEDfromZadanie==0)
        {
            if (countStartGEDfromZadanie<MAX_COUNT_COUNTSTARTGEDFROMZADANIE)
                countStartGEDfromZadanie++;
            else
                edrk.StartGEDfromZadanie = localStartGEDfromZadanie;
        }
        else
        {
            edrk.StartGEDfromZadanie = localStartGEDfromZadanie;
            countStartGEDfromZadanie = 0;
        }


        edrk.prevStartGEDfromZadanie = edrk.StartGEDfromZadanie;

        set_tics_timer_pwm(13,count_timer_buf);
        get_tics_timer_pwm(pwm_enable_calc_main_log);



        // мы крутим и есть запрос на подключение расцепителя?
        if (optical_read_data.data.cmd.bit.rascepitel_cmd==CODE_RASCEPITEL_CMD_REQUEST_AND_THIS_OFF)
        {
            if (edrk.StartGEDfromZadanie==1)
            {
               edrk.flag_wait_set_to_zero_zadanie = 1;
               edrk.you_can_on_rascepitel = 0;
            }
            else
                edrk.flag_block_zadanie = 1;
        }
        else
        {
            if (edrk.StartGEDfromZadanie)
              edrk.you_can_on_rascepitel = 0;
            else
                edrk.you_can_on_rascepitel = 1;
        }
//            edrk.flag_wait_set_to_zero_zadanie = 0;



        set_tics_timer_pwm(131,count_timer_buf);
        get_tics_timer_pwm(pwm_enable_calc_main_log);


        if (optical_read_data.data.cmd.bit.ready_cmd == CODE_READY_CMD_READY1TO2
                && optical_write_data.data.cmd.bit.ready_cmd == CODE_READY_CMD_READY1TO2)
        {
            // оба БС вошли в режим сбора из Готовность1 в 2.
            edrk.flag_wait_both_ready2 = 1;
        }


//        if (optical_read_data.data.cmd.bit.ready_cmd)
//
//        edrk.flag_another_bs_first_ready12

        if (optical_read_data.data.cmd.bit.ready_cmd == CODE_READY_CMD_READY2
                && optical_write_data.data.cmd.bit.ready_cmd == CODE_READY_CMD_READY2 && edrk.flag_wait_both_ready2)
        {
            // дождались сбора обоих
            edrk.flag_wait_both_ready2 = 0;
        }

        if (optical_write_data.data.cmd.bit.ready_cmd == CODE_READY_CMD_READY1)
            edrk.flag_wait_both_ready2 = 0;

        if (edrk.flag_wait_both_ready2)
        {
            if (timer_wait_both_ready2>MAX_TIMER_WAIT_BOTH_READY2)
                edrk.errors.e1.bits.VERY_LONG_BOTH_READY2 |= 1;
            else
                timer_wait_both_ready2++;

        }
        else
            timer_wait_both_ready2 = 0;


        if (optical_read_data.data.cmd.bit.rascepitel_cmd==CODE_RASCEPITEL_CMD_ENABLE_ON_AND_THIS_ON
                && optical_read_data.data.cmd.bit.ready_cmd == CODE_READY_CMD_READY2) // тот расцепитель включен или включился и тот БС собрался
        {
            edrk.flag_block_zadanie = 0;
            edrk.flag_wait_set_to_zero_zadanie = 0;
        }

        if (optical_read_data.data.cmd.bit.rascepitel_cmd==CODE_RASCEPITEL_CMD_ENABLE_ON_AND_THIS_OFF
                && optical_read_data.data.cmd.bit.ready_cmd == CODE_READY_CMD_READY1) // тот расцепитель выключен и схема на том БС разобрана
        {
            edrk.flag_block_zadanie = 0;
            edrk.flag_wait_set_to_zero_zadanie = 0;
        }


        if (edrk.StartGEDfromZadanie==0 && edrk.flag_block_zadanie
                && (optical_read_data.data.cmd.bit.rascepitel_cmd==CODE_RASCEPITEL_CMD_REQUEST_AND_THIS_OFF))
        // разрешаем другому БС завести расцепитель
            edrk.you_can_on_rascepitel = 1;


        if (edrk.flag_wait_set_to_zero_zadanie)
        {
            if (timer_wait_set_to_zero_zadanie>MAX_TIMER_WAIT_SET_TO_ZERO_ZADANIE)
            {
                // другой БС запросил включения своего расцепителя, мы сбросили обороты и ждали пока тот БС соберет свою схему
                // но этого не произошло!!!!
                edrk.errors.e1.bits.ANOTHER_BS_NOT_ON_RASCEPITEL |= 1;

            }
            else
               timer_wait_set_to_zero_zadanie++;

        }
        else
            timer_wait_set_to_zero_zadanie = 0;


        // если ошибка подключения, то обнуляем запрос на подключение.
        if (edrk.errors.e1.bits.ANOTHER_BS_NOT_ON_RASCEPITEL)
            edrk.flag_wait_set_to_zero_zadanie = 0;


        edrk.StartGED = ((edrk.StartGEDfromControl==1) && (edrk.StartGEDfromZadanie==1) && (edrk.flag_block_zadanie==0));


        if (edrk.MasterSlave == MODE_MASTER)
        {
            edrk.GoWait = ( (edrk.StartGED ) && (edrk.Stop == 0)
                    && (project.controller.read.errors.all==0) &&
                    (slow_error==0) &&
                    (edrk.Status_Ready.bits.ready_final)
                    && edrk.Status_Ready.bits.MasterSlaveActive
                    && edrk.warnings.e9.bits.BREAKER_GED_ON==0
                    );
        }
        else
        if (edrk.MasterSlave == MODE_SLAVE)
        {
            edrk.GoWait = ( (edrk.StartGED && edrk.StartGEDfromSyncBus) && (edrk.Stop == 0)
                        && (project.controller.read.errors.all==0) &&
                        (slow_error==0) &&
                        (edrk.Status_Ready.bits.ready_final)
                        && edrk.Status_Ready.bits.MasterSlaveActive
                        );
        }
        else
            edrk.GoWait = 0;

        //    if (edrk.GoWait==0 && edrk.Go == 0 &&


        // исключаем дребезг сигнала edrk.Go
        if (edrk.GoWait)
        {
            if (count_wait_go_0>=MAX_COUNT_WAIT_GO_0)
                edrk.Go = edrk.GoWait;
            else
            {
                edrk.Go = 0;
                edrk.errors.e7.bits.VERY_FAST_GO_0to1 |=1; // ошибка! слишком быстро пришел повторный edrk.Go!!!
            }
        }
        else
        {
            if (edrk.Go)
                count_wait_go_0 = 0;

            edrk.Go = 0;
            if (count_wait_go_0<MAX_COUNT_WAIT_GO_0)
                count_wait_go_0++;
        }


        if (optical_read_data.data.cmd.bit.ready_cmd == CODE_READY_CMD_READY2)
            edrk.count_bs_work = 1;
        else
            edrk.count_bs_work = 0;

#if (_ENABLE_LOG_TICS_PWM==1)
/*
        if (stop_count_time_buf==0)
        {
          count_time_buf++;
          if (count_time_buf>=(MAX_COUNT_TIME_BUF-1))
              count_time_buf = 0;

          log_wait = 0;
          if (edrk.MasterSlave == MODE_MASTER)
              log_wait |= 0x1;
          if (edrk.MasterSlave == MODE_SLAVE)
              log_wait |= 0x2;
          if (edrk.StartGED)
              log_wait |= 0x4;
          if (edrk.Stop)
              log_wait |= 0x8;
          if (edrk.Status_Ready.bits.ready_final)
              log_wait |= 0x10;
          if (edrk.Status_Ready.bits.MasterSlaveActive)
              log_wait |= 0x20;
          if (edrk.GoWait)
              log_wait |= 0x40;
          if (edrk.Go)
              log_wait |= 0x80;
          if (project.controller.read.errors.all==0)
              log_wait |= 0x100;
          if (slow_error)
              log_wait |= 0x200;
          if (edrk.StartGEDfromSyncBus)
              log_wait |= 0x400;


          time_buf[count_time_buf] = log_wait;

          if (edrk.errors.e7.bits.VERY_FAST_GO_0to1)
              stop_count_time_buf = 1;
        }
*/
#endif



#if(_ENABLE_PWM_LINES_FOR_TESTS_GO)
        if (edrk.StartGEDfromSyncBus)
        {
            PWM_LINES_TK_17_ON;
        }
        else
        {
            PWM_LINES_TK_17_OFF;
        }

        if (edrk.StartGEDfromZadanie)
        {
            PWM_LINES_TK_18_ON;
        }
        else
        {
            PWM_LINES_TK_18_OFF;
        }
        if (edrk.flag_block_zadanie)
        {
            PWM_LINES_TK_19_ON;
        }
        else
        {
            PWM_LINES_TK_19_OFF;
        }

    if (edrk.StartGEDfromControl)
    {
        PWM_LINES_TK_16_ON;
    }
    else
    {
        PWM_LINES_TK_16_OFF;
    }

#endif



        set_tics_timer_pwm(15,count_timer_buf);
        get_tics_timer_pwm(pwm_enable_calc_main_log);

        //////////////////////////////////
        //////////////////////////////////

		if(edrk.Go == 1)
		{
			if (edrk.Go != prevGo)
			{
			    edrk.count_run++;
//				clear_mem(FAST_LOG);
//				count_start_impuls = 0;
//				count_step = 0;
				f.count_step_ram_off = COUNT_SAVE_LOG_OFF;
//				count_step_run = 0;

    //            set_start_mem(FAST_LOG);
    //            set_start_mem(SLOW_LOG);

          //      logpar.start_write_fast_log = 1;

                init_uf_const();
                init_simple_scalar();

                Fzad = 0;
                Uzad1 = 0;
                Uzad2 = 0;

                clear_logpar();
			}
			else
			{

				if (f.count_start_impuls < COUNT_START_IMP)
				{
				    f.count_start_impuls++;
				}
				else
				{
				    f.count_start_impuls = COUNT_START_IMP;

				    f.flag_record_log = 1;
	                enable_calc_vector = 1;

				}

			}
		}
		else  // (edrk.Go == 0)
		{

	        if (f.count_step_ram_off > 0)
	        {
	            f.count_step_ram_off--;
	            f.flag_record_log = 1;
	        } else {
	            f.flag_record_log = 0;
	        }

	        // ручной разряд
	        if (edrk.ManualDischarge && prev_ManualDischarge!=edrk.ManualDischarge)
	            edrk.Discharge = 1;

	        prev_ManualDischarge =edrk.ManualDischarge;

            if (f.count_start_impuls == 0)
            {

                if (edrk.Discharge || (edrk.ManualDischarge )   )
                {
                    break_resistor_managment_calc();
                    soft_start_x24_break_1();
                }
                else
                {

                    if (f.count_step_ram_off > 0)
                    {
                        break_resistor_recup_calc(edrk.zadanie.iq_set_break_level);
      //                  soft_start_x24_break_1();
                    }
                    else
                    {
                        // это произойдет только на последнем такте выключения
                           soft_stop_x24_pwm_all();

                    }
                }

            }

            set_tics_timer_pwm(16,count_timer_buf);
            get_tics_timer_pwm(pwm_enable_calc_main_log);

            if (f.count_start_impuls==COUNT_START_IMP)
            {
                if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_OBOROTS || edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_POWER)
                {
                    if (edrk.flag_second_PCH == 0) {
                        wd = uf_alg.winding_displacement_bs1;
                    } else {
                        wd = uf_alg.winding_displacement_bs2;
                    }

                    vectorControlConstId(edrk.zadanie.iq_power_zad_rmp, edrk.zadanie.iq_oborots_zad_hz_rmp,
                                         WRotor.RotorDirectionSlow, WRotor.iqWRotorSumFilter,
                                         edrk.Mode_ScalarVectorUFConst,
                                         edrk.MasterSlave, edrk.zadanie.iq_Izad, wd,
                                         edrk.master_theta, edrk.master_Iq, edrk.iq_power_kw_another_bs,
                                         &edrk.tetta_to_slave, &edrk.Iq_to_slave, &edrk.P_to_master,
                                         0, 1);

                    test_calc_vect_dq_pwm24_Ing(vect_control.iqTheta, vect_control.iqUdKm, vect_control.iqUqKm,
                                                edrk.disable_alg_u_disbalance,
                                                edrk.zadanie.iq_kplus_u_disbalance_rmp,  edrk.zadanie.iq_k_u_disbalance_rmp,
                                                filter.iqU_1_fast, filter.iqU_2_fast,
                                                0,
                                                edrk.Uzad_max,
                                                edrk.MasterSlave,
                                                edrk.flag_second_PCH,
                                                &edrk.Kplus, &edrk.Uzad_to_slave);
                    analog.PowerFOC = edrk.P_to_master;
                    Fzad = vect_control.iqFstator;
                    Izad_out = edrk.Iq_to_slave;
                } else {
                    test_calc_simple_dq_pwm24_Ing(Fzad, 0, 0,
                                                  0,  0, filter.iqU_1_fast, filter.iqU_2_fast,
                                                  1,
                                                  edrk.Uzad_max,
                                                  edrk.master_theta,
                                                  edrk.master_Uzad,
                                                  edrk.MasterSlave,
                                                  edrk.flag_second_PCH,
                                                  &edrk.Kplus, &edrk.tetta_to_slave,
                                                  &edrk.Uzad_to_slave);
                }
            }
            else
            {
                if (f.count_start_impuls==COUNT_START_IMP-1)
                {

                    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_OBOROTS || edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_POWER)
                    {
                        if (edrk.flag_second_PCH == 0) {
                            wd = uf_alg.winding_displacement_bs1;
                        } else {
                            wd = uf_alg.winding_displacement_bs2;
                        }

                        vectorControlConstId(edrk.zadanie.iq_power_zad_rmp, edrk.zadanie.iq_oborots_zad_hz_rmp,
                                             WRotor.RotorDirectionSlow, WRotor.iqWRotorSumFilter,
                                             edrk.Mode_ScalarVectorUFConst,
                                             edrk.MasterSlave, edrk.zadanie.iq_Izad, wd,
                                             edrk.master_theta, edrk.master_Iq, edrk.iq_power_kw_another_bs,
                                             &edrk.tetta_to_slave, &edrk.Iq_to_slave, &edrk.P_to_master,
                                             0, 1);

                        test_calc_vect_dq_pwm24_Ing(vect_control.iqTheta, vect_control.iqUdKm, vect_control.iqUqKm,
                                                    edrk.disable_alg_u_disbalance,
                                                    edrk.zadanie.iq_kplus_u_disbalance_rmp,  edrk.zadanie.iq_k_u_disbalance_rmp,
                                                    filter.iqU_1_fast, filter.iqU_2_fast,
                                                    0,
                                                    edrk.Uzad_max,
                                                    edrk.MasterSlave,
                                                    edrk.flag_second_PCH,
                                                    &edrk.Kplus, &edrk.Uzad_to_slave);
                        analog.PowerFOC = edrk.P_to_master;
                        Fzad = vect_control.iqFstator;
                        Izad_out = edrk.Iq_to_slave;
                    } else {
                        test_calc_simple_dq_pwm24_Ing(Fzad, 0, 0,
                                                      0,  0, filter.iqU_1_fast, filter.iqU_2_fast,
                                                      1,
                                                      edrk.Uzad_max,
                                                      edrk.master_theta,
                                                      edrk.master_Uzad,
                                                      edrk.MasterSlave,
                                                      edrk.flag_second_PCH,
                                                      &edrk.Kplus, &edrk.tetta_to_slave,
                                                      &edrk.Uzad_to_slave);
                    }

                }
                else
                {
                     if (f.count_start_impuls==COUNT_START_IMP-2)
                     {
                        // тут опять middle состояние перед выключением ключей
//                         svgen_set_time_keys_closed(&svgen_pwm24_1);
//                         svgen_set_time_keys_closed(&svgen_pwm24_2);
                         svgen_set_time_middle_keys_open(&svgen_pwm24_1);
                         svgen_set_time_middle_keys_open(&svgen_pwm24_2);
                     }
                     else
                     // а тут мы уже выключились
                     {
                        svgen_set_time_keys_closed(&svgen_pwm24_1);
                        svgen_set_time_keys_closed(&svgen_pwm24_2);
                     }

                     Fzad = 0;

                }
            }


	        if (f.count_start_impuls > 0) {
	                    f.count_start_impuls -= 1;
	                } else {
	                    f.count_start_impuls = 0;
	                }
			enable_calc_vector = 0;



			Uzad1 = 0;
			Uzad2 = 0;

		}  // end if Go==1

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_18_OFF;
#endif


	  }  // end pwm_enable_calc_main one interrupt one period only

/*
 *
            //                if ((m.m0.bit.EnableGoA == 1) && (f.Obmotka1 == 0))


            //                if ((m.m0.bit.EnableGoB == 1) && (f.Obmotka2 == 0))
                            if (f.Obmotka2 == 0)
                            {
                                go_b = 1;
                            }
                            else
                            {
                                go_b = 0;
                            }

                            if (go_a == 0 && prev_go_a != go_a)
                            {
                                //отключаем 1 обмотку
                                soft_stop_x24_pwm_1();
                            }

                            if (go_a == 1 && prev_go_a != go_a)
                            {
                                //включаем 1 обмотку
                                soft_start_x24_pwm_1();
                            }

                            if (go_b == 0 && prev_go_b != go_b)
                            {
                                //отключаем 2 обмотку
                                soft_stop_x24_pwm_2();
                            }

                            if (go_b == 1 && prev_go_b != go_b)
                            {
                                //включаем 2 обмотку
                                soft_start_x24_pwm_2();
                            }

                            prev_go_a = go_a;
                            prev_go_b = go_b;
 *
 *
 */

      ///////////////////////////////////////////
      ///////////////////////////////////////////
      ///////////////////////////////////////////
      ///////////////////////////////////////////
      ///////////////////////////////////////////
      ///////////////////////////////////////////
      ///////////////////////////////////////////
      ///////////////////////////////////////////

	  if (pwm_enable_calc_main) // заходим в расчет только раз за период шима
	  {


        if (f.count_start_impuls==1 && edrk.Go==1)
        {
            // а тут мы еше не включились
            svgen_set_time_keys_closed(&svgen_pwm24_1);
            svgen_set_time_keys_closed(&svgen_pwm24_2);
 //           soft_start_x24_pwm_1_2();
            if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_OBOROTS || edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_POWER) {
                if (edrk.flag_second_PCH == 0) {
                    wd = uf_alg.winding_displacement_bs1;
                } else {
                    wd = uf_alg.winding_displacement_bs2;
                }
                vectorControlConstId(edrk.zadanie.iq_power_zad_rmp, edrk.zadanie.iq_oborots_zad_hz_rmp,
                                     WRotor.RotorDirectionSlow, WRotor.iqWRotorSumFilter,
                                     edrk.Mode_ScalarVectorUFConst,
                                     edrk.MasterSlave, edrk.zadanie.iq_Izad, wd,
                                     edrk.master_theta, edrk.master_Iq, edrk.P_from_slave,
                                     &edrk.tetta_to_slave, &edrk.Iq_to_slave, &edrk.P_to_master, 1, edrk.prepare_stop_PWM);
            }
        }

        if (f.count_start_impuls==2 && edrk.Go==1)
        {
            // включаем ШИМ
             if (go_a == 1 && go_b == 1) {
             // start_pwm(); должен вызваться один раз за изменение edrk.Go
                 soft_start_x24_pwm_1_2();
             } else if (go_a == 1) {
                 soft_start_x24_pwm_1();
             } else if (go_b == 1) {
                 soft_start_x24_pwm_2();
             }

             // enable work break
#if (DISABLE_WORK_BREAK==1)

#else
//                          if (edrk.disable_break_work==0)
                          {
                              soft_start_x24_break_1();
                          }
#endif

        } // end if (count_start_impuls==5)


        if (f.count_start_impuls==3 && edrk.Go==1)
        {
            // готовимся разрешить ШИМ
                    svgen_set_time_middle_keys_open(&svgen_pwm24_1);
                    svgen_set_time_middle_keys_open(&svgen_pwm24_2);
        }



        if (f.count_start_impuls==4 && edrk.Go==1)
        {
            if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_OBOROTS || edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_POWER)
            {

//              void simple_scalar(int n_alg, int n_wind_pump, _iq Frot_pid, _iq Frot,_iq fzad,_iq mzz_zad, _iq bpsi_const, _iq fzad_provorot,
//                                  _iq iqIm_1, _iq iqIm_2, _iq iqUin, _iq Iin, _iq powerzad, _iq power_pid,
//                                   _iq *Fz, _iq *Uz1)

                if (edrk.flag_second_PCH == 0) {
                    wd = uf_alg.winding_displacement_bs1;
                } else {
                    wd = uf_alg.winding_displacement_bs2;
                }

                vectorControlConstId(0, 0,
                                     WRotor.RotorDirectionSlow, WRotor.iqWRotorSumFilter,
                                     edrk.Mode_ScalarVectorUFConst,
                                     edrk.MasterSlave, edrk.zadanie.iq_Izad, wd,
                                     edrk.master_theta, edrk.master_Iq, edrk.iq_power_kw_another_bs,
                                     &edrk.tetta_to_slave, &edrk.Iq_to_slave, &edrk.P_to_master,
                                     0, edrk.prepare_stop_PWM);

                test_calc_vect_dq_pwm24_Ing(vect_control.iqTheta, vect_control.iqUdKm, vect_control.iqUqKm,
                                            edrk.disable_alg_u_disbalance,
                                            edrk.zadanie.iq_kplus_u_disbalance_rmp,  edrk.zadanie.iq_k_u_disbalance_rmp,
                                            filter.iqU_1_fast, filter.iqU_2_fast,
                                            0,
                                            edrk.Uzad_max,
                                            edrk.MasterSlave,
                                            edrk.flag_second_PCH,
                                            &edrk.Kplus, &edrk.Uzad_to_slave);
                Fzad = vect_control.iqFstator;
                Izad_out = edrk.Iq_to_slave;
            } else {
                test_calc_simple_dq_pwm24_Ing(Fzad, 0, 0,
                      0,  0, filter.iqU_1_fast, filter.iqU_2_fast,
                      0,
                      edrk.Uzad_max,
                      edrk.master_theta,
                      edrk.master_Uzad,
                      edrk.MasterSlave,
                      edrk.flag_second_PCH,
                      &edrk.Kplus, &edrk.tetta_to_slave, &edrk.Uzad_to_slave);


                simple_scalar(1,0, WRotor.RotorDirectionSlow,
                              WRotor.iqWRotorSumFilter2, WRotor.iqWRotorSumFilter,
                                              0,
                                              0,
                                              0, edrk.iq_bpsi_normal,
                                              0,
                //                            analog.iqU_1_long+analog.iqU_2_long,
                                              edrk.zadanie.iq_ZadanieU_Charge_rmp+edrk.zadanie.iq_ZadanieU_Charge_rmp,
                                              0,
                                              edrk.zadanie.iq_power_zad_rmp, 0,
                                              edrk.zadanie.iq_limit_power_zad_rmp, edrk.Mode_ScalarVectorUFConst,
                                              0,0, edrk.count_bs_work+1,
                                              &Fzad, &Uzad1, &Uzad2, &Izad_out);
            }

        }

	    if (f.count_start_impuls == COUNT_START_IMP && edrk.Go==1)
	    {
	       if (pwm_enable_calc_main) // заходим в расчет только раз за период шима
	       {
#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_21_ON;
#endif


	           //break_resistor_recup_calc(edrk.zadanie.iq_ZadanieU_Charge);
	           break_resistor_recup_calc(edrk.zadanie.iq_set_break_level);

	           set_tics_timer_pwm(17,count_timer_buf);
	           get_tics_timer_pwm(pwm_enable_calc_main_log);

	           run_calc_uf = 1;

	        // основная работа тут, ШИМ уже включен в middle
	        if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_UF_CONST)
	        {
#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_ON;
#endif
	            uf_const(&Fzad,&Uzad1,&Uzad2);
#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_OFF;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_ON;
#endif

	            test_calc_simple_dq_pwm24_Ing(Fzad,
	                                          Uzad1,
	                                          edrk.disable_alg_u_disbalance,
	                                      edrk.zadanie.iq_kplus_u_disbalance,
	                                      edrk.zadanie.iq_k_u_disbalance,
	                                      filter.iqU_1_fast,
	                                      filter.iqU_2_fast,
	                                      0,
	                                      edrk.Uzad_max,
	                                      edrk.master_theta,
	                                      edrk.master_Uzad,
	                                      edrk.MasterSlave,
	                                      edrk.flag_second_PCH,
	                                      &edrk.Kplus,
	                                      &edrk.tetta_to_slave,
	                                      &edrk.Uzad_to_slave);
//	            rmp_freq.DesiredInput = alg_pwm24.freq1;
//                rmp_freq.calc(&rmp_freq);
//                Fzad = rmp_freq.Out;
//
//                vhz1.Freq = Fzad;
//                vhz1.calc(&vhz1);
//
//
//                Uzad1 = alg_pwm24.k1;
//                Uzad2 = alg_pwm24.k1;

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_OFF;
#endif

	//            test_calc_pwm24(Uzad1, Uzad2, Fzad);
	  //          analog_dq_calc_const();

	        } // end ALG_MODE_UF_CONST
	        else
	        if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_SCALAR_OBOROTS || edrk.Mode_ScalarVectorUFConst == ALG_MODE_SCALAR_POWER)
	        {
#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_ON;
#endif
	            simple_scalar(1,
	                          0,
	                          WRotor.RotorDirectionSlow,
	                          WRotor.iqWRotorSumFilter,   //rotor_22220.iqFlong * rotor_22220.direct_rotor;
	                          WRotor.iqWRotorSumFilter, //rotor_22220.iqFout  * rotor_22220.direct_rotor;
	                          //0, 0,
	                          edrk.zadanie.iq_oborots_zad_hz_rmp,
	                          edrk.all_limit_koeffs.sum_limit,
	                          edrk.zadanie.iq_Izad_rmp,
	                          edrk.iq_bpsi_normal,
	                          analog.iqIm,
//	                          analog.iqU_1_long+analog.iqU_2_long,
	                          edrk.zadanie.iq_ZadanieU_Charge_rmp+edrk.zadanie.iq_ZadanieU_Charge_rmp,
	                          analog.iqIin_sum,
	                          edrk.zadanie.iq_power_zad_rmp,
	                          edrk.iq_power_kw_full_znak,//(filter.PowerScalar+edrk.iq_power_kw_another_bs),
	                          edrk.zadanie.iq_limit_power_zad_rmp, edrk.Mode_ScalarVectorUFConst,
	                          edrk.master_Izad,
	                          edrk.MasterSlave,
	                          edrk.count_bs_work+1,
	                          &Fzad,
	                          &Uzad1,
	                          &Uzad2,
	                          &Izad_out);

	            set_tics_timer_pwm(18,count_timer_buf);
	            get_tics_timer_pwm(pwm_enable_calc_main_log);

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_OFF;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_ON;
#endif



    if (edrk.cmd_disable_calc_km_on_slave)
        Uzad_from_master = edrk.master_Uzad;
    else
    {
#if (DISABLE_CALC_KM_ON_SLAVE==1)
        Uzad_from_master = edrk.master_Uzad;
#else
        Uzad_from_master =  Uzad1;
#endif

    }

                test_calc_simple_dq_pwm24_Ing(Fzad, Uzad1, edrk.disable_alg_u_disbalance,
                                          edrk.zadanie.iq_kplus_u_disbalance,  edrk.zadanie.iq_k_u_disbalance, filter.iqU_1_fast, filter.iqU_2_fast,
                                          0,
                                          edrk.Uzad_max,
                                          edrk.master_theta,
                                          Uzad_from_master,
                                          edrk.MasterSlave,
                                          edrk.flag_second_PCH,
                                          &edrk.Kplus, &edrk.tetta_to_slave, &edrk.Uzad_to_slave);
#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_OFF;
#endif

                set_tics_timer_pwm(19,count_timer_buf);
            get_tics_timer_pwm(pwm_enable_calc_main_log);

                if (edrk.flag_second_PCH == 0) {
                    wd = uf_alg.winding_displacement_bs1;
                } else {
                    wd = uf_alg.winding_displacement_bs2;
                }

                analog_dq_calc_external(wd, uf_alg.tetta);

	        } // end ALG_MODE_SCALAR_OBOROTS
            else
            if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_OBOROTS || edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_POWER)
            {

//	            void simple_scalar(int n_alg, int n_wind_pump, _iq Frot_pid, _iq Frot,_iq fzad,_iq mzz_zad, _iq bpsi_const, _iq fzad_provorot,
//	                                _iq iqIm_1, _iq iqIm_2, _iq iqUin, _iq Iin, _iq powerzad, _iq power_pid,
//	                                 _iq *Fz, _iq *Uz1)

	            if (edrk.flag_second_PCH == 0) {
	            	wd = uf_alg.winding_displacement_bs1;
	            } else {
	            	wd = uf_alg.winding_displacement_bs2;
	            }
#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_ON;
#endif
	            vectorControlConstId(edrk.zadanie.iq_power_zad_rmp, edrk.zadanie.iq_oborots_zad_hz_rmp,
	                                 WRotor.RotorDirectionSlow, WRotor.iqWRotorSumFilter,
	                                 edrk.Mode_ScalarVectorUFConst,
	                                 edrk.MasterSlave, edrk.zadanie.iq_Izad, wd,
									 edrk.master_theta, edrk.master_Iq, edrk.iq_power_kw_another_bs,
									 &edrk.tetta_to_slave, &edrk.Iq_to_slave, &edrk.P_to_master,
									 0, edrk.prepare_stop_PWM);
#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_OFF;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_ON;
#endif

	            test_calc_vect_dq_pwm24_Ing(vect_control.iqTheta, vect_control.iqUdKm, vect_control.iqUqKm,
	                                        edrk.disable_alg_u_disbalance,
                                            edrk.zadanie.iq_kplus_u_disbalance_rmp,  edrk.zadanie.iq_k_u_disbalance_rmp,
                                            filter.iqU_1_fast, filter.iqU_2_fast,
                                            0,
                                            edrk.Uzad_max,
                                            edrk.MasterSlave,
                                            edrk.flag_second_PCH,
                                            &edrk.Kplus, &edrk.Uzad_to_slave);

	            analog.PowerFOC = edrk.P_to_master;
	            Fzad = vect_control.iqFstator;
	            Izad_out = edrk.Iq_to_slave;

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_20_OFF;
#endif
	        } // end ALG_MODE_FOC_OBOROTS

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_21_OFF;
#endif

	       } // end pwm_enable_calc_main

	    }  // end (count_start_impuls == COUNT_START_IMP && edrk.Go==1)
	    else
	    {
	       run_calc_uf = 0;
	       if (pwm_enable_calc_main) // заходим в расчет только раз за период шима
           {

           }
	       svgen_pwm24_1.Ta_imp = 0;
           svgen_pwm24_1.Tb_imp = 0;
           svgen_pwm24_1.Tc_imp = 0;
           svgen_pwm24_2.Ta_imp = 0;
           svgen_pwm24_2.Tb_imp = 0;
           svgen_pwm24_2.Tc_imp = 0;

	    } // end else (count_start_impuls == COUNT_START_IMP && edrk.Go==1)

		prevGo = edrk.Go;



        //////////////////////////////////
        optical_write_data.data.cmd.bit.start_pwm = edrk.Go;
        optical_write_data.data.cmd.bit.prepare_stop_PWM = edrk.prepare_stop_PWM;

        optical_write_data.data.angle_pwm     =  _IQtoIQ12(edrk.tetta_to_slave + vect_control.add_tetta);
        optical_write_data.data.pzad_or_wzad  =  _IQtoIQ15(edrk.Uzad_to_slave);
        optical_write_data.data.iq_zad_i_zad  =  _IQtoIQ15(edrk.Izad_out);

        optical_bus_update_data_write();

        set_tics_timer_pwm(20,count_timer_buf);
        get_tics_timer_pwm(pwm_enable_calc_main_log);


        if (edrk.ms.another_bs_maybe_on==1 && edrk.auto_master_slave.local.bits.master)
        {
        //    i_led2_on();
        }

        //////////////////////////////////
        //////////////////////////////////

    edrk.Izad_out = Izad_out;

    if (edrk.MasterSlave==MODE_SLAVE)
    {
        edrk.f_stator  = Fzad;
        edrk.k_stator1 = edrk.Uzad_to_slave;//Uzad1;
        edrk.k_stator2 = edrk.Uzad_to_slave;//Uzad2;

    }
    else
        if (edrk.MasterSlave==MODE_MASTER)
        {
            edrk.f_stator  = Fzad;
            edrk.k_stator1 = edrk.Uzad_to_slave;//Uzad1;
            edrk.k_stator2 = edrk.Uzad_to_slave;
        }
        else
        {
            edrk.f_stator  = 0;
            edrk.k_stator1 = 0;
            edrk.k_stator2 = 0;
        }

  } // end pwm_enable_calc_main




	  ///////////////////////////////////////////
	  ///////////////////////////////////////////
	  ///////////////////////////////////////////
	  ///////////////////////////////////////////


#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_22_ON;
#endif

	  if (xpwm_time.one_or_two_interrupts_run == PWM_ONE_INTERRUPT_RUN)
	      write_swgen_pwm_times(PWM_MODE_RELOAD_FORCE);
	  else
	  {
	      if (edrk.Go==1)
	      {
	          if (f.count_start_impuls==COUNT_START_IMP-1)
	          {
	               if (pwm_enable_calc_main)
	                  write_swgen_pwm_times(PWM_MODE_RELOAD_LEVEL_HIGH);
	               else
	                  write_swgen_pwm_times(PWM_MODE_RELOAD_LEVEL_LOW);
	          }
	          else
//	              if (pwm_enable_calc_main)
	             write_swgen_pwm_times(PWM_MODE_RELOAD_FORCE);
	      }
	      else
	      {
	          if (f.count_start_impuls==COUNT_START_IMP-3)
	          {
                  if (pwm_enable_calc_main)
                     write_swgen_pwm_times(PWM_MODE_RELOAD_LEVEL_HIGH);
                  else
                     write_swgen_pwm_times(PWM_MODE_RELOAD_LEVEL_LOW);

	          }
	          else
	            write_swgen_pwm_times(PWM_MODE_RELOAD_FORCE);
	      }



	//      if (pwm_enable_calc_main)
	//          prev_run_calc_uf = run_calc_uf;



	  }
#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_22_OFF;
#endif


	set_tics_timer_pwm(21,count_timer_buf);
    get_tics_timer_pwm(pwm_enable_calc_main_log);


    // test write oscil buf

    if ( pwm_enable_calc_main==0) // заходим в расчет только раз за период шима
    {

        run_write_logs();

    }


    //    i_led2_on();
    //
        if (edrk.SumSbor == 1) {
            detect_protect_adc(uf_alg.tetta_bs, uf_alg.tetta_bs);
    ////        get_tics_timer_pwm(pwm_enable_calc_main,count_timer_buf);
        }

    //    fill_RMS_buff_interrupt(uf_alg.tetta_bs, uf_alg.tetta_bs);

        set_tics_timer_pwm(24,count_timer_buf);
        get_tics_timer_pwm(pwm_enable_calc_main_log);


    //    out_I_over_1_6.calc(&out_I_over_1_6);
    //    i_led2_off();


    pwm_run = 0;


	} // end if pwm_run==1

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_16_OFF;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_16_ON;
#endif

	if (pwm_enable_calc_main==0) // заходим в расчет только раз за период шима
	{


	 //   pwm_analog_ext_interrupt();

//	     inc_RS_timeout_cicle();
//	     inc_CAN_timeout_cicle();

#if (_SIMULATE_AC==1)
	sim_model_execute();
#endif

	}

	 pwm_analog_ext_interrupt();
	 pwm_inc_interrupt();



#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_16_OFF;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_16_ON;
#endif




    set_tics_timer_pwm(25,count_timer_buf);
    get_tics_timer_pwm(pwm_enable_calc_main_log);


#if (_ENABLE_SLOW_PWM)
//    pause_1000(slow_pwm_pause);
#endif

    set_tics_timer_pwm(26,count_timer_buf);
    get_tics_timer_pwm(pwm_enable_calc_main_log);

/////////////////////////////////////////////////
	// считаем время работы в прерывании
   end_tics_4timer = EvbRegs.T3CNT;

   if (end_tics_4timer>start_tics_4timer)
   {
     time_delta = (end_tics_4timer - start_tics_4timer);
	 time_delta = time_delta * 33/1000;
	 if (pwm_enable_calc_main)
	     edrk.period_calc_pwm_int1 = time_delta;//(end_tics_4timer - start_tics_4timer)*33/1000;
	 else
	     edrk.period_calc_pwm_int2 = time_delta;//(end_tics_4timer - start_tics_4timer)*33/1000;
   }
   // закончили считать время работы в прерывании
   /////////////////////////////////////////////////

 //  get_tics_timer_pwm(pwm_enable_calc_main,count_timer_buf);





#if (_ENABLE_LOG_TICS_PWM==1)

	for (i_log=count_timer_buf;i_log<MAX_COUNT_TIME_BUF;i_log++)
	{
	    time_buf[i_log] = 0;
	}

    set_tics_timer_pwm(100,count_timer_buf);
    time_buf[count_timer_buf] = time_delta;

//    set_tics_timer_pwm(edrk.period_calc_pwm_int);


	if (c_run>=10000)
	    c_run=c_run_start;
	else
	  c_run++;
#endif

#if (ENABLE_LOG_INTERRUPTS)
    add_log_interrupts(103);
#endif



//    i_sync_pin_off();
    edrk.into_pwm_interrupt = 0;

#if (_ENABLE_INTERRUPT_PWM_LED2)
i_led2_on_off(0);
#endif



#if(_ENABLE_PWM_LINES_FOR_TESTS)
  //  PWM_LINES_TK_16_OFF;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_ROTOR)
    PWM_LINES_TK_16_OFF;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_PWM)
    PWM_LINES_TK_16_OFF;
#endif


#if (_ENABLE_PWM_LED2_PROFILE)
        i_led2_on_off(0);
        if (pwm_enable_calc_main==0)
            profile_pwm[pos_profile_pwm] = 2;
#endif


}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////



#pragma CODE_SECTION(fix_pwm_freq_synchro_ain,".fast_run");
void fix_pwm_freq_synchro_ain(void)
{
    unsigned int new_freq;
    static unsigned int delta_freq = 1;
//  if (f.Sync_input_or_output == SYNC_INPUT)
    {
     sync_inc_error();

     if (sync_data.disable_sync || sync_data.timeout_sync_signal == 1 || sync_data.enable_do_sync == 0)
     {

        new_freq  = xpwm_time.pwm_tics;
        i_WriteMemory(ADR_PWM_PERIOD, new_freq);

        return;
     }

     if (sync_data.pwm_freq_plus_minus_zero==1)
     {


             //Increment xtics
             new_freq  = xpwm_time.pwm_tics + delta_freq;
             i_WriteMemory(ADR_PWM_PERIOD, new_freq); // Saw period in tics. 1 tic = 16.67 nsec

  //           change_freq_pwm(VAR_FREQ_PWM_XTICS);


     }

     if (sync_data.pwm_freq_plus_minus_zero==-1)
     {
    //4464
             //Decrement xtics
             new_freq  = xpwm_time.pwm_tics - delta_freq;
             i_WriteMemory(ADR_PWM_PERIOD, new_freq); // Saw period in tics. 1 tic = 16.67 nsec

   //          change_freq_pwm(VAR_FREQ_PWM_XTICS);

     }

     if (sync_data.pwm_freq_plus_minus_zero==0)
     {
         new_freq  = xpwm_time.pwm_tics;
         i_WriteMemory(ADR_PWM_PERIOD, new_freq);
   //      change_freq_pwm(VAR_FREQ_PWM_XTICS);
     }

    }



}

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

/*
void slow_vector_update()
{
	_iq iqKzad = 0;

	freq1 = _IQ (f.fzad/F_STATOR_MAX);//f.iqFRotorSetHz;
	iqKzad = _IQ(f.kzad);
	k1 = zad_intensiv_q(20000, 20000, k1, iqKzad);
	
}
*/

void detect_work_revers(int direction, _iq fzad, _iq frot)
{
    static int prev_revers = 0;
    int flag_revers;
    // ограничение при рекуперации
        if (direction == -1 && fzad > 0)
        {
            flag_revers = 1;
        }
        else
        if (direction == 1 && fzad < 0)
        {
            flag_revers = 1;
        }
        else
        {
            flag_revers = 0;
        }

        if (flag_revers && prev_revers==0)
            edrk.count_revers++;

        prev_revers = flag_revers;

}


void calc_power_full(void)
{
    _iq power_full_abs, power_one_abs, power_full_abs_f, power_one_abs_f;

    //
    power_one_abs  = _IQabs(filter.PowerScalar);
    power_one_abs_f  = _IQabs(filter.PowerScalarFilter2);
    power_full_abs = power_one_abs  + _IQabs(edrk.iq_power_kw_another_bs);
    power_full_abs_f = power_one_abs_f  + _IQabs(edrk.iq_power_kw_another_bs);

    if (edrk.oborots>=0)
    {
        edrk.iq_power_kw_full_znak = power_full_abs;
        edrk.iq_power_kw_one_znak  = power_one_abs;
        edrk.iq_power_kw_full_filter_znak = power_full_abs_f;
        edrk.iq_power_kw_one_filter_znak  = power_one_abs_f;
    }
    else
    {
        edrk.iq_power_kw_full_znak = -power_full_abs;
        edrk.iq_power_kw_one_znak  = -power_one_abs;
        edrk.iq_power_kw_full_filter_znak = -power_full_abs_f;
        edrk.iq_power_kw_one_filter_znak  = -power_one_abs_f;
    }

    edrk.iq_power_kw_full_abs = power_full_abs;
    edrk.iq_power_kw_one_abs  = power_one_abs;
    edrk.iq_power_kw_full_filter_abs = power_full_abs_f;
    edrk.iq_power_kw_one_filter_abs  = power_one_abs_f;

}
