#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"

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


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

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

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

/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
#define ENABLE_LOG_INTERRUPTS   0 //1

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

}


#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 a = WINDING_DEFAULT;

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

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

int i = 0;
/*void InitPWM()
{
		i_WriteMemory(ADR_PWM_MODE_0, 0x0000); //Выбираем в качестве источника ШИМ TMS
}*/

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


#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};
///////////////////////////////////////////////////////////////////
#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();


    inc_RS_timeout_cicle();
    inc_CAN_timeout_cicle();

//    global_time.calc(&global_time);

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

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

unsigned int sum_count_err_read_opt_bus=0;

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


    static unsigned int prev_error_read = 0, count_read_optical_bus_error = 0;
    static unsigned int flag_disable_resend = 0;
    static unsigned int count_resend = 0, cc=0;
//    static STATUS_DATA_READ_OPT_BUS buf_status[10];
    static STATUS_DATA_READ_OPT_BUS optbus_status;
    static unsigned int  tt=0, t1 = 6; //t1 = 10    //, t2 = 3, t3 = 30;
    static unsigned int  cmd_wdog_sbus = 0, count_wait_wdog_sbus = 0, wdog_sbus = 0;

    if (flag_special_mode_rs==1)
      return;

    if (edrk.KvitirProcess)
      return;

    if (edrk.disable_interrupt_timer2)
        return;

#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_17_ON;
#endif

//i_led2_on_off(1);


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


//    pause_1000(100);
    if (optical_read_data.flag_clear)
    {
  //    stage_1 = 0;
      optical_read_data.timer = 0;
      optical_read_data.flag_clear = 0;
      optical_read_data.error_wdog = 0;
//      count_wait_wdog_sbus = 0;


//      if (optical_read_data.data_was_update_between_pwm_int==0)
//          sum_count_err_read_opt_bus++;
//
//      optical_read_data.data_was_update_between_pwm_int = 0;

  //    optical_read_data.data_was_update_between_pwm_int = 0;
      cc = 0;
    }

//    else
    optical_read_data.timer++;

//    if (edrk.into_pwm_interrupt==1)
//    {
//        if (optical_read_data.timer>=2)
//        {
//          optical_read_data.timer--;
//          optical_read_data.timer--;
//        }
//        flag_disable_resend = 0;
//        count_resend = 0;
//
//    }

//
//
//
//      if (stage_1==0)
//          tt = t1;
//
//      if (stage_1==1)
//          tt = t2;

    if (edrk.ms.another_bs_maybe_on==1 && edrk.flag_second_PCH==0 /*edrk.auto_master_slave.local.bits.master*/ )
    {

        if (optical_read_data.data.cmd.bit.wdog_tick)
        {
  //          i_led1_on();
#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_21_ON;
#endif
        }
        else
        {
    //        i_led1_off();
#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_21_OFF;
#endif

        }

        optical_write_data.data.cmd.bit.wdog_tick =  optical_read_data.data.cmd.bit.wdog_tick;

        if (optical_write_data.data.cmd.bit.wdog_tick)
        {
    //        i_led2_on();
#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_22_ON;
#endif

        }
        else
        {
     //       i_led2_off();
#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_22_OFF;
#endif
        }



    }


    if (edrk.ms.another_bs_maybe_on==1 && edrk.flag_second_PCH==1 /*edrk.auto_master_slave.local.bits.slave*/ )
    {

        if (optical_write_data.data.cmd.bit.wdog_tick)
        {
    //        i_led2_on();
#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_22_ON;
#endif

        }
        else
        {
     //       i_led2_off();
#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_22_OFF;
#endif
        }



        if (optical_read_data.data.cmd.bit.wdog_tick)
        {
   //         i_led1_on();
#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_21_ON;
#endif
        }
        else
        {
     //       i_led1_off();
#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_21_OFF;
#endif
        }




        // пишем
        optical_write_data.data.cmd.bit.wdog_tick = wdog_sbus;
        if (cmd_wdog_sbus==0)
        {
//            optical_write_data.data.cmd.bit.wdog_tick = wdog_sbus;
            count_wait_wdog_sbus = 0;
            cmd_wdog_sbus++;
        }
        else
        // ждем подтверждения
        if (cmd_wdog_sbus==1)
        {
          if (optical_read_data.data.cmd.bit.wdog_tick == wdog_sbus) //&& prev_error_read==0
          {
 //               result_code_wdog_sbus = 1;
              optical_read_data.count_error_wdog = count_wait_wdog_sbus;
                count_wait_wdog_sbus = 0;
                wdog_sbus = !wdog_sbus;
                cmd_wdog_sbus = 0;
          }
          else
          {
              if (count_wait_wdog_sbus<(8*t1) )  //6
              {
                count_wait_wdog_sbus++;
              }
              else
              {
                  if (optical_read_data.error_wdog==0)
                  {
                      // не было ошибок и вдруг есть!

//                      i_led2_toggle();
//                      pause_1000(10);
//                      i_led2_toggle();
//                      pause_1000(10);
                  }
     //             if (optical_read_data.data.cmd.bit.alarm==0) // пока так!
                  optical_read_data.error_wdog = 1;  // даем ошибку

              }


          }
        }


    }

#if(_ENABLE_PWM_LINES_FOR_TESTS)

//    if (count_wait_wdog_sbus==0)
//    {
//        PWM_LINES_TK_16_ON;
//    }
//    else
//    {
//        PWM_LINES_TK_16_OFF;
//    }


#endif


#if(_ENABLE_PWM_LINES_FOR_TESTS)
    if (optical_read_data.error_wdog)
    {
        PWM_LINES_TK_23_ON;
        PWM_LINES_TK_23_ON;
    }
    else
    {
        PWM_LINES_TK_23_OFF;
    }
#endif



    if  (optical_read_data.timer>=t1 || prev_error_read==1)
    {

#if(_ENABLE_PWM_LINES_FOR_TESTS)
        PWM_LINES_TK_18_OFF;
        PWM_LINES_TK_16_OFF;
#endif
//        i_led2_on_off(1);
//        i_led2_on_off(0);
//        i_led2_on_off(1);

#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_19_ON;

#endif
        project.cds_tk[3].read_pbus(&project.cds_tk[3]); //optical_bus_read();


//            i_led2_on_off(0);
//            i_led2_on_off(1);

            optbus_status = optical_bus_get_status_and_read();

//        i_led2_on_off(0);

#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_19_OFF;
#endif
            cc++;

            if (optbus_status.bit.new_data_ready)
            {

                prev_error_read = 0;

                if (optical_read_data.data_was_update_between_pwm_int<10000)
                  optical_read_data.data_was_update_between_pwm_int += 1;

                count_read_optical_bus_error = 0;
            }

            if (optbus_status.bit.receiver_error || optbus_status.bit.bad_status12
                                             )
            {

                prev_error_read = 1;

                if (count_read_optical_bus_error<=t1)
                  count_read_optical_bus_error++;
                else
                {
                            optical_read_data.data.pzad_or_wzad = 0;
                            optical_read_data.data.angle_pwm = 0;
                            optical_read_data.data.iq_zad_i_zad = 0;
//                            optical_read_data.data.cmd.all = 0x40; // временно! alarm = 1
                            optical_read_data.data.cmd.all = 0;
                }
            }


#if(_ENABLE_PWM_LINES_FOR_TESTS)
    if (optbus_status.bit.new_data_ready)
    {
        PWM_LINES_TK_18_ON;
    }
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS)
    if (optbus_status.bit.receiver_busy || optbus_status.bit.receiver_error || optbus_status.bit.bad_status12)
    {
        PWM_LINES_TK_16_ON;
    }
#endif

    }





        if  (optical_read_data.timer>=t1)
        {
//i_led2_on_off(1);
//i_led2_on_off(0);
//i_led2_on_off(1);
//i_led2_on_off(0);
//i_led2_on_off(1);
#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_20_ON;
#endif
            optical_bus_write();
                /////////////////
//i_led2_on_off(0);
#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_20_OFF;
#endif

                optical_read_data.timer = 0;

        }

//         if (prev_error_read==0)
//             i_led2_off();


//        if  (optical_read_data.timer==t2)
//        {
//
// //           if (edrk.flag_second_PCH==0)
//               stage_2 = 1;
//  //          else
//   //            stage_1 = 1;
//
//            optical_read_data.timer = 0;
//        }

//        if  (optical_read_data.timer>=t3)
//        {
//            optical_read_data.timer = 0;
//        }





//
//      if  (stage_1==2 && prev_stage1!=stage_1)
//      {
// //         i_led2_on();
////          if (flag_disable_resend==0)
////          {
//  //            if (edrk.ms.another_bs_maybe_on==1 && (edrk.auto_master_slave.local.bits.master )  )
//
// //          if (edrk.flag_second_PCH==0)
//           {
//               i_led2_on();
//               i_led2_off();
//               i_led2_on();
//
//               optical_bus_write();
//           }
////           else
////           {
////               i_led2_on();
////
////           optical_bus_read();
////           optbus_status = optical_bus_get_status_and_read();
////           buf_status[cc] = optbus_status;
////           cc++;
////
////           if (optbus_status.bit.new_data_ready)
////               optical_read_data.data_was_update_between_pwm_int = 1;
////
////                     if (optbus_status.bit.receiver_busy || optbus_status.bit.receiver_error || optbus_status.bit.bad_status12
////                                                      )
////                     {
////                         i_led1_on();
////                                        i_led1_off();
////
////                     }
////
////           }
//           stage_1 = 0;
//      }

//      if  (stage_1==1 && prev_stage1!=stage_1)
//      {
//
////          if (edrk.flag_second_PCH==1)
////          {
////              i_led2_on();
////              i_led2_off();
////              i_led2_on();
////
////              optical_bus_write();
////          }
////          else
// //         {
//              i_led2_on();
//
//          optical_bus_read();
//          optbus_status = optical_bus_get_status_and_read();
//          buf_status[cc] = optbus_status;
//          cc++;
//
//          if (optbus_status.bit.new_data_ready)
//              optical_read_data.data_was_update_between_pwm_int = 1;
//
//          if (optbus_status.bit.receiver_busy || optbus_status.bit.receiver_error || optbus_status.bit.bad_status12
//                                           )
//          {
//              i_led1_on();
//                             i_led1_off();
//
//          }
//
//      //    }
//
//
//  //        stage_1 = 0;
//      }

  //    prev_stage1 = stage_1;
 //   }
//        if (edrk.flag_second_PCH==1)
//        {
//          i_led2_off();
//        }

//i_led2_on_off(0);

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

#if(_ENABLE_PWM_LINES_FOR_TESTS)
    PWM_LINES_TK_17_OFF;
#endif


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

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_MASTER_SLAVE             4500 // 5 sec

///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//#define _ENABLE_LOG_TICS_PWM    1
#define _ENABLE_SLOW_PWM    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;


#pragma DATA_SECTION(time_buf,".slow_vars");
#define MAX_COUNT_TIME_BUF  50
unsigned 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(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;
	static int count_step=0;
	static int count_step_ram_off = 0;
	static int count_start_impuls = 0;
	static int flag_record_log = 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 = 0;//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;




	unsigned long time_delta = 0;

	static unsigned int count_step_run = 0, 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;


//	OPTICAL_BUS_CODE_STATUS optbus_status = {0};
	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_LINES_TK_16_ON;
#endif



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

   if (edrk.disable_interrupt_pwm)
   {
//       i_led1_on_off(0);
       return;
   }

   if (flag_special_mode_rs==1)
   {
     calc_norm_ADC(0);
//     inc_RS_timeout_cicle();
//     inc_CAN_timeout_cicle();

//i_led2_on_off(0);

     return;
   }


////////////////
   err_interr = detect_level_interrupt();
   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)
   {
      i_sync_pin_on();
//      i_led1_on_off(1);
   }

/////////////////
#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);


   calc_norm_ADC(0); // читаем АЦП

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

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

   //////////////////////////////
//   inc_RS_timeout_cicle();
   ////////////////////////////////
   ////////////////////////////////////////////
//   i_led1_off();
//   set_tics_timer_pwm(3,count_timer_buf);
//   get_tics_timer_pwm(1);

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

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

   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;


//i_led2_on_off(0);//2
//i_led2_on_off(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 (edrk.flag_second_PCH)
        {
            fix_pwm_freq_synchro_ain();
        }

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

       if (en_rotor)
          update_rot_sensors();

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


       if (en_rotor)
       {
          RotorMeasure();
          set_tics_timer_pwm(7,count_timer_buf);
          get_tics_timer_pwm(pwm_enable_calc_main_log);
          RotorMeasurePBus();
          set_tics_timer_pwm(8,count_timer_buf);
          get_tics_timer_pwm(pwm_enable_calc_main_log);
       }
    }
    else
        pwm_enable_calc_main = 0;


//    calc_norm_ADC();
    set_tics_timer_pwm(9,count_timer_buf);
    get_tics_timer_pwm(pwm_enable_calc_main_log);
 //   calc_pll_50hz();

//i_led2_on_off(0);//1
//i_led2_on_off(1);


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

#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


//i_led2_on_off(0);//2
//i_led2_on_off(1);

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

//	i_led1_on_off(1);

	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;

//i_led2_on_off(0);//3
//i_led2_on_off(1);


		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)// заходим в расчет только раз за период шима
	  {

        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);

//i_led2_on_off(0);//4
//i_led2_on_off(1);

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

        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;
        }

//i_led2_on_off(0);//5
//i_led2_on_off(1);

        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;
                } else {
                    edrk.prepare_stop_PWM = 1;
                    if (edrk.k_stator1 < 41943) {  //335544 ~ 2%
                        edrk.StartGEDfromZadanie = 0;
                    }
                }
            } else {
                if (get_start_ged_from_zadanie()) {
                    edrk.StartGEDfromZadanie = 1;
                } else {
                    if (edrk.k_stator1 < 41943) {  //335544 ~ 2%
                        edrk.StartGEDfromZadanie = 0;
                    }
                }
                edrk.prepare_stop_PWM = optical_read_data.data.cmd.bit.prepare_stop_PWM;
            }
        } else {
            edrk.StartGEDfromZadanie = get_start_ged_from_zadanie();
        }

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

//i_led2_on_off(0);//6
//i_led2_on_off(1);


        // мы крутим и есть запрос на подключение расцепителя?
        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;

//i_led2_on_off(0);//7
//i_led2_on_off(1);

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


        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);  // тут все по штатному


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

//        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);  // тут все по штатному


//i_led2_on_off(0);//8
//i_led2_on_off(1);

        set_tics_timer_pwm(14,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 == 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
                    );
        }
        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 (_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

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


        //////////////////////////////////
        //////////////////////////////////
//i_led2_on_off(0);//9
//i_led2_on_off(1);

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

		if(edrk.Go == 1)
		{
			if (edrk.Go != prevGo)
			{
//				clear_mem(FAST_LOG);
//				count_start_impuls = 0;
				count_step = 0;
				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;

//               count_start_preobr++;

                clear_logpar();

//				uzad_down_koeff = _IQ(1);
//				rotor_error_counter = 0;

//                if (f.Mode == 0)
//                {
//                    vector_moment_f(WRotor.iqWRotorCalc, 0, 0, 0, 0, 0, &Fzad,
//                                    &Uzad1, &Uzad2, WRotor.RotorDirection,
  //                                  f.iqFRotorSetHz);
  //              }



			}
			else
			{

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

				    flag_record_log = 1;
	                enable_calc_vector = 1;

				}

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

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

//	        pwm_vector_model_titov(f.iq_p_zad, f.iq_fzad, rotor.direct_rotor,
	//                rotor.iqFout, 0);

	        // ручной разряд

	        if (edrk.ManualDischarge && prev_ManualDischarge!=edrk.ManualDischarge)
	            edrk.Discharge = 1;

	        prev_ManualDischarge =edrk.ManualDischarge;

            if (count_start_impuls == 0) {
                if (edrk.Discharge || (edrk.ManualDischarge )   ) {
                    break_resistor_managment_calc();
                    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 (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,
                                         WRotorPBus.RotorDirection1, WRotor.iqWRotorCalcBeforeRegul1,
                                         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 (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,
                                             WRotorPBus.RotorDirection1, WRotor.iqWRotorCalcBeforeRegul1,
                                             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 (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 (count_start_impuls > 0) {
	                    count_start_impuls -= 1;
	                } else {
	                    count_start_impuls = 0;
	                }
			enable_calc_vector = 0;

//			k1 = 0; //Edited Aleksey
//			k2 = 0;

			Uzad1 = 0;
			Uzad2 = 0;

		}  // end if Go==1


	  }  // end pwm_enable_calc_main one interrupt one period only


//i_led2_on_off(0);//10
//i_led2_on_off(1);


/*
 *
            //                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 (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,
                                     WRotorPBus.RotorDirection1, WRotor.iqWRotorCalcBeforeRegul1,
                                     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 (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();
             }
        } // end if (count_start_impuls==5)


        if (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 (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,
                                     WRotorPBus.RotorDirection1, WRotor.iqWRotorCalcBeforeRegul1,
                                     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.iqWRotorCalcBeforeRegul1, WRotor.iqWRotorCalcBeforeRegul1,
                                              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,
                                              0,0,
                                              &Fzad, &Uzad1, &Uzad2, &Izad_out);
            }

        }

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

	           break_resistor_recup_calc(edrk.zadanie.iq_ZadanieU_Charge);

	           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)
	        {

	            uf_const(&Fzad,&Uzad1,&Uzad2);

	            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;



	//            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)
	        {
	            simple_scalar(1,0,
	                          WRotor.iqWRotorCalcBeforeRegul1,   WRotor.iqWRotorCalcBeforeRegul1, edrk.zadanie.iq_oborots_zad_hz_rmp,
	                          edrk.temper_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, (filter.PowerScalar+edrk.iq_power_kw_another_bs),
	                          edrk.master_Izad, edrk.MasterSlave,
	                          &Fzad, &Uzad1, &Uzad2, &Izad_out);

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



                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,
                                          Uzad1, //edrk.master_Uzad,
                                          edrk.MasterSlave,
                                          edrk.flag_second_PCH,
                                          &edrk.Kplus, &edrk.tetta_to_slave, &edrk.Uzad_to_slave);

                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;
	            }

	            vectorControlConstId(edrk.zadanie.iq_power_zad_rmp, edrk.zadanie.iq_oborots_zad_hz_rmp,
	                                 WRotorPBus.RotorDirection1, WRotor.iqWRotorCalcBeforeRegul1,
	                                 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);
	            analog.PowerFOC = edrk.P_to_master;
	            Fzad = vect_control.iqFstator;
	            Izad_out = edrk.Iq_to_slave;
	        } // end ALG_MODE_FOC_OBOROTS


	       } // end pwm_enable_calc_main

	    }  // end (count_start_impuls == COUNT_START_IMP && edrk.Go==1)
	    else
	    {
	        run_calc_uf = 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);
        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();
        }

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

//		write_swgen_pwm_times(PWM_MODE_RELOAD_FORCE);

//	    if (xpwm_time.one_or_two_interrupts_run == PWM_ONE_INTERRUPT_RUN || count_start_impuls<COUNT_START_IMP)
//	        write_swgen_pwm_times(PWM_MODE_RELOAD_FORCE);
//	    else
//	    {
//	      if (count_start_impuls == COUNT_START_IMP)
//	      {
//	          if ((run_calc_uf==1) && (prev_run_calc_uf==0))
//	          {
//	           if (xpwm_time.where_interrupt == PWM_LOW_LEVEL_INTERRUPT)
//	             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);
//	      }
//	      else
//	          write_swgen_pwm_times(PWM_MODE_RELOAD_FORCE);
//	    }
//	    prev_run_calc_uf = run_calc_uf;


	//	break_resistor_managment_calc();
	//	break_resistor_recup_calc();
	//	break_resistor_managment_update();


			
//    a.iqk1 = Uzad1;//svgen_pwm24_1.Gain;	//For output Kmodul to terminal
//	a.iqk2 = Uzad2;//svgen_pwm24_2.Gain;	//end counting Uout
//	a.iqk = (a.iqk1 + a.iqk2) / 2;
	//a.iqf = Fzad;

    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

  edrk.iq_f_rotor_hz = WRotor.iqWRotorCalcBeforeRegul1;

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

 //   iq_U_1_prev = filter.iqU_1_long;
//   iq_U_2_prev = filter.iqU_2_long;

	  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 (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 (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;



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

//
//	  if (xpwm_time.one_or_two_interrupts_run == PWM_ONE_INTERRUPT_RUN || count_start_impuls<COUNT_START_IMP)
//	            write_swgen_pwm_times(PWM_MODE_RELOAD_FORCE);
//	        else
//	        {
//	          if (count_start_impuls == COUNT_START_IMP)
//	          {
//	              if ((run_calc_uf==1) && (prev_run_calc_uf==0))
//	              {
//	               if (xpwm_time.where_interrupt == PWM_LOW_LEVEL_INTERRUPT)
//	                 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);
//	          }
//	          else
//	              write_swgen_pwm_times(PWM_MODE_RELOAD_FORCE);
//	        }
//	        prev_run_calc_uf = run_calc_uf;
//



//    break_resistor_managment_calc();
//    break_resistor_recup_calc();
//    break_resistor_managment_update();
//    RotorMeasure();


    if (enable_calc_vector == 1)
    {
/*
        k_decr_izad = _IQmpy(
                f.iq_decr_mzz_power,
                _IQmpy(f.iq_decr_mzz_moment, f.iq_decr_mzz_temper));

        iqIm1 = analog.iqIm_1;
        iqIm2 = analog.iqIm_2;

//		i_led1_on_off(0);
        //vector_moment_f(WRotor.iqWRotorCalc, f.iqFRotorSetHz, _IQmpy(f.iqCurrentSet, k_decr_izad), f.iq_bpsi_zad,
        vector_moment_f(WRotor.iqWRotorCalc,
                        _IQmpy(f.iqFRotorSetHz, k_decr_izad), f.iqCurrentSet,
                        f.iq_bpsi_zad, iqIm1, iqIm2, &Fzad, &Uzad1, &Uzad2,
                        WRotor.RotorDirection, 0);
*/

    }

/*
    if (count_start_impuls >= (2 * COUNT_START_IMP) ) {

        uf_const_f_24(Fzad, Fzad, Uzad1, Uzad2,  f.Revers,  edrk.disable_alg_u_disbalance,  edrk.kplus_u_disbalance,  edrk.k_u_disbalance, filter.iqU_1_fast, filter.iqU_1_fast);

    } else {
//      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);
    }
*/



/*
    if (flag_record_log)
    {
        //	i_led1_on_off(0);
 //       test_calc_pwm24(Uzad1, Uzad2, Fzad);
//        uf_const_f( Fzad, Fzad, Uzad1, Uzad2, f.Revers ); // space vector pwm  sandart algoritm
        uf_const_f_24(Fzad, Fzad, Uzad1, Uzad2,  f.Revers,  edrk.disable_alg_u_disbalance,  edrk.kplus_u_disbalance,  edrk.k_u_disbalance, filter.iqU_1_fast, filter.iqU_1_fast);


        //	i_led1_on_off(1);

			if (go_a == 0) {
				svgen_set_time_keys_closed(&svgen_pwm24_1);
			}
			if (go_b == 0) {
				svgen_set_time_keys_closed(&svgen_pwm24_2);
			}


    } else {
        svgen_set_time_keys_closed(&svgen_pwm24_1);
        svgen_set_time_keys_closed(&svgen_pwm24_2);
    }
*/



    // test write oscil buf

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

                if (edrk.Go)
                    oscil_can.status_pwm = 1;
                else
                    oscil_can.status_pwm = 0;


                if ( (edrk.Stop == 0) && (project.controller.read.errors.all==0) )
                    oscil_can.status_error = 0;
                else
                    oscil_can.status_error = 1;

                oscil_can.oscil_buffer[0][oscil_can.current_position] = global_time.pwm_tics;
//                if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_OBOROTS || edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_POWER) {
                    oscil_can.oscil_buffer[1][oscil_can.current_position] = (int16) _IQtoIQ15(filter.iqU_1_long);//xpwm_time.Ta0_0;    //(int16) _IQtoIQ15(turns.pidFvect.Ui);
                    oscil_can.oscil_buffer[2][oscil_can.current_position] = (int16) _IQtoIQ15(filter.iqU_2_long);//xpwm_time.Ta0_1;    //(int16) _IQtoIQ15(turns.pidFvect.Up);
                    oscil_can.oscil_buffer[3][oscil_can.current_position] = (int16) _IQtoIQ15(turns.pidFvect.Out);
                    oscil_can.oscil_buffer[4][oscil_can.current_position] = (int16) _IQtoIQ15(turns.pidFvect.OutMax);
                    oscil_can.oscil_buffer[5][oscil_can.current_position] = (int16) _IQtoIQ15(power.pidP.Out);
                    oscil_can.oscil_buffer[6][oscil_can.current_position] = (int16) _IQtoIQ15(power.pidP.OutMax);
//                } else {
//                    oscil_can.oscil_buffer[1][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.pidF.Ui);  // count_updated_sbus;//xpwm_time.Ta0_0;
//                    oscil_can.oscil_buffer[2][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.pidF.Up);
//                    oscil_can.oscil_buffer[3][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.pidF.Out);//xpwm_time.Tb0_0;
//                    oscil_can.oscil_buffer[4][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.pidF.OutMax);//xpwm_time.Tb0_1;
//                    oscil_can.oscil_buffer[5][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.pidPower.Out);//xpwm_time.Tc0_0;
//                    oscil_can.oscil_buffer[6][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.pidPower.OutMax); //xpwm_time.Tc0_1;
//                }


                oscil_can.oscil_buffer[7][oscil_can.current_position] = (int16) _IQtoIQ15(edrk.master_Uzad) ;
                oscil_can.oscil_buffer[8][oscil_can.current_position] = (int16) _IQtoIQ12(edrk.master_theta);//global_time.microseconds;

                oscil_can.oscil_buffer[9][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqIu_1);
                oscil_can.oscil_buffer[10][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqIv_1);
                oscil_can.oscil_buffer[11][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqIw_1);

                oscil_can.oscil_buffer[12][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqIu_2);
                oscil_can.oscil_buffer[13][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqIv_2);
                oscil_can.oscil_buffer[14][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqIw_2);

                oscil_can.oscil_buffer[15][oscil_can.current_position] = (int16) _IQtoIQ15(turns.Fzad_rmp);//(int16) _IQtoIQ15(analog.iqU_1);
                oscil_can.oscil_buffer[16][oscil_can.current_position] = (int16) _IQtoIQ15(WRotor.iqWRotorCalcBeforeRegul1);//(int16) _IQtoIQ15(analog.iqU_2);

//                oscil_can.oscil_buffer[17][oscil_can.current_position] = 0;

                oscil_can.oscil_buffer[18][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqIin_2);
                oscil_can.oscil_buffer[19][oscil_can.current_position] = (int16) _IQtoIQ15(vect_control.iqUdCompensation);
                oscil_can.oscil_buffer[20][oscil_can.current_position] = (int16) _IQtoIQ15(vect_control.iqUqCompensation);

                oscil_can.oscil_buffer[21][oscil_can.current_position] = (int16) _IQtoIQ15(edrk.f_stator);
                oscil_can.oscil_buffer[22][oscil_can.current_position] = (int16) _IQtoIQ12(edrk.k_stator1);

                if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_OBOROTS || edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_POWER) {
                    oscil_can.oscil_buffer[17][oscil_can.current_position] = (int16) _IQtoIQ15(vect_control.iqPvsi1 + vect_control.iqPvsi2);
                    oscil_can.oscil_buffer[23][oscil_can.current_position] = (int16) _IQtoIQ15(vect_control.iqId1);//(int16) _IQtoIQ15(WRotorPBus.iqAngle1F);
                    oscil_can.oscil_buffer[24][oscil_can.current_position] = (int16) _IQtoIQ15(vect_control.iqIq1);//(int16) _IQtoIQ15(WRotorPBus.iqAngle2F);
                    oscil_can.oscil_buffer[25][oscil_can.current_position] = (int16) _IQtoIQ15(vect_control.iqFsl);
                    oscil_can.oscil_buffer[26][oscil_can.current_position] = (int16) _IQtoIQ15(turns.mzz_zad_int);
                    oscil_can.oscil_buffer[27][oscil_can.current_position] = (int16) _IQtoIQ15(vect_control.pidD1.Out);//(int16) _IQtoIQ15(WRotorPBus.iqWRotorCalcBeforeRegul1);
                    oscil_can.oscil_buffer[28][oscil_can.current_position] = (int16) _IQtoIQ15(vect_control.pidQ1.Out);
                    oscil_can.oscil_buffer[29][oscil_can.current_position] = (int16) _IQtoIQ15(vect_control.pidD1.Ref);
                } else {
                    oscil_can.oscil_buffer[17][oscil_can.current_position] = (int16) _IQtoIQ15(analog.PowerScalar);
                    oscil_can.oscil_buffer[23][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.pidIm1.Ui);  // count_updated_sbus;//xpwm_time.Ta0_0;
                    oscil_can.oscil_buffer[24][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.pidIm1.Up);
                    oscil_can.oscil_buffer[25][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.pidIm1.Out);
                    oscil_can.oscil_buffer[26][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.mzz_zad_int);//(int16) _IQtoIQ15(WRotor.iqWRotorCalcBeforeRegul1);
                    oscil_can.oscil_buffer[27][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.Im_regul);//(int16) _IQtoIQ15(WRotorPBus.iqWRotorCalcBeforeRegul1);
                    oscil_can.oscil_buffer[28][oscil_can.current_position] = (int16) _IQtoIQ15(edrk.Kplus);
                    oscil_can.oscil_buffer[29][oscil_can.current_position] = (int16) _IQtoIQ15(filter.iqIm);
                }


//                oscil_can.oscil_buffer[23][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.Izad);//(int16) _IQtoIQ15(WRotorPBus.iqAngle1F);
//                oscil_can.oscil_buffer[24][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.Izad_from_master);//(int16) _IQtoIQ15(WRotorPBus.iqAngle2F);
//                oscil_can.oscil_buffer[25][oscil_can.current_position] = (int16) _IQtoIQ15(simple_scalar1.mzz_zad);//(int16) _IQtoIQ15(WRotor.iqWRotorImpulses1);



                oscil_can.oscil_buffer[30][oscil_can.current_position] = (int16) _IQtoIQ12(edrk.master_theta);//_IQtoIQ15(edrk.Uzad_to_slave);
                oscil_can.oscil_buffer[31][oscil_can.current_position] = (int16) _IQtoIQ12(edrk.tetta_to_slave);


//                oscil_can.oscil_buffer[26][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqUin_m1);
//                oscil_can.oscil_buffer[27][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqUin_m2);
//
//                oscil_can.oscil_buffer[28][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqUin_A1B1);
//                oscil_can.oscil_buffer[29][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqUin_B1C1);
//                oscil_can.oscil_buffer[30][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqUin_A2B2);
//                oscil_can.oscil_buffer[31][oscil_can.current_position] = (int16) _IQtoIQ15(analog.iqUin_B2C2);


                oscil_can.set_next_position(&oscil_can);
            }

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


            //


        //    if ((m.m2.bit.LatchCrashError == 0) && (f.Startstoplog == 0))// && (edrk.Go == 1))
            if ( (f.Startstoplog == 0) && flag_record_log)// && (edrk.Go == 1))
            {
                test_mem_limit(FAST_LOG, !f.Ciclelog);

                count_step++;

                if (count_step >= 0)
                {
                    count_step_run++;
                    //	i_led1_on_off(1);
                    write_to_mem(FAST_LOG, (int16)count_step_run);

                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqIu_1));
                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqIv_1));
                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqIw_1));

                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqIu_2));
                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqIv_2));
                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqIw_2));

                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqUin_A1B1));
                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqUin_A2B2));


                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqU_1));
                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqU_2));//10

                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqIin_1));
                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqIin_2));

                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqIm_1));
                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(analog.iqIm_2));

                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(filter.iqU_1_long));
                    write_to_mem(FAST_LOG, (int16) _IQtoIQ15(filter.iqU_2_long));


                    write_to_mem(FAST_LOG,(int16)svgen_pwm24_1.Ta_0);
                    write_to_mem(FAST_LOG,(int16)svgen_pwm24_1.Ta_1);
                    write_to_mem(FAST_LOG,(int16)svgen_pwm24_1.Tb_0);
                    write_to_mem(FAST_LOG,(int16)svgen_pwm24_1.Tb_1);
                    write_to_mem(FAST_LOG,(int16)svgen_pwm24_1.Tc_0);
                    write_to_mem(FAST_LOG,(int16)svgen_pwm24_1.Tc_1); //22

                    write_to_mem(FAST_LOG, (int16) logpar.log1);
                    write_to_mem(FAST_LOG, (int16) logpar.log2);
                    write_to_mem(FAST_LOG, (int16) logpar.log3);
                    write_to_mem(FAST_LOG, (int16) logpar.log4);
                    write_to_mem(FAST_LOG, (int16) logpar.log5);
                    write_to_mem(FAST_LOG, (int16) logpar.log6);
                    write_to_mem(FAST_LOG, (int16) logpar.log7);
                    write_to_mem(FAST_LOG, (int16) logpar.log8);
                    write_to_mem(FAST_LOG, (int16) logpar.log9);

                    write_to_mem(FAST_LOG, (int16) logpar.log10);
                    write_to_mem(FAST_LOG, (int16) logpar.log11);
                    write_to_mem(FAST_LOG, (int16) logpar.log12);
                    write_to_mem(FAST_LOG, (int16) logpar.log13);

                    write_to_mem(FAST_LOG, (int16) project.cds_in[0].read.pbus.ready_in.all);
                    write_to_mem(FAST_LOG, (int16) project.cds_in[1].read.pbus.ready_in.all);

                    if (logpar.start_write_fast_log) {
                        get_log_params_count();
                        logpar.start_write_fast_log = 0;
                    }
                    count_step = 0;
                }
            }
            set_tics_timer_pwm(23,count_timer_buf);
            get_tics_timer_pwm(pwm_enable_calc_main_log);

    }



    //    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);
    //    i_led2_off();
    //    i_led2_on();
    //
    //    out_I_over_1_6.calc(&out_I_over_1_6);
    //    i_led2_off();


    pwm_run = 0;

		
	} // end if pwm_run==1


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


	 //   pwm_analog_ext_interrupt();

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


	}

	 pwm_analog_ext_interrupt();

//    i_led1_off();

//	optical_bus_write();

 //   pause_1000(50);

 //   i_led2_off();
  //  i_led1_off();




    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=count_timer_buf;i<MAX_COUNT_TIME_BUF;i++)
	{
	    time_buf[i] = 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


}


#pragma CODE_SECTION(fix_pwm_freq_synchro_ain,".fast_run");
void fix_pwm_freq_synchro_ain(void)
{
    unsigned int new_freq;
//  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 + 1;
             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 - 1;
             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);
	
}
*/



