#include <281xEvTimersInit.h>
#include <adc_tools.h>
#include <alg_simple_scalar.h>
#include <break_regul.h>
#include <calc_rms_vals.h>
#include <calc_tempers.h>
#include <can_bs2bs.h>
#include <detect_errors.h>
#include <detect_errors_adc.h>
#include <detect_overload.h>
#include <detect_overload.h>
#include <edrk_main.h>
#include <log_to_mem.h>
#include <math.h> 
#include <message_modbus.h>
#include <modbus_hmi.h>
#include <modbus_hmi_update.h>
#include <modbus_svu_update.h>
#include <optical_bus.h>
#include <overheat_limit.h>
#include <params.h>
#include <params_alg.h>
#include <params_norma.h>
#include <params_pwm24.h>
#include <params_temper_p.h>
#include <project.h>
#include <pump_control.h>
#include <PWMTMSHandle.h>
#include <PWMTools.h>
#include <sync_tools.h>
#include <v_rotor.h>
#include <vector.h>
#include "edrk_main.h"
#include "mathlib.h"

//#include "modbus_fill_table.h"

#include "big_dsp_module.h"
#include "control_station.h"
#include "CAN_Setup.h"
#include "global_time.h"
#include "global_time.h"
#include "IQmathLib.h"
#include "mathlib.h"
#include "mathlib.h"
#include "modbus_table_v2.h"
#include "oscil_can.h"
#include "DSP281x_Examples.h"   // DSP281x Examples Include File
#include "DSP281x_SWPrioritizedIsrLevels.h"   // DSP281x Examples Include File
#include "DSP281x_Device.h"
#include "alg_pll.h"
#include "vector_control.h"
#include "CRC_Functions.h"
#include "RS_Functions.h"
#include "xp_project.h"
#include "sbor_shema.h"
#include "alarm_log_can.h"
#include "pwm_test_lines.h"

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


#pragma DATA_SECTION(Unites2VPU, ".slow_vars")
int Unites2VPU[127]={0};

#pragma DATA_SECTION(Unites2Zadat4ik, ".slow_vars")
int Unites2Zadat4ik[127]={0};

#pragma DATA_SECTION(Unites2BKSSD, ".slow_vars")
int Unites2BKSSD[127]={0};

#pragma DATA_SECTION(Unites2UMU, ".slow_vars")
int Unites2UMU[127]={0};

#pragma DATA_SECTION(f, ".slow_vars")
FLAG f = FLAG_DEFAULTS;

int cur1=0;
int cur2=0;

unsigned int old_time_edrk1 = 0, old_time_edrk2 = 0, prev_flag_special_mode_rs = 0;

#pragma DATA_SECTION(edrk, ".slow_vars")
EDRK edrk = EDRK_DEFAULT;

#pragma DATA_SECTION(pll1, ".slow_vars")
PLL_REC pll1 = PLL_REC_DEFAULT;

#define U_LEVEL_ON_BLOCK_KEY   559240  // 100V
#define U_LEVEL_OFF_BLOCK_KEY  279620   // 50V


#define TEMPER_NAGREF_ON	5
#define TEMPER_NAGREF_OFF	10

int vozb_on_off=0;


int vozb_plus=0;
int vozb_minus=0;

#define MAX_TIME_SBOR	100
#define MAX_TIME_RAZBOR	100


#define VOZB_MAX_TIMER_ON 	20
#define VOZB_MAX_TIMER_OFF 	20

#define QTV_MAX_TIMER_ON	20
#define QTV_MAX_TIMER_OFF	20


#define VOZB_ACP_IN				project.adc[0].read.pbus.adc_value[2]
#define ING_ACP_IN_CUR_OBOROT	project.adc[0].read.pbus.adc_value[0]
#define ING_ACP_IN_ZAD_VOZB		project.adc[0].read.pbus.adc_value[1]


//#define DEC_ZAD_OBOROTS	1
//#define INC_ZAD_OBOROTS	1

//#define MAX_ZAD_OBOROTS	150

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// задание оборотов от Задатчика PLUS, MINUS
// если выбран нужный режим
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
void set_oborots_from_zadat4ik(void)
{
static unsigned int old_time_edrk3 = 0, prev_PROVOROT;


  if (!(detect_pause_milisec(100,&old_time_edrk3)))
  return;

//  if (edrk.from_shema.bits.SVU) 	return;
//  if (edrk.from_shema.bits.ZADA_DISPLAY) return;
//
//
//  if (control_station.active_control_station[CONTROL_STATION_ZADATCHIK_CAN])
//  {
//
//	if (edrk.from_zadat4ik.bits.MINUS)
//	{
//		if (edrk.W_from_ZADAT4IK>0)
//		 edrk.W_from_ZADAT4IK=edrk.W_from_ZADAT4IK-DEC_ZAD_OBOROTS;
//		if (edrk.W_from_ZADAT4IK<0)
//		 edrk.W_from_ZADAT4IK=0;
//	}
//
//	if (edrk.from_zadat4ik.bits.PLUS)
//	{
//		if (edrk.W_from_ZADAT4IK<MAX_ZAD_OBOROTS)
//		 edrk.W_from_ZADAT4IK=edrk.W_from_ZADAT4IK+INC_ZAD_OBOROTS;
//		if (edrk.W_from_ZADAT4IK>=MAX_ZAD_OBOROTS)
//		 edrk.W_from_ZADAT4IK=MAX_ZAD_OBOROTS;
//	}
//
//
//	if (edrk.from_zadat4ik.bits.PROVOROT)
//	{
//		edrk.W_from_ZADAT4IK = 3;
//	}
//
//	if ((edrk.from_zadat4ik.bits.PROVOROT==0) && (prev_PROVOROT==1))
//		edrk.W_from_ZADAT4IK = 0;
//
//	prev_PROVOROT = edrk.from_zadat4ik.bits.PROVOROT;
//  }
//
//  if (control_station.active_control_station[CONTROL_STATION_VPU_CAN])
//  {
//
//    if (edrk.from_vpu.bits.MINUS)
//    {
//        if (edrk.W_from_VPU>0)
//         edrk.W_from_VPU=edrk.W_from_VPU-DEC_ZAD_OBOROTS;
//        if (edrk.W_from_VPU<0)
//         edrk.W_from_VPU=0;
//    }
//
//    if (edrk.from_vpu.bits.PLUS)
//    {
//        if (edrk.W_from_VPU<MAX_ZAD_OBOROTS)
//         edrk.W_from_VPU=edrk.W_from_VPU+INC_ZAD_OBOROTS;
//        if (edrk.W_from_VPU>=MAX_ZAD_OBOROTS)
//         edrk.W_from_VPU=MAX_ZAD_OBOROTS;
//    }
//
//
//    if (edrk.from_vpu.bits.PROVOROT)
//    {
//        edrk.W_from_VPU = 3;
//    }
//
//    if ((edrk.from_vpu.bits.PROVOROT==0) && (prev_PROVOROT==1))
//        edrk.W_from_VPU = 0;
//
//    prev_PROVOROT = edrk.from_vpu.bits.PROVOROT;
//  }

}
////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//TODO: may be move to detect_errors.c
unsigned int pause_detect_error(unsigned int *c_err, unsigned int max_wait,unsigned int flag)
{
   if (flag)
   {
		if ((*c_err)>=max_wait)
		{
		  return 1;
		}
		else
		{
			(*c_err)++;
			return 0;
		}
   }
   else
   {
      (*c_err) = 0;
	  return 0;

   }



}



void update_ukss_setup(unsigned int pause)
{
    static unsigned int old_time_ukss1=0;
    int real_mbox;


    Unites2Zadat4ik[96] = 25;
    Unites2Zadat4ik[97] = 100;
    Unites2Zadat4ik[98] = 8;

    Unites2VPU[96] = 25;
    Unites2VPU[97] = 100;
    Unites2VPU[98] = 8;

    Unites2UMU[96] = 25;
    Unites2UMU[97] = 100;
    Unites2UMU[98] = 8;

    Unites2BKSSD[96] = 25;
    Unites2BKSSD[97] = 100;
    Unites2BKSSD[98] = 8;

    if (detect_pause_milisec(pause,&old_time_ukss1))
        {
            real_mbox = get_real_out_mbox (UNITS_TYPE_BOX, ZADATCHIK_CAN);

            if (CAN_cycle_free(real_mbox))
            {
                 CAN_cycle_send( UNITS_TYPE_BOX, ZADATCHIK_CAN, 96, &Unites2Zadat4ik[96], 3, CAN_BOX_STANDART_ADR, CAN_BOX_PRIORITY_NORMAL);// примерно 40 мсек. идет отправка всей посылки
            }

            real_mbox = get_real_out_mbox (UNITS_TYPE_BOX, VPU_CAN);

            if (CAN_cycle_free(real_mbox))
            {
                 CAN_cycle_send( UNITS_TYPE_BOX, VPU_CAN, 96, &Unites2VPU[96], 3, CAN_BOX_STANDART_ADR, CAN_BOX_PRIORITY_NORMAL);// примерно 40 мсек. идет отправка всей посылки
            }

            real_mbox = get_real_out_mbox (UNITS_TYPE_BOX, UMU_CAN_DEVICE);

            if (CAN_cycle_free(real_mbox))
            {
                 CAN_cycle_send( UNITS_TYPE_BOX, UMU_CAN_DEVICE, 96, &Unites2UMU[96], 3, CAN_BOX_STANDART_ADR, CAN_BOX_PRIORITY_NORMAL);// примерно 40 мсек. идет отправка всей посылки
            }

            real_mbox = get_real_out_mbox (UNITS_TYPE_BOX, BKSSD_CAN_DEVICE);

            if (CAN_cycle_free(real_mbox))
            {
                CAN_cycle_send( UNITS_TYPE_BOX, BKSSD_CAN_DEVICE, 96, &Unites2BKSSD[96], 3, CAN_BOX_STANDART_ADR, CAN_BOX_PRIORITY_NORMAL);// примерно 40 мсек. идет отправка всей посылки
            }
        }

}

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//  обновлЯем задатчик и ВПУ
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////

void update_ukss_can(unsigned int pause)
{
    int real_mbox;
    int t1;
    static unsigned int old_time_ukss2=0;


    if (edrk.flag_second_PCH==0)
        t1 = pause;
    if (edrk.flag_second_PCH==1)
        t1 = pause;


    Unites2Zadat4ik[4] = edrk.to_zadat4ik.OBOROTS1.all;
    Unites2Zadat4ik[5] = edrk.to_zadat4ik.OBOROTS2.all;
    Unites2Zadat4ik[6] = edrk.to_zadat4ik.BIG_LAMS.all;
    Unites2Zadat4ik[7] = edrk.to_zadat4ik.APL_LAMS0.all;
    Unites2Zadat4ik[8] = 0;

    Unites2VPU[4] = edrk.to_vpu.OBOROTS1.all;
    Unites2VPU[5] = edrk.to_vpu.OBOROTS2.all;
    Unites2VPU[6] = edrk.to_vpu.BIG_LAMS.all;
    Unites2VPU[7] = 0;
    Unites2VPU[8] = 0;

	if (detect_pause_milisec(t1,&old_time_ukss2))
	{

//	  real_mbox = get_real_out_mbox(UNITS_TYPE_BOX, ZADATCHIK_CAN);
	    real_mbox = get_real_out_mbox (UNITS_TYPE_BOX, ZADATCHIK_CAN);

	    if (CAN_cycle_full_free(real_mbox,CAN_BOX_STAT_ON))
	    {
	        if (edrk.flag_second_PCH==0)
	              CAN_cycle_send( UNITS_TYPE_BOX, ZADATCHIK_CAN, 4, &Unites2Zadat4ik[4], 5, CAN_BOX_STANDART_ADR, CAN_BOX_PRIORITY_NORMAL);// примерно 40 мсек. идет отправка всей посылки
	        else
	              CAN_cycle_send( UNITS_TYPE_BOX, ZADATCHIK_CAN, 0xa, &Unites2Zadat4ik[4], 5, CAN_BOX_STANDART_ADR, CAN_BOX_PRIORITY_NORMAL);// примерно 40 мсек. идет отправка всей посылки
	    }


//
//
//	  if (CAN_FIFO_free(5))
//	  {
//	   if (edrk.flag_second_PCH==0)
//	   {
//
//           CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK_CAN, 0x4, edrk.to_zadat4ik.OBOROTS1.all);
//           CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK_CAN, 0x5, edrk.to_zadat4ik.OBOROTS2.all);
//
//           CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK_CAN, 0x6, edrk.to_zadat4ik.BIG_LAMS.all);
//           CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK_CAN, 0x7, edrk.to_zadat4ik.APL_LAMS0.all);
//           CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK_CAN, 0x8, 0);
//
//	   }
//	   else
//       {
//
//           CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK_CAN, 0xa, edrk.to_zadat4ik.OBOROTS1.all);
//           CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK_CAN, 0xb, edrk.to_zadat4ik.OBOROTS2.all);
//
//           CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK_CAN, 0xc, edrk.to_zadat4ik.BIG_LAMS.all);
//           CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK_CAN, 0xd, edrk.to_zadat4ik.APL_LAMS0.all);
//           CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK_CAN, 0xe, 0);
//
//       }
//
//	  }


//      real_mbox = get_real_out_mbox(UNITS_TYPE_BOX, VPU_CAN);

	    real_mbox = get_real_out_mbox (UNITS_TYPE_BOX, VPU_CAN);

	    if (CAN_cycle_full_free(real_mbox,CAN_BOX_STAT_ON))
	    {
	        if (edrk.flag_second_PCH==0)
	                CAN_cycle_send( UNITS_TYPE_BOX, VPU_CAN, 4, &Unites2VPU[4], 4, CAN_BOX_STANDART_ADR, CAN_BOX_PRIORITY_NORMAL);// примерно 40 мсек. идет отправка всей посылки
	        else
	                CAN_cycle_send( UNITS_TYPE_BOX, VPU_CAN, 0xa, &Unites2VPU[4], 4, CAN_BOX_STANDART_ADR, CAN_BOX_PRIORITY_NORMAL);// примерно 40 мсек. идет отправка всей посылки
	    }

//      if (CAN_FIFO_free(3))
//      {
//       if (edrk.flag_second_PCH==0)
//       {
//           CAN_word_send(UNITS_TYPE_BOX, VPU_CAN, 0x4, edrk.to_vpu.OBOROTS1.all);
//           CAN_word_send(UNITS_TYPE_BOX, VPU_CAN, 0x5, edrk.to_vpu.OBOROTS2.all);
//           CAN_word_send(UNITS_TYPE_BOX, VPU_CAN, 0x6, edrk.to_vpu.BIG_LAMS.all);
//           CAN_word_send(UNITS_TYPE_BOX, VPU_CAN, 0x8, 0);
//       }
//       else
//       {
//           CAN_word_send(UNITS_TYPE_BOX, VPU_CAN, 0xa, edrk.to_vpu.OBOROTS1.all);
//           CAN_word_send(UNITS_TYPE_BOX, VPU_CAN, 0xb, edrk.to_vpu.OBOROTS2.all);
//           CAN_word_send(UNITS_TYPE_BOX, VPU_CAN, 0xc, edrk.to_vpu.BIG_LAMS.all);
//           CAN_word_send(UNITS_TYPE_BOX, VPU_CAN, 0xe, 0);
//       }
//
//      }



//	  CAN_word_send(UNITS_TYPE_BOX, ZADATCHIK, 0x4, edrk.to_zadat4ik.APL_LAMS1.all);
	}

}


////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//  спец настройки для межблочного обмена БС1 БС2 по CAN
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////

void init_can_box_between_bs1_bs2(void)
{
    // включаем реверс адресов только для одного БС
    // имитируем ящик Unites какбы
    //
    if (edrk.flag_second_PCH==0)
    {
       unites_can_setup.revers_box[ANOTHER_BSU1_CAN_DEVICE] = 1;
    }

    unites_can_setup.adr_detect_refresh[ZADATCHIK_CAN] = 16;

}

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//  обновлЯем другой БСУ по CAN
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////

void update_bsu_can(unsigned int pause)
{
    int real_mbox;
    int t1;

//    if (edrk.flag_second_PCH==0)
//        t1 = 125;
//    if (edrk.flag_second_PCH==1)
//        t1 = 150;

    SendAll2SecondBS(pause);

}

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

unsigned int counter_imit_rascepitel = 0;

unsigned int imit_signals_rascepitel(unsigned int *counter, unsigned int max_pause, unsigned int s, unsigned int cmd_clear)
{
    if (cmd_clear==1)
    {
        (*counter) = 0;
        return 0;
    }

    if (s)
    {
       if ((*counter)>=max_pause)
          return 1;
       else
           (*counter)++;

       return 0;
    }

    if (s==0)
    {
       if ((*counter)==0)
          return 0;
       else
           (*counter)--;

       return 1;
    }
    return 0;
}

//////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// считываем цифровые входы
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
#define RASCEPITEL_MANUAL_ALWAYS_ON_2   1//1
#define TIME_ON_OFF_FOR_IMITATION_RASCEPITEL    50 // 5 сек.

void update_input_edrk(void)
{
    static unsigned int flag_imit_rascepitel = 0;
    static int st1=0;
// ANOTHER PCH
    edrk.from_second_pch.bits.RASCEPITEL = !FROM_ING_ANOTHER_RASCEPITEL;
    edrk.from_second_pch.bits.MASTER = FROM_ING_ANOTHER_MASTER_PCH;




// ZADAT4IK
    if (control_station.alive_control_station[CONTROL_STATION_ZADATCHIK_CAN])
       edrk.from_zadat4ik.all = Unites[ZADATCHIK_CAN][16];
    else
        edrk.from_zadat4ik.all = 0;

	if (control_station.alive_control_station[CONTROL_STATION_VPU_CAN])
       edrk.from_vpu.all = Unites[VPU_CAN][16];
	else
	    edrk.from_vpu.all = 0;

// ING
#if (_FLOOR6==1)

	if (st1==0)
	{
        edrk.from_ing1.bits.ALL_KNOPKA_AVARIA  = 0;//!FROM_ALL_KNOPKA_AVARIA;
        edrk.from_ing1.bits.BLOCK_IZOL_AVARIA  = 0;//!FROM_ING_BLOCK_IZOL_AVARIA;
        edrk.from_ing1.bits.BLOCK_IZOL_NORMA   = 1;//!FROM_ING_BLOCK_IZOL_NORMA;
        edrk.from_ing1.bits.LOCAL_REMOUTE      = 0;//!FROM_ING_LOCAL_REMOUTE;
        edrk.from_ing1.bits.NAGREV_ON          = 1;//!FROM_ING_NAGREV_ON;
        edrk.from_ing1.bits.NASOS_NORMA        = 1;//!FROM_ING_NASOS_NORMA;
        edrk.from_ing1.bits.NASOS_ON           = 0;//!FROM_ING_NASOS_ON;
        edrk.from_ing1.bits.OHLAD_UTE4KA_WATER = 0;//!FROM_ING_OHLAD_UTE4KA_WATER;
        edrk.from_ing1.bits.UPC_24V_NORMA      = 1;//!FROM_ING_UPC_24V_NORMA;
        edrk.from_ing1.bits.OP_PIT_NORMA       = 1;//!FROM_ING_OP_PIT_NORMA;
        edrk.from_ing1.bits.VENTIL_ON          = 0;//!FROM_ING_VENTIL_ON;
        edrk.from_ing1.bits.VIPR_PREDOHR_NORMA = 1;//!FROM_ING_VIPR_PREDOHR_NORMA;

        edrk.from_ing1.bits.ZARYAD_ON          = 0;//!FROM_ING_ZARYAD_ON;
        edrk.from_ing1.bits.ZAZEML_OFF         = 1;//!FROM_ING_ZAZEML_OFF;
        edrk.from_ing1.bits.ZAZEML_ON          = 0;//!FROM_ING_ZAZEML_ON;

        edrk.from_ing2.bits.KEY_MINUS          = 0;//FROM_ING_OBOROTS_MINUS;
        edrk.from_ing2.bits.KEY_PLUS           = 0;//!FROM_ING_OBOROTS_PLUS;
        edrk.from_ing2.bits.KEY_KVITIR         = 0;//FROM_ING_LOCAL_KVITIR;

        edrk.from_ing2.bits.KEY_SBOR           = 0;//FROM_ING_SBOR_SHEMA;
        edrk.from_ing2.bits.KEY_RAZBOR         = 0;//FROM_ING_RAZBOR_SHEMA;

    //    edrk.from_ing1.bits.RASCEPITEL_ON      = 0;//FROM_ING_RASCEPITEL_ON_OFF;

 //       edrk.from_ing2.bits.SOST_ZAMKA         = !edrk.to_ing.bits.BLOCK_KEY_OFF;//1;//!FROM_ING_SOST_ZAMKA;


    // SHEMA
        edrk.from_shema.bits.RAZBOR_SHEMA      = 0;//FROM_BSU_RAZBOR_SHEMA;
        edrk.from_shema.bits.SBOR_SHEMA        = 0;//FROM_BSU_SBOR_SHEMA;

        edrk.from_shema.bits.ZADA_DISPLAY      = 0;//!FROM_BSU_ZADA_DISPLAY;
        edrk.from_shema.bits.SVU               = 0;//!FROM_BSU_SVU;
    //  edrk.from_shema.bits.KNOPKA_AVARIA     = FROM_ALL_KNOPKA_AVARIA;
        edrk.from_shema.bits.QTV_ON_OFF        = 0;//!FROM_SHEMA_QTV_ON_OFF;
        edrk.from_shema.bits.UMP_ON_OFF        = 0;//!FROM_SHEMA_UMP_ON_OFF;
        edrk.from_shema.bits.READY_UMP         = 1;//!FROM_SHEMA_READY_UMP;
        edrk.from_shema.bits.SVU_BLOCK_QTV     = 0;//!FROM_SVU_BLOCK_QTV;
        st1 = 1;
	}

	// имитация расцепителя
	if (edrk.to_ing.bits.RASCEPITEL_ON)
	    flag_imit_rascepitel = 1;
    if (edrk.to_ing.bits.RASCEPITEL_OFF)
        flag_imit_rascepitel = 0;

	 edrk.from_ing1.bits.RASCEPITEL_ON = imit_signals_rascepitel(&counter_imit_rascepitel, TIME_ON_OFF_FOR_IMITATION_RASCEPITEL, flag_imit_rascepitel, 0);
	/////


	edrk.from_ing2.bits.SOST_ZAMKA         = !edrk.to_ing.bits.BLOCK_KEY_OFF;

#else
	edrk.from_ing1.bits.ALL_KNOPKA_AVARIA  = !FROM_ALL_KNOPKA_AVARIA;
	edrk.from_ing1.bits.BLOCK_IZOL_AVARIA  = !FROM_ING_BLOCK_IZOL_AVARIA;
	edrk.from_ing1.bits.BLOCK_IZOL_NORMA   = !FROM_ING_BLOCK_IZOL_NORMA;
	edrk.from_ing1.bits.LOCAL_REMOUTE 	   = !FROM_ING_LOCAL_REMOUTE;
	edrk.from_ing1.bits.NAGREV_ON 		   = !FROM_ING_NAGREV_ON;
	edrk.from_ing1.bits.NASOS_NORMA        = !FROM_ING_NASOS_NORMA;
	edrk.from_ing1.bits.NASOS_ON 		   = !FROM_ING_NASOS_ON;
	edrk.from_ing1.bits.OHLAD_UTE4KA_WATER = !FROM_ING_OHLAD_UTE4KA_WATER;
	edrk.from_ing1.bits.UPC_24V_NORMA 	   = !FROM_ING_UPC_24V_NORMA;
	edrk.from_ing1.bits.OP_PIT_NORMA 	   = !FROM_ING_OP_PIT_NORMA;
	edrk.from_ing1.bits.VENTIL_ON 		   = !FROM_ING_VENTIL_ON;
	edrk.from_ing1.bits.VIPR_PREDOHR_NORMA = !FROM_ING_VIPR_PREDOHR_NORMA;

	edrk.from_ing1.bits.ZARYAD_ON 		   = !FROM_ING_ZARYAD_ON;
	edrk.from_ing1.bits.ZAZEML_OFF 		   = !FROM_ING_ZAZEML_OFF;
	edrk.from_ing1.bits.ZAZEML_ON 		   = !FROM_ING_ZAZEML_ON;

    edrk.from_ing2.bits.KEY_MINUS          = FROM_ING_OBOROTS_MINUS;
    edrk.from_ing2.bits.KEY_PLUS           = !FROM_ING_OBOROTS_PLUS;
    edrk.from_ing2.bits.KEY_KVITIR         = FROM_ING_LOCAL_KVITIR;

    edrk.from_ing2.bits.KEY_SBOR           = FROM_ING_SBOR_SHEMA;
    edrk.from_ing2.bits.KEY_RAZBOR         = FROM_ING_RAZBOR_SHEMA;

#if(RASCEPITEL_MANUAL_ALWAYS_ON_2)

    // имитация расцепителя
    if (edrk.to_ing.bits.RASCEPITEL_ON)
        flag_imit_rascepitel = 1;
    if (edrk.to_ing.bits.RASCEPITEL_OFF)
        flag_imit_rascepitel = 0;

     edrk.from_ing1.bits.RASCEPITEL_ON = imit_signals_rascepitel(&counter_imit_rascepitel, TIME_ON_OFF_FOR_IMITATION_RASCEPITEL, flag_imit_rascepitel, 0);

#else
    edrk.from_ing1.bits.RASCEPITEL_ON      = FROM_ING_RASCEPITEL_ON_OFF;
#endif
    edrk.from_ing2.bits.SOST_ZAMKA         = !FROM_ING_SOST_ZAMKA;


// SHEMA
	edrk.from_shema.bits.RAZBOR_SHEMA	   = FROM_BSU_RAZBOR_SHEMA;
	edrk.from_shema.bits.SBOR_SHEMA		   = FROM_BSU_SBOR_SHEMA;

	edrk.from_shema.bits.ZADA_DISPLAY 	   = !FROM_BSU_ZADA_DISPLAY;
	edrk.from_shema.bits.SVU 			   = !FROM_BSU_SVU;
//	edrk.from_shema.bits.KNOPKA_AVARIA 	   = FROM_ALL_KNOPKA_AVARIA;
	edrk.from_shema.bits.QTV_ON_OFF		   = !FROM_SHEMA_QTV_ON_OFF;
	edrk.from_shema.bits.UMP_ON_OFF        = !FROM_SHEMA_UMP_ON_OFF;
	edrk.from_shema.bits.READY_UMP         = !FROM_SHEMA_READY_UMP;
	edrk.from_shema.bits.SVU_BLOCK_QTV     = !FROM_SVU_BLOCK_QTV;

#endif
}

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// определение откуда получать задачу на обороты
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
void get_where_oborots(void)
{

////	if (CAN_timeout[get_real_out_mbox(MPU_TYPE_BOX,0)-1]==0)
//    if (CAN_timeout[get_real_in_mbox(MPU_TYPE_BOX,0)]==0)
//	{
//	  edrk.W_from_SVU = modbus_table_can_in[14].all;
//      edrk.W_from_DISPLAY = modbus_table_can_in[16].all;
//	}
//	else
//	{
//	  edrk.W_from_SVU = 0;
//	  edrk.W_from_DISPLAY = 0;
//	}
//
//
//
//
//	if (edrk.from_shema.bits.SVU)
//	{
//	 edrk.W_from_all = edrk.W_from_SVU;
//	 edrk.W_from_ZADAT4IK = edrk.W_from_all;
//	}
//	else
//	{
//	  if (edrk.from_shema.bits.ZADA_DISPLAY)
//	  {
//	   edrk.W_from_all = edrk.W_from_DISPLAY;
//	   edrk.W_from_ZADAT4IK = edrk.W_from_all;
//	  }
//	  else
//	   edrk.W_from_all = edrk.W_from_ZADAT4IK;
//	}

}

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

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

unsigned int toggle_status_lamp(unsigned int bb1, unsigned int flag)
{

    if (bb1==1 && flag==0)
    {
        return 0;
    }

    if (bb1==0 && flag==0)
    {
        return 0;
    }

    if (bb1==1 && flag==1)
    {
            return 0;
    }

    if (bb1==0 && flag==1)
    {
            return 1;
    }
    return 0;
}

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// записываем цифровые выходы
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
void update_output_edrk(void)
{
    unsigned int b;
    static unsigned int time_toggle1=0,time_toggle2=0;

//to ingetim

	TO_ING_NAGREV_OFF					= !edrk.to_ing.bits.NAGREV_OFF;
	TO_ING_NASOS_1_ON					= !edrk.to_ing.bits.NASOS_1_ON;
	TO_ING_NASOS_2_ON					= !edrk.to_ing.bits.NASOS_2_ON;
  //	TO_ING_RESET_BLOCK_IZOL				= !edrk.to_ing.bits.RESET_BLOCK_IZOL;
	TO_ING_SMALL_LAMPA_AVARIA			= edrk.to_ing.bits.SMALL_LAMPA_AVARIA;


	TO_ING_RASCEPITEL_OFF               = !edrk.to_ing.bits.RASCEPITEL_OFF;
    TO_ING_RASCEPITEL_ON                = !edrk.to_ing.bits.RASCEPITEL_ON;


// ANOTHER PCH
    TO_SECOND_PCH_MASTER                = edrk.to_second_pch.bits.MASTER;
    TO_SECOND_PCH_ALARM                 = !edrk.to_second_pch.bits.ALARM;



//to_shema
//
//#if (ENABLE_USE_QTV==1)
//	TO_STEND_QM_ON_INVERS				= !edrk.to_shema.bits.QTV_ON;
//#endif


    if (control_station.active_array_cmd[CONTROL_STATION_CMD_CROSS_STEND_AUTOMATS])
    {
#if (MODE_QTV_UPRAVLENIE==1)
        TO_SHEMA_QTV_ON_OFF                     = !edrk.to_shema.bits.CROSS_QTV_ON_OFF;
#endif
        TO_ING_LAMPA_ZARYAD                     = !edrk.to_shema.bits.CROSS_QTV_ON_OFF;
        if (edrk.to_ing.bits.BLOCK_KEY_OFF || edrk.to_shema.bits.CROSS_QTV_ON_OFF)
            TO_ING_BLOCK_KEY_OFF = 0;
        else
            TO_ING_BLOCK_KEY_OFF = 1;
//        TO_ING_BLOCK_KEY_OFF                    = !edrk.to_shema.bits.CROSS_QTV_ON_OFF;


        TO_SHEMA_ENABLE_QTV                     = !edrk.to_shema.bits.CROSS_QTV_ON_OFF;

        TO_SHEMA_UMP_ON_OFF                     = !edrk.to_shema.bits.CROSS_UMP_ON_OFF;
    }
    else
    {

        TO_ING_LAMPA_ZARYAD                 = !edrk.Status_Ready.bits.Batt;
        TO_ING_ZARYAD_ON                    = !edrk.to_ing.bits.ZARYAD_ON;
        TO_ING_BLOCK_KEY_OFF                = !edrk.to_ing.bits.BLOCK_KEY_OFF;

#if (MODE_QTV_UPRAVLENIE==1)
        TO_SHEMA_QTV_ON_OFF                     = !edrk.to_shema.bits.QTV_ON_OFF;
#endif


#if (MODE_QTV_UPRAVLENIE==2)
        TO_SHEMA_QTV_OFF                        = !edrk.to_shema.bits.QTV_OFF;
        TO_SHEMA_QTV_ON                         = !edrk.to_shema.bits.QTV_ON;
#endif

        TO_SHEMA_ENABLE_QTV                     = !edrk.to_shema.bits.ENABLE_QTV;
        TO_SHEMA_UMP_ON_OFF                     = !edrk.to_shema.bits.UMP_ON_OFF;

    }





//lamps APL
//	if (edrk.Sbor)// && edrk.from_ing.bits2.GED_NAMAGNI4EN==0)
//	{
//	    if (edrk.Status_Ready.bits.ready5==0)
//		  edrk.to_zadat4ik.APL_LAMS0.bits.SBOR_SIL_SHEMA = 1;
//		else
//		  edrk.to_zadat4ik.APL_LAMS0.bits.SBOR_SIL_SHEMA = 0;
//	}
//	else
//	{
//		edrk.to_zadat4ik.APL_LAMS0.bits.SBOR_SIL_SHEMA = 0;
//	}



	edrk.to_vpu.BIG_LAMS.bits.GOTOV2 =  edrk.Status_Ready.bits.ready_final;
	edrk.to_vpu.BIG_LAMS.bits.PEREGRUZKA = edrk.to_zadat4ik.BIG_LAMS.bits.OGRAN_POWER;
	edrk.to_vpu.BIG_LAMS.bits.PODDERG_OBOROTS = 0;//
	edrk.to_vpu.BIG_LAMS.bits.VPU = edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_VPU;

}


///////////////////////////////////////////////
///////////////////////////////////////////////
// ОсновнаЯ программа 
///////////////////////////////////////////////
///////////////////////////////////////////////

///////////////////////////////////////////////
void nagrev_auto_on_off(void)
{
   if (edrk.temper_edrk.max_real_int_temper_water<TEMPER_NAGREF_ON)
     edrk.to_ing.bits.NAGREV_OFF = 0; 

   if (edrk.temper_edrk.max_real_int_temper_water>TEMPER_NAGREF_OFF)
     edrk.to_ing.bits.NAGREV_OFF = 1; 

}
///////////////////////////////////////////////
#define TIME_WAIT_OFF_BLOCK_KEY	100
void auto_block_key_on_off(void)
{
static unsigned int count_err = TIME_WAIT_OFF_BLOCK_KEY;

   if (filter.iqU_1_long >= U_LEVEL_ON_BLOCK_KEY || filter.iqU_2_long >= U_LEVEL_ON_BLOCK_KEY || edrk.SumSbor)
   {
     edrk.Status_Ready.bits.Batt    = 1;
     edrk.to_ing.bits.BLOCK_KEY_OFF = 0;
	 count_err = 0;
   }

   if (filter.iqU_1_long <= U_LEVEL_OFF_BLOCK_KEY && filter.iqU_2_long <= U_LEVEL_OFF_BLOCK_KEY && edrk.SumSbor==0)
   {
     if (pause_detect_error(&count_err,TIME_WAIT_OFF_BLOCK_KEY,1))
	 {
        edrk.to_ing.bits.BLOCK_KEY_OFF = 1;
		edrk.Status_Ready.bits.Batt    = 0;
	 }
   }
   else
     count_err = 0;


}


///////////////////////////////////////////////
///////////////////////////////////////////////
void update_lamp_alarm(void)
{
	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.to_ing.bits.SMALL_LAMPA_AVARIA = 1;
 //	  edrk.to_second_pch.bits.ALARM = 1;
	  edrk.summ_errors = 1;
	  edrk.Stop |= 1;
	}
	else
	{
	  edrk.to_ing.bits.SMALL_LAMPA_AVARIA = 0;
	  edrk.to_second_pch.bits.ALARM = 0;
	  edrk.summ_errors = 0;
	}

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




///////////////////////////////////////////////
///////////////////////////////////////////////
#define TIME_WAIT_RELE_QTV_ON 20 //2 sec
#define TIME_WAIT_RELE_QTV_OFF 20 //2 sec

#define TIME_WAIT_ANSWER_QTV_ON     TIME_WAIT_ERROR_QTV //150 //15 sec
#define TIME_WAIT_ANSWER_QTV_OFF    40 //4 sec

///////////////////////////////////////////////
int qtv_on_off(unsigned int flag)
{
static unsigned int time_wait_rele_on_qtv=0;
static unsigned int time_wait_rele_off_qtv=0;
static unsigned int time_wait_answer_on_qtv=0;
static unsigned int time_wait_answer_off_qtv=0;
static unsigned int count_err_on = 0;


int cmd_qtv=0;//,cmd_p2=0;
static int QTV_Ok = 0;
static int prev_error = 0;


   cmd_qtv = 0;
//   cmd_p2 = 0;

   if ( flag==1 && edrk.summ_errors==0)	
   {
	   cmd_qtv = 1;
   }
   else
   {
	   cmd_qtv = 0;
   }



   edrk.cmd_to_qtv = cmd_qtv;

   if (cmd_qtv)
   {   
        edrk.to_shema.bits.ENABLE_QTV = 1;
        edrk.to_shema.bits.QTV_OFF = 1;

        if ((pause_detect_error(&time_wait_rele_on_qtv,TIME_WAIT_RELE_QTV_ON,1)==0) && edrk.from_shema.bits.QTV_ON_OFF==0)
        {
#if (MODE_QTV_UPRAVLENIE==2)
		  edrk.to_shema.bits.QTV_ON = 1;
#endif
#if (MODE_QTV_UPRAVLENIE==1)
		  edrk.to_shema.bits.QTV_ON_OFF = 1;
#endif
        }
		else
		  edrk.to_shema.bits.QTV_ON = 0;


		if (pause_detect_error(&time_wait_answer_on_qtv,TIME_WAIT_ANSWER_QTV_ON,1)==0)
		{

		   if (edrk.from_shema.bits.QTV_ON_OFF==1)
  			  QTV_Ok = 1;

		}
		else
		{

		    // была команда на вкл, но сухой контакт не пришел
			if (edrk.from_shema.bits.QTV_ON_OFF==0)
			{
#if (WORK_ON_STEND_D)
			  if (pause_detect_error(&count_err_on,TIME_WAIT_ANSWER_QTV_ON,1))
			  {
			      edrk.errors.e6.bits.QTV_ERROR_NOT_ANSWER |= 1;
			      QTV_Ok = 0;
			  }
#else
			  edrk.errors.e6.bits.QTV_ERROR_NOT_ANSWER |= 1;
			  QTV_Ok = 0;
#endif
			}
			else
			    count_err_on = 0;

		}

		time_wait_rele_off_qtv = 0;
		time_wait_answer_off_qtv = 0;
   }
   else
   {
		QTV_Ok = 0;
		edrk.to_shema.bits.ENABLE_QTV = 0;
        time_wait_rele_on_qtv = 0;
		time_wait_answer_on_qtv = 0;

		edrk.to_shema.bits.QTV_ON = 0;

		edrk.to_shema.bits.QTV_ON_OFF = 0;

//        if (pause_detect_error(&time_wait_rele_off_qtv,TIME_WAIT_RELE_QTV_OFF,1)==0)
//		  edrk.to_shema.bits.QTV_OFF = 1;
//		else
		  edrk.to_shema.bits.QTV_OFF = 0;
		

		if (pause_detect_error(&time_wait_answer_off_qtv,TIME_WAIT_ANSWER_QTV_OFF,1)==0)
		{
			
		}
		else
		{
			if (edrk.from_shema.bits.QTV_ON_OFF==1)
			  edrk.errors.e6.bits.QTV_ERROR_NOT_ANSWER |= 1;
		}


		if (prev_error!=edrk.summ_errors && edrk.summ_errors)
		{
		  if (pause_detect_error(&time_wait_rele_off_qtv,TIME_WAIT_RELE_QTV_OFF,1)==1)
		     time_wait_rele_off_qtv = 0; 
		}


   }

   prev_error = edrk.summ_errors;
   return (QTV_Ok);


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

///////////////////////////////////////////////
void detect_kvitir_from_all(void)
{

  static int prev_kvitir=0;

  edrk.Kvitir = control_station.active_array_cmd[CONTROL_STATION_CMD_CHECKBACK] || edrk.from_ing2.bits.KEY_KVITIR;

 /*
  if (edrk.RemouteFromRS)
    edrk.Kvitir = edrk.KvitirRS;

  if (edrk.RemouteFromVPU)
    edrk.Kvitir = edrk.KvitirVPU;

  if (edrk.RemouteFromDISPLAY)
    edrk.Kvitir = edrk.from_display.bits.KVITIR;//edrk.KvitirDISPLAY;

  if (edrk.RemouteFromMPU)
    edrk.Kvitir = edrk.KvitirMPU;
*/

  if (edrk.Kvitir==1 && prev_kvitir==0)
  {

    if (edrk.Status_Ready.bits.ready_final==0 && edrk.Go==0 && edrk.Stop == 1)
	{
      edrk.KvitirProcess = 1;
	  project.clear_errors_all_plates();
	  clear_errors();
      edrk.KvitirProcess = 0;
	}
    clear_warnings();
 /*   edrk.KvitirDISPLAY = 0;
	edrk.KvitirVPU = 0;
	edrk.KvitirMPU = 0;
	edrk.KvitirSVU = 0;
	edrk.KvitirRS = 0;
	*/
  }

  prev_kvitir = edrk.Kvitir;
}

///////////////////////////////////////////////
unsigned int get_ready_1(void)
{
    unsigned int r1, r2;



    if (project.cds_in[0].status == component_Ready
            && project.cds_in[1].status == component_Ready
              && project.cds_out[0].status == component_Ready
              && project.cds_tk[0].status == component_Ready
              && project.cds_tk[1].status == component_Ready
              && project.cds_tk[2].status == component_Ready
              && project.cds_tk[3].status == component_Ready
              && project.adc[0].status == component_Ready
              && project.adc[1].status == component_Ready
              && project.hwp[0].status == component_Ready
              )
      r2 = 1;
    else
      r2 = 0;


    r1 = (edrk.ms.ready1 && edrk.from_ing1.bits.NASOS_NORMA
            && edrk.from_ing1.bits.ZAZEML_ON==0 && edrk.from_ing1.bits.ZAZEML_OFF==1
            && edrk.from_ing1.bits.VIPR_PREDOHR_NORMA
            && edrk.from_ing1.bits.BLOCK_IZOL_NORMA
            && edrk.from_ing1.bits.OP_PIT_NORMA
            && edrk.from_ing1.bits.UPC_24V_NORMA
            && r2);

    return r1;


}
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
#define MAX_U_PROC_SMALL	        2.5                 //1.4
#define MAX_U_PROC                  1.3             //1.11                 //1.4
#define MIN_U_PROC                  0.8       //0.7

#define ADD_U_MAX_GLOBAL            200.0   //V  Насколько поднимаем уставку GLOBAL относительно ZadanieU_Charge
#define ADD_U_MAX_GLOBAL_SMALL      500.0   //V  Насколько поднимаем уставку GLOBAL относительно ZadanieU_Charge
#define LEVEL_DETECT_U_SMALL        1000.0  //V  Насколько поднимаем уставку GLOBAL относительно ZadanieU_Charge


void set_zadanie_u_charge(void)
{

//	edrk.ZadanieU_Charge = edrk.ZadanieU_Charge_RS;

//	edrk.iq_ZadanieU_Charge = _IQ(edrk.ZadanieU_Charge/NORMA_ACP);

    if (edrk.zadanie.ZadanieU_Charge<=100)
    {
        edrk.iqMIN_U_ZPT = _IQ(-50.0/NORMA_ACP);
        edrk.iqMIN_U_IN = _IQ(-50.0/NORMA_ACP);
    }
    else
    {

        edrk.iqMIN_U_ZPT = _IQ(edrk.zadanie.ZadanieU_Charge*MIN_U_PROC/NORMA_ACP);
        edrk.iqMIN_U_IN = _IQ(edrk.zadanie.ZadanieU_Charge*MIN_U_PROC/NORMA_ACP);

    }

    if (edrk.zadanie.ZadanieU_Charge<LEVEL_DETECT_U_SMALL)
    {
	  edrk.iqMAX_U_ZPT_Predzaryad = _IQ(edrk.zadanie.ZadanieU_Charge*MAX_U_PROC_SMALL/NORMA_ACP);
	  edrk.iqMAX_U_ZPT_Global = edrk.iqMAX_U_ZPT_Predzaryad + _IQ(ADD_U_MAX_GLOBAL_SMALL/NORMA_ACP); // +500V

    }
    else
    {
      edrk.iqMAX_U_ZPT_Predzaryad = _IQ(edrk.zadanie.ZadanieU_Charge*MAX_U_PROC/NORMA_ACP);
      edrk.iqMAX_U_ZPT_Global = edrk.iqMAX_U_ZPT_Predzaryad + _IQ(ADD_U_MAX_GLOBAL/NORMA_ACP); // +200V

      if (edrk.iqMAX_U_ZPT_Global>U_D_MAX_ERROR_GLOBAL_2800)
          edrk.iqMAX_U_ZPT_Global = U_D_MAX_ERROR_GLOBAL_2800;
    }

    edrk.iqMAX_U_ZPT =  _IQ(edrk.zadanie.ZadanieU_Charge*MAX_U_PROC/NORMA_ACP);
    edrk.iqMAX_U_IN = _IQ(edrk.zadanie.ZadanieU_Charge*MAX_U_PROC/NORMA_ACP);


}


///////////////////////////////////////////////
///////////////////////////////////////////////
// ОсновнаЯ программа 
///////////////////////////////////////////////
///////////////////////////////////////////////

void test_send_alarm_log(int alarm_cmd)
{
    static unsigned int points_alarm_log = 1000;
 //   static unsigned int nchannel_alarm_log = 30;
    static int prev_alarm_cmd = 0;
    static int local_alarm_cmd = 0;



    if (alarm_cmd && prev_alarm_cmd==0 && alarm_log_can.stage==0)
    {
//        i_led2_on();

        alarm_log_can.post_points = COUNT_SAVE_LOG_OFF;//100;                   // количество поставарийныйх записей
        alarm_log_can.oscills = logpar.count_log_params_fast_log;//nchannel_alarm_log;         // количество колонок

        alarm_log_can.global_enable = 1;

        alarm_log_can.start_adr_temp = (int *)0xc0000;      // адрес для временного размещения копии лога, лог скопируется из циклического буфера в этот развернувшись.

    //    alarm_log_can.finish_adr_temp = (int *)0xa0000;      // адрес для временного размещения копии лога, лог скопируется из циклического буфера в этот развернувшись.

        alarm_log_can.start_adr_real_logs = (int *)START_ADDRESS_LOG; // адрес начала реальных логов в циклическом буфере
        alarm_log_can.finish_adr_real_log = (int *)logpar.real_finish_addres_mem; // конец логов в циклическом буфере

        alarm_log_can.current_adr_real_log = (int *)logpar.addres_mem;


        alarm_log_can.temp_points = points_alarm_log;   // реальный размер циклическго буфера в точках.
    //    alarm_log_can.real_points = 1000;               // нужный кусок для копии, данное количество скопируется из циклического буфера во временный лог.

        alarm_log_can.step = 450; // mks
        local_alarm_cmd = alarm_cmd;
//        alarm_log_can.status_alarm = alarm_cmd;//cmd_alarm_log; //  код аварии
        alarm_log_can.start = 0x1;
        alarm_log_can.stop = 0x1;
        alarm_log_can.copy2temp = 0x1;


        alarm_log_can.clear(&alarm_log_can);
//        alarm_log_can.send(&alarm_log_can);

//        i_led2_off();
    }
    else
        local_alarm_cmd = 0;

    alarm_log_can.status_alarm = local_alarm_cmd;//cmd_alarm_log; //  код аварии
    alarm_log_can.send(&alarm_log_can);

    if (alarm_log_can.stage)
    {
        i_led2_on_off(1);
    }
    else
    {
        i_led2_on_off(0);
    }

    prev_alarm_cmd = alarm_cmd;

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

void run_edrk(void)
{
 //   static unsigned int prev_SumSbor = 0, prev_AllStart = 0, prev_VozbudOnOff = 0, prev_SBOR_SHEMA_VPU = 0,prev_SBOR_SHEMA_RS=0, prev_SBOR_SHEMA_DISPLAY = 0;

    int current_active_control, ff =0;
    static unsigned int filter_count_error_control_station_select_active = 0;
    static int flag_enable_update_mpu = 1;
    static unsigned int external_cmd_alarm_log = 0;
    //static int ccc[40] = {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, 0,0,0,0,0,0,0,0,0,0};
    static int ccc[40] = {0,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1};
    static int prev_enable_pwm_test_lines=0;


    if (f.Prepare || f.terminal_prepare) {
        project.clear_errors_all_plates();
    }

 //   slow_vector_update();

    read_plane_errors();

//    if (flag_enable_update_hmi)
//       update_tables_HMI();
//    if (flag_enable_update_mpu)
//       update_modbus_table();
//    modbusNetworkSharing(1);
//    get_command_HMI();

//    return;

//    i_led1_on_off(1);
    if (edrk.flag_disable_pult_485==0)
        modbusNetworkSharing(0);
//    i_led1_on_off(0);

    if (!(detect_pause_milisec(100,&old_time_edrk2)))
       return;

    if (ccc[0])  return;
    ////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////
    //  Дальше код запускается раз в 100 мсек.
    ////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////


    // external_cmd_alarm_log = modbus_table_can_in[11].all;
    //  test_send_alarm_log(external_cmd_alarm_log);

    //  modbusNetworkSharing(0);

    //    i_led2_on_off(1);

    if (ccc[1]) modbusNetworkSharingCAN();

    #if (ENABLE_CAN_SEND_TO_UKSS_FROM_MAIN)
    // пишем в задатчик
    if (ccc[2]) update_ukss_can(TIME_PAUSE_MODBUS_CAN_ZADATCHIK_VPU);
    if (ccc[3]) update_ukss_setup(TIME_PAUSE_MODBUS_CAN_UKSS_SETUP);
    #endif

    #if (ENABLE_CAN_SEND_TO_ANOTHER_BSU_FROM_MAIN)
// пишем в задатчик
    if (ccc[4]) update_bsu_can(TIME_PAUSE_MODBUS_CAN_BS2BS);
    #endif

    if (ccc[5]) check_all_power_limits();

    if (ccc[6]) calc_p_water_edrk();
    if (ccc[7]) calc_temper_edrk();
    if (ccc[8]) calc_temper_acdrive();

    // читаем цифр входы
    if (ccc[9]) update_input_edrk();

    if (ccc[10]) detect_kvitir_from_all();

    if (ccc[11]) detect_error_all();

    if (ccc[12]) calc_limit_overheat();

    if (ccc[13]) calc_RMS_values_main();

    if (ccc[14]) update_lamp_alarm();

    if (ccc[15]) set_zadanie_u_charge();

    if (ccc[16]) reinit_protect_I_and_U_settings();

    if (ccc[17]) nagrev_auto_on_off();

    if (ccc[18]) auto_block_key_on_off();

    edrk.f_rotor_hz = _IQtoF(edrk.iq_f_rotor_hz) * NORMA_FROTOR;
    edrk.oborots =  fast_round(edrk.f_rotor_hz*60.0);
    edrk.power_kw =  _IQtoF(filter.PowerScalar) * NORMA_ACP * NORMA_ACP / 1000.0;
    edrk.Status_Ready.bits.ready1 = get_ready_1();

    if (ccc[19]) pump_control();


    if (control_station_select_active())
    {

        if (filter_count_error_control_station_select_active<30)
            filter_count_error_control_station_select_active++;
        else
            edrk.errors.e7.bits.NOT_VALID_CONTROL_STATION |= 1;
    }
    else
        filter_count_error_control_station_select_active = 0;

    current_active_control = get_current_station_control();

    if (current_active_control<CONTROL_STATION_LAST)
    {
          // есть активный пост управления
    }


    // разбираем все данные со всех возможных постов управления
    if (ccc[20]) parse_parameters_from_all_control_station();
    //копируем данные из активного поста в текущий
    if (ccc[21]) load_parameters_from_active_control_station(current_active_control);

    // если мы slave то часть данных берем с мастера по CAN и замещаем в active_control_station
    if (ccc[22]) parse_data_from_master_to_alg();


    ff = control_station.active_array_cmd[CONTROL_STATION_CMD_SET_ROTOR];
    control_station.array_cmd[CONTROL_STATION_INGETEAM_PULT_RS485][CONTROL_STATION_CMD_SET_ROTOR] = ff;
    control_station.array_cmd[CONTROL_STATION_VPU_CAN][CONTROL_STATION_CMD_SET_ROTOR] = ff;
    control_station.array_cmd[CONTROL_STATION_ZADATCHIK_CAN][CONTROL_STATION_CMD_SET_ROTOR] = ff;

    ff = control_station.active_array_cmd[CONTROL_STATION_CMD_SET_POWER];
    control_station.array_cmd[CONTROL_STATION_INGETEAM_PULT_RS485][CONTROL_STATION_CMD_SET_POWER] = ff;


    if (control_station.active_array_cmd[CONTROL_STATION_CMD_ROTOR_POWER])
    {
          control_station.array_cmd[CONTROL_STATION_ZADATCHIK_CAN][CONTROL_STATION_CMD_SET_ROTOR] = 0;
          control_station.array_cmd[CONTROL_STATION_VPU_CAN][CONTROL_STATION_CMD_SET_ROTOR] = 0;
    }

    // для стенда, при пуске только одного БС, на другом мы должны включить разрешающие сигналы для автоматов,
    // т.к. сигналы управления QTV и QPU включены последовательно.
    if (ccc[23]) cross_stend_automats();

    // обработка данных от другого БС по CAN
    if (ccc[24]) read_data_from_bs();

    //конвертим аналоговые данные из текущего поста управления в структуру edrk.
    if (ccc[25]) parse_analog_data_from_active_control_station_to_alg();

    //  if (flag_enable_update_hmi)
    //     update_tables_HMI();
    if (flag_enable_update_mpu)
    {
        if (ccc[26])     update_svu_modbus_table();
    }

     // modbusNetworkSharing(0);

    if (edrk.get_new_data_from_hmi)
    {
        if (ccc[27]) get_command_HMI();
          edrk.get_new_data_from_hmi = 0;
    }


    if (flag_enable_can_from_mpu)
    {

    //          write_all_data_to_mpu_485(0);
    //          read_all_data_from_mpu_485(0);
    //          write_all_data_to_mpu_can(1);
    //          test_rs_can_with_svu_mpu();
    }

    //

    if (edrk.test_mode) return;

    if (ccc[28]) get_sumsbor_command();

    if (ccc[29]) sbor_shema(edrk.SumSbor);

    if (ccc[30]) auto_select_master_slave();

    if (ccc[31]) who_select_sync_signal();

    if (ccc[32]) check_change_post_upravl();

    if (ccc[33]) get_freq_50hz();

    if (ccc[34]) auto_detect_zero_u_zpt();

    if (detect_pause_sec(1,&old_time_edrk1))
    {

    }  // 1 sec end

    if (ccc[35]) update_zadat4ik();

    ////////////////////////////////////////////////////////////
    //  пишем цифровые выходы
    ////////////////////////////////////////////////////////////
    if (ccc[36]) update_output_edrk();

    //    i_led2_on_off(0);





    if (edrk.enable_pwm_test_lines != prev_enable_pwm_test_lines)
    {
        if (edrk.enable_pwm_test_lines)
            pwm_test_lines_start();
        else
            pwm_test_lines_stop();
    }
    prev_enable_pwm_test_lines = edrk.enable_pwm_test_lines;
}


////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
void get_sumsbor_command(void)
{
    static unsigned int prev_SBOR_SHEMA = 0;
    static unsigned int prev_SBOR_SHEMA_ANOTHER_BS = 0;
    unsigned int SBOR_SHEMA_ANOTHER_BS = 0;
    static unsigned int Sbor;

    Sbor = edrk.SumSbor;

    if (Sbor == 0)
        edrk.run_razbor_shema = 0;

    SBOR_SHEMA_ANOTHER_BS = read_cmd_sbor_from_bs();

    // есть команда сбор схемы с активного пульта
    if (control_station.active_array_cmd[CONTROL_STATION_CMD_CHARGE]==1 && (prev_SBOR_SHEMA==0)
            && edrk.from_ing1.bits.ALL_KNOPKA_AVARIA==0 && edrk.summ_errors==0
            && control_station.active_array_cmd[CONTROL_STATION_CMD_UNCHARGE]==0
            )
        Sbor = 1;

    if (control_station.active_array_cmd[CONTROL_STATION_CMD_UNCHARGE]==1)
    {
        edrk.run_razbor_shema = 1;
 //       Sbor = 0;
    }


    if (edrk.StartGEDfromZadanie==0 && edrk.run_razbor_shema)
        Sbor = 0;


    if (SBOR_SHEMA_ANOTHER_BS==0 && prev_SBOR_SHEMA_ANOTHER_BS==1)
    {
        Sbor = 0;
    }

    prev_SBOR_SHEMA = control_station.active_array_cmd[CONTROL_STATION_CMD_CHARGE];

    prev_SBOR_SHEMA_ANOTHER_BS = SBOR_SHEMA_ANOTHER_BS;


    // разбор по аварии и кнопке!
        if (edrk.from_ing1.bits.ALL_KNOPKA_AVARIA || edrk.summ_errors)
        {
            Sbor = 0;
        }

        edrk.SumSbor = Sbor;

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


void update_zadat4ik(void)
{

       static unsigned int time_toggle1 = 0, time_toggle2 = 0, time_toggle3 = 0, time_toggle4 = 0;
       int b;
       static unsigned int time_toggle_leds = 500;


    // update zadatchik
//        if (edrk.from_zadat4ik.bits.MINUS || edrk.from_zadat4ik.bits.PLUS || edrk.from_ing2.bits.KEY_MINUS || edrk.from_ing2.bits.KEY_PLUS || edrk.from_vpu.bits.PLUS || edrk.from_vpu.bits.MINUS)
//        {
//          if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_UF_CONST) // UFCONST
//          {
//           edrk.to_zadat4ik.OBOROTS1.all = fast_round(edrk.zadanie.fzad*100.0);              // обороты заданные
//           edrk.to_vpu.OBOROTS1.all = edrk.to_zadat4ik.OBOROTS1.all;             // обороты заданные
//          }
//          else
//          {
//              edrk.to_zadat4ik.OBOROTS1.all = (edrk.zadanie.oborots_zad);             // обороты заданные
//              edrk.to_vpu.OBOROTS1.all =  edrk.to_zadat4ik.OBOROTS1.all;             // обороты заданные
//          }
//
//        }
//        else
//        {
//
//              if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_UF_CONST) // UFCONST
//              {
//               edrk.to_zadat4ik.OBOROTS1.all = fast_round(_IQtoF(edrk.f_stator)*NORMA_FROTOR*100.0);             // обороты тек.
//               edrk.to_vpu.OBOROTS1.all = edrk.to_zadat4ik.OBOROTS1.all;             // обороты тек.
//              }
//              else
//              {
//                  edrk.to_zadat4ik.OBOROTS1.all = edrk.oborots;             // обороты тек.
//                  edrk.to_vpu.OBOROTS1.all =  edrk.to_zadat4ik.OBOROTS1.all;             // обороты тек.
//              }
//
//        }

        if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_UF_CONST) // UFCONST
        {
            edrk.to_zadat4ik.OBOROTS1.all = fast_round(_IQtoF(edrk.f_stator)*NORMA_FROTOR*100.0);             // обороты тек.
            edrk.to_vpu.OBOROTS1.all = edrk.to_zadat4ik.OBOROTS1.all;             // обороты тек.
        }
        else
        {
            edrk.to_zadat4ik.OBOROTS1.all = edrk.zadanie.oborots_zad;             // обороты заданные
            edrk.to_vpu.OBOROTS1.all =  edrk.to_zadat4ik.OBOROTS1.all;             // обороты заданные
        }

        //edrk.to_zadat4ik.OBOROTS2.all = edrk.I_cur_vozbud_exp;    // ток возбудителЯ

        if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_UF_CONST) // UFCONST
        {
            edrk.to_zadat4ik.OBOROTS2.all = fast_round(_IQtoF(edrk.k_stator1)*10000.0);
            edrk.to_vpu.OBOROTS2.all =  edrk.to_zadat4ik.OBOROTS2.all;
        }
        else
        {
//            edrk.to_zadat4ik.OBOROTS2.all = edrk.to_zadat4ik.OBOROTS1.all;
//            edrk.to_vpu.OBOROTS2.all = edrk.to_zadat4ik.OBOROTS2.all;
            edrk.to_zadat4ik.OBOROTS2.all = edrk.oborots;   //оборты текущие
            edrk.to_vpu.OBOROTS2.all = edrk.to_zadat4ik.OBOROTS2.all;

        }


        // Готовность2
            if (edrk.Status_Ready.bits.ready_final)
               edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_SHEMA_SOBRANA = 1;//edrk.from_shema.bits.QTV_ON_OFF;
            else
            {
               if (edrk.SumSbor)
               {
                   if (detect_pause_milisec(time_toggle_leds,&time_toggle1))
                     edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_SHEMA_SOBRANA = toggle_status_lamp((unsigned int)edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_SHEMA_SOBRANA,1);
               }
               else
                   edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_SHEMA_SOBRANA = 0;
            }


            if (edrk.Ready2_another_bs && edrk.Status_Ready.bits.ready_final)
                edrk.to_zadat4ik.BIG_LAMS.bits.GOTOV2 = 1;
            else
            {
                if (edrk.Status_Ready.bits.ready_final)
                {
                  if (detect_pause_milisec(time_toggle_leds,&time_toggle3))
                      edrk.to_zadat4ik.BIG_LAMS.bits.GOTOV2 = toggle_status_lamp((unsigned int)edrk.to_zadat4ik.BIG_LAMS.bits.GOTOV2,1);
                }
                else
                    edrk.to_zadat4ik.BIG_LAMS.bits.GOTOV2 = 0;
            }

            edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_MESTNOE = control_station.active_control_station[CONTROL_STATION_INGETEAM_PULT_RS485];//edrk.from_ing1.bits.LOCAL_REMOUTE; // LOCAL


            if (edrk.Status_Perehod_Rascepitel==0)
                edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_PODKLU4EN = edrk.Final_Status_Rascepitel;
            else
            {
                b =  edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_PODKLU4EN;
                if (detect_pause_milisec(time_toggle_leds,&time_toggle2))
                  edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_PODKLU4EN = toggle_status_lamp((unsigned int)edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_PODKLU4EN,1);
            }

        //  edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_PODKLU4EN = edrk.Status_Rascepitel_Ok || edrk.Status_Perehod_Rascepitel;
            edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_READY1 = edrk.Status_Ready.bits.ready1;

        //Емкость
//            edrk.to_zadat4ik.BIG_LAMS.bits.EMKOST = edrk.Status_Ready.bits.Batt;//edrk.Status_Charge; For 23550.3


            edrk.to_zadat4ik.BIG_LAMS.bits.PEREGREV = edrk.temper_limit_koeffs.code_status;
            edrk.to_zadat4ik.BIG_LAMS.bits.OGRAN_POWER = edrk.power_limit.all;

            if (edrk.Ready1_another_bs && edrk.Status_Ready.bits.ready1)
                edrk.to_zadat4ik.BIG_LAMS.bits.GOTOV1 = 1;
            else
            {
                if (edrk.Status_Ready.bits.ready1)
                {
                  if (detect_pause_milisec(time_toggle_leds,&time_toggle4))
                    edrk.to_zadat4ik.BIG_LAMS.bits.GOTOV1 = toggle_status_lamp((unsigned int)edrk.to_zadat4ik.BIG_LAMS.bits.GOTOV1,1);
                }
                else
                    edrk.to_zadat4ik.BIG_LAMS.bits.GOTOV1 = 0;
            }
            edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_READY1 = edrk.Status_Ready.bits.ready1;

            edrk.to_zadat4ik.BIG_LAMS.bits.NEISPRAVNOST = edrk.warning;

            if (edrk.flag_second_PCH==0)
            {
                edrk.to_zadat4ik.APL_LAMS0.bits.PCH1_MESTNOE = edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_MESTNOE;
                edrk.to_zadat4ik.APL_LAMS0.bits.PCH1_PODKLU4EN = edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_PODKLU4EN;
                edrk.to_zadat4ik.APL_LAMS0.bits.PCH1_READY1 = edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_READY1;
                edrk.to_zadat4ik.APL_LAMS0.bits.PCH1_SHEMA_SOBRANA = edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_SHEMA_SOBRANA;
            }
            else
            {
                edrk.to_zadat4ik.APL_LAMS0.bits.PCH2_MESTNOE = edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_MESTNOE;
                edrk.to_zadat4ik.APL_LAMS0.bits.PCH2_PODKLU4EN = edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_PODKLU4EN;
                edrk.to_zadat4ik.APL_LAMS0.bits.PCH2_READY1 = edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_READY1;
                edrk.to_zadat4ik.APL_LAMS0.bits.PCH2_SHEMA_SOBRANA = edrk.to_zadat4ik.APL_LAMS_PCH.bits.PCH_SHEMA_SOBRANA;
            }


        //  edrk.to_zadat4ik.APL_LAMS0.bits0.GED_PEREGRUZ = 0;
        //  edrk.to_zadat4ik.APL_LAMS0.bits0.PROVOROT = 0;





            if (control_station.active_control_station[CONTROL_STATION_INGETEAM_PULT_RS485])
            {
                edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_ZADAT = 0;
                edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_MONITOR = 0;
                edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_SVU = 0;
                edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_VPU = 0;
        //       edrk.to_zadat4ik.APL_LAMS0.bits.WORK_PMU = 0;


            }
            else // control_station.active_control_station[CONTROL_STATION_INGETEAM_PULT_RS485] == 0//edrk.RemouteFromDISPLAY==0
            {
                if (edrk.from_shema.bits.SVU==0)
                {
                 edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_VPU = 0;
                 if (edrk.from_shema.bits.ZADA_DISPLAY)
                 {
                   edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_MONITOR = 1;
                   edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_ZADAT = 0;
                 }
                 else
                 {
                   edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_MONITOR = 0;
                   edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_ZADAT = 1;
                 }
                }
                else // SVU==1
                {
                   edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_MONITOR = 0;
                   edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_ZADAT = 0;
                }

                if (edrk.from_shema.bits.SVU)
                {

                     if (edrk.from_vpu.bits.ACTIVE)
                     {
                         edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_VPU = 1;
                         edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_SVU = 0;
                     }
                     else
                     {
                         edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_SVU = 1;
                         edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_VPU = 0;
                     }

                }
                else //edrk.from_shema.bits.SVU == 0
                {
                     edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_SVU = 0;
                     edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_VPU = 0;
                }
            }


            edrk.to_zadat4ik.APL_LAMS0.bits.HOD = edrk.Go;
            edrk.to_zadat4ik.APL_LAMS0.bits.PCH1_PCH2_SYNC = sync_data.sync_ready;

        //  if (edrk.from_zadat4ik.bits.PROVOROT)
        //    edrk.to_zadat4ik.APL_LAMS0.bits.PROVOROT = 1;
        //  else
        //    edrk.to_zadat4ik.APL_LAMS0.bits.PROVOROT = 0;

            edrk.to_zadat4ik.BIG_LAMS.bits.AVARIA = edrk.to_ing.bits.SMALL_LAMPA_AVARIA;


}

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

//#define koef_P_Water_filter 1600000 //0.095367431640625
void calc_p_water_edrk(void)
{
    _iq iqtain,iq_temp;
    static _iq koef_P_Water_filter = _IQ (0.1/2.0); // 5 сек фильтр

    edrk.p_water_edrk.adc_p_water[0]  = ADC_f[1][14];

	edrk.p_water_edrk.real_p_water[0] = (_IQtoF(analog.P_Water_internal) * NORMA_ACP_P - 4.0) / 1.6;
    edrk.p_water_edrk.real_int_p_water[0] = edrk.p_water_edrk.real_p_water[0] * K_P_WATER_TO_SVU;


    iqtain = _IQ(edrk.p_water_edrk.real_p_water[0]/100.0);
    iq_temp = _IQ(edrk.p_water_edrk.filter_real_p_water[0]/100.0);

    if (edrk.p_water_edrk.flag_init_filter_temp[0]==0)
    {
      iq_temp = iqtain;
      edrk.p_water_edrk.flag_init_filter_temp[0]=1;
    }

//  iq_temp_engine[i] = exp_regul_iq(koef_Temper_ENGINE_filter, iq_temp_engine[i], iqtain);

    iq_temp +=  _IQmpy( (iqtain-iq_temp),  koef_P_Water_filter);
    edrk.p_water_edrk.filter_real_p_water[0] = _IQtoF(iq_temp)*100.0;
    edrk.p_water_edrk.filter_real_int_p_water[0] = edrk.p_water_edrk.filter_real_p_water[0]*K_P_WATER_TO_SVU;



}

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


void edrk_init(void)
{

    edrk.Uzad_max = _IQ(K_STATOR_MAX); // макс амплитуда в Км для минимального импульса = DEF_PERIOD_MIN_MKS
    edrk.iq_bpsi_normal = _IQ(BPSI_NORMAL/NORMA_FROTOR);
//    edrk.iq_f_provorot = _IQ(F_PROVOROT/NORMA_FROTOR);

    init_simple_scalar();

    edrk.flag_enable_update_hmi = 1;

}

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



unsigned int filter_err_count(unsigned int *counter, unsigned int max_errors, unsigned int err, unsigned int cmd)
{
    if (cmd==1)
    {
        (*counter) = 0;
        return 0;
    }

    if (err)
    {
       if ((*counter)>=max_errors)
          return 1;
       else
           (*counter)++;

       return 0;
    }

    if (err==0)
    {
       if ((*counter)==0)
          return 0;
       else
           (*counter)--;

       return 0;
    }
    return 0;
}

//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
#define MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS          30//20
#define MAX_WAIT_READY1_DETECT_ALIVE_ANOTHER_BS      100
#define MAX_WAIT_READY2_DETECT_ALIVE_ANOTHER_BS      70 //30 // должен быть больше чем MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
void detect_alive_another_bs(void)
{
 //   static unsigned int count_wait_ready = 0;
    static unsigned int prev_another_bs_maybe_on = 0;
    static unsigned int prev_another_bs_maybe_on_after_ready1 = 0;


    edrk.ms.err_signals.alive_can_to_another_bs = CAN_timeout[get_real_in_mbox(UNITS_TYPE_BOX,ANOTHER_BSU1_CAN_DEVICE)];
    edrk.ms.err_signals.alive_opt_bus_read      = !project.cds_tk[3].optical_data_in.ready;
    edrk.ms.err_signals.alive_opt_bus_write     = !project.cds_tk[3].optical_data_out.ready;
    edrk.ms.err_signals.alive_sync_line         = !sync_data.global_flag_sync_1_2;
    edrk.ms.err_signals.alive_sync_line_local   = !sync_data.local_flag_sync_1_2;
//    edrk.ms.err_signals.input_alarm_another_bs  = edrk.from_ing1.bits.
    // тут пока отключен канал.
 //   edrk.ms.err_signals.fast_optical_alarm      = 0;//!project.cds_tk[3].read.sbus.status_tk_40pin.bit.tk5_ack;
    edrk.ms.err_signals.another_rascepitel      = edrk.from_second_pch.bits.RASCEPITEL;

    if (edrk.ms.err_signals.alive_can_to_another_bs
            && (edrk.ms.err_signals.alive_opt_bus_read
            || edrk.ms.err_signals.alive_opt_bus_write)
            && edrk.ms.err_signals.alive_sync_line
//            && edrk.ms.err_signals.fast_optical_alarm
            )
    {
        edrk.ms.another_bs_maybe_off = 1;
        edrk.ms.another_bs_maybe_on = 0;
    }
    else
    {
        edrk.ms.another_bs_maybe_off = 0;
        edrk.ms.another_bs_maybe_on = 1;
    }

    // если связь восстановилась, то опять ждем некоторое время пока запустятся все остальные каналы связи.
    if (prev_another_bs_maybe_on!=edrk.ms.another_bs_maybe_on && edrk.ms.another_bs_maybe_on)
    {
//        edrk.ms.count_time_wait_ready1 = 0;
        edrk.ms.count_time_wait_ready2 = 0;
        prev_another_bs_maybe_on_after_ready1 = 0;
        clear_errors_master_slave();
    }


    //
    // выставляем флаг только через время MAX_WAIT_READY_DETECT_ALIVE_ANOTHER_BS
    //
    edrk.ms.ready1 = filter_err_count(&edrk.ms.count_time_wait_ready1,
                               MAX_WAIT_READY1_DETECT_ALIVE_ANOTHER_BS,
                               1,
                               0);

    if (edrk.Status_Ready.bits.ready5)
    {
        edrk.ms.ready2 = filter_err_count(&edrk.ms.count_time_wait_ready2,
                                       MAX_WAIT_READY2_DETECT_ALIVE_ANOTHER_BS,
                                       1,
                                       0);
    }
    else
    {
        edrk.ms.count_time_wait_ready2 = 0;
        edrk.ms.ready2 = 0;
    }

//    edrk.ms.ready2 = edrk.Status_Ready.bits.ready5 && filter_err_count(&edrk.ms.count_time_wait_ready2,
//                               MAX_WAIT_READY2_DETECT_ALIVE_ANOTHER_BS,
//                               1,
//                               0);





    prev_another_bs_maybe_on = edrk.ms.another_bs_maybe_on;


    // ждем пока пройдет некоторое время
    if (edrk.ms.ready1==0)
    {


        edrk.ms.status = 1;
        return;
    }


    // если связь была после edrk.ms.ready1==1, но вся пропала, даем ошибку
    if (prev_another_bs_maybe_on_after_ready1!=edrk.ms.another_bs_maybe_on && edrk.ms.another_bs_maybe_on==0)
    {
        edrk.errors.e4.bits.ANOTHER_BS_POWER_OFF |= 1;
    }
    prev_another_bs_maybe_on_after_ready1 = edrk.ms.another_bs_maybe_on;




    edrk.ms.err_lock_signals.alive_can_to_another_bs |= filter_err_count(&edrk.ms.errors_count.alive_can_to_another_bs,
                                                                        MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS,
                                                                        edrk.ms.err_signals.alive_can_to_another_bs,
                                                                        0);

    edrk.ms.err_lock_signals.alive_opt_bus_read |= filter_err_count(&edrk.ms.errors_count.alive_opt_bus_read,
                                                                        MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS,
                                                                        edrk.ms.err_signals.alive_opt_bus_read,
                                                                        0);
    edrk.ms.err_lock_signals.alive_opt_bus_write |= filter_err_count(&edrk.ms.errors_count.alive_opt_bus_write,
                                                                        MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS,
                                                                        edrk.ms.err_signals.alive_opt_bus_write,
                                                                        0);

    edrk.ms.err_lock_signals.alive_sync_line = filter_err_count(&edrk.ms.errors_count.alive_sync_line,
                                                                        MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS,
                                                                        edrk.ms.err_signals.alive_sync_line,
                                                                        0);

    edrk.ms.err_lock_signals.alive_sync_line_local = filter_err_count(&edrk.ms.errors_count.alive_sync_line_local,
                                                                        MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS,
                                                                        edrk.ms.err_signals.alive_sync_line_local,
                                                                        0);

    edrk.ms.err_lock_signals.fast_optical_alarm |= filter_err_count(&edrk.ms.errors_count.fast_optical_alarm,
                                                                        MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS,
                                                                        edrk.ms.err_signals.fast_optical_alarm,
                                                                        0);

    edrk.ms.err_lock_signals.input_alarm_another_bs |= filter_err_count(&edrk.ms.errors_count.input_alarm_another_bs,
                                                                        MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS,
                                                                        edrk.ms.err_signals.input_alarm_another_bs,
                                                                        0);

    edrk.ms.err_lock_signals.another_rascepitel |= filter_err_count(&edrk.ms.errors_count.another_rascepitel,
                                                                        MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS,
                                                                        edrk.ms.err_signals.another_rascepitel,
                                                                        0);

    edrk.ms.err_lock_signals.input_master_slave |= filter_err_count(&edrk.ms.errors_count.input_master_slave,
                                                                        MAX_ERRORS_DETECT_ALIVE_ANOTHER_BS,
                                                                        edrk.ms.err_signals.input_master_slave,
                                                                        0);


    if (edrk.ms.err_signals.alive_can_to_another_bs
            && (edrk.ms.err_signals.alive_opt_bus_read
            || edrk.ms.err_signals.alive_opt_bus_write)
            && edrk.ms.err_signals.alive_sync_line
  //          && edrk.ms.err_signals.fast_optical_alarm
 //         &&  edrk.ms.err_signals.input_alarm_another_bs &&
//            && edrk.ms.err_signals.another_rascepitel == 0
//            && edrk.ms.err_signals.input_master_slave
            )
    {

        if (edrk.ms.err_signals.another_rascepitel)
            edrk.errors.e7.bits.ANOTHER_RASCEPITEL_ON |= 1;

//        edrk.ms.another_bs_maybe_off = 1;
//        edrk.ms.another_bs_maybe_on = 0;

        edrk.warnings.e4.bits.ANOTHER_BS_POWER_OFF = 1;
  //      edrk.warnings.e4.bits.FAST_OPTICAL_ALARM = 1;
        edrk.warnings.e7.bits.MASTER_SLAVE_SYNC = 1;
        edrk.warnings.e7.bits.READ_OPTBUS = edrk.ms.err_signals.alive_opt_bus_read;
        edrk.warnings.e7.bits.WRITE_OPTBUS = edrk.ms.err_signals.alive_opt_bus_write;
        edrk.warnings.e7.bits.CAN2CAN_BS = 1;

        edrk.ms.status = 2;

    }
    else
    {

        edrk.warnings.e4.bits.ANOTHER_BS_POWER_OFF = 0;

//
        if (edrk.ms.err_lock_signals.alive_can_to_another_bs)
            edrk.errors.e7.bits.CAN2CAN_BS |= 1;
        else
            edrk.warnings.e7.bits.CAN2CAN_BS = 0;
//
        if (edrk.ms.err_lock_signals.alive_opt_bus_read)
            edrk.errors.e7.bits.READ_OPTBUS |= 1;
        else
            edrk.warnings.e7.bits.READ_OPTBUS = 0;
//
        if (edrk.ms.err_lock_signals.alive_opt_bus_write)
            edrk.errors.e7.bits.WRITE_OPTBUS |= 1;
        else
            edrk.warnings.e7.bits.WRITE_OPTBUS = 0;
//
        if (edrk.ms.err_lock_signals.alive_sync_line)
            edrk.warnings.e7.bits.MASTER_SLAVE_SYNC = 1;
        else
            edrk.warnings.e7.bits.MASTER_SLAVE_SYNC = 0;
//
//        if (edrk.ms.err_lock_signals.fast_optical_alarm)
//            edrk.errors.e4.bits.FAST_OPTICAL_ALARM |= 1;
//        else
//            edrk.warnings.e4.bits.FAST_OPTICAL_ALARM = 0;


 //       edrk.ms.another_bs_maybe_on = 1;
 //       edrk.ms.another_bs_maybe_off = 0;

        if (edrk.ms.err_signals.alive_can_to_another_bs
                    || edrk.ms.err_signals.alive_opt_bus_read
                    || edrk.ms.err_signals.alive_opt_bus_write
                    || edrk.ms.err_signals.alive_sync_line
                    || edrk.ms.err_signals.fast_optical_alarm
                    )
            edrk.ms.status = 3;
        else
            edrk.ms.status = 4;

    }





}

//////////////////////////////////////////////////////////
unsigned int wait_synhro_optical_bus(void)
{
    static unsigned int cmd = 0;
    static unsigned int count_wait_synhro = 0;


//
//    switch(cmd)
//    {
//      0 :    if (optical_read_data.data.cmd.bit.wdog_tick == 0)
//                cmd = 1;
//
//            break;
//
//      1 :   optical_write_data.data.cmd.bit.wdog_tick = 1;
//            break;
//
//
//      default: break
//    }



    return 0;
}

//////////////////////////////////////////////////////////
void clear_wait_synhro_optical_bus(void)
{

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

}
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
#define MAX_COUNT_TRY_MASTER_BS1    200//40 //15  //5
#define MAX_COUNT_TRY_MASTER_BS2    100//40 //15 //40  //20
#define MAX_COUNT_WAIT_ANSWER_CONFIRM_MODE    20

#define MAX_COUNT_WAIT_SLAVE_TRY_MASTER 100


#define SIZE_LOG_MASTER_SLAVE_STATUS   50
#pragma DATA_SECTION(buf_log_master_slave_status,".slow_vars");
unsigned int buf_log_master_slave_status[SIZE_LOG_MASTER_SLAVE_STATUS] = {0};
//AUTO_MASTER_SLAVE_DATA buf2[SIZE_BUF1] = {0};
//AUTO_MASTER_SLAVE_DATA buf3[SIZE_BUF1] = {0};
//OPTICAL_BUS_DATA_LOW_CMD buf4[SIZE_BUF1] = {0};
//OPTICAL_BUS_DATA_LOW_CMD buf5[SIZE_BUF1] = {0};


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

void auto_select_master_slave(void)
{
    static unsigned int count_try_master = 0;
    static unsigned int count_wait_answer_confirm_mode = 0;
    static unsigned int count_wait_slave_try_master = 0;
    unsigned int err_confirm_mode = 0; // ошибка подтверждения режима другим ПЧ
    static unsigned int c_buf_log_master_slave_status = 0, prev_status = 0;



// logs master_slave_status
    if (edrk.auto_master_slave.status != prev_status)
    {
        c_buf_log_master_slave_status++;
        if (c_buf_log_master_slave_status>=SIZE_LOG_MASTER_SLAVE_STATUS)
            c_buf_log_master_slave_status = 0;
        buf_log_master_slave_status[c_buf_log_master_slave_status] = edrk.auto_master_slave.status;
    }
    prev_status = edrk.auto_master_slave.status;
//end logs master_slave_status

    if (edrk.ms.ready2==0 && edrk.errors.e7.bits.AUTO_SET_MASTER==0)
    {
        edrk.auto_master_slave.remoute.all = 0;
        edrk.auto_master_slave.local.all = 0;
        edrk.auto_master_slave.prev_remoute.all = edrk.auto_master_slave.remoute.all;
        edrk.auto_master_slave.prev_local.all = edrk.auto_master_slave.local.all;

        edrk.auto_master_slave.status = 1;

//        if (prev_ready!=edrk.ms.ready2)
//            for (c_buf=0;c_buf<SIZE_BUF1;c_buf++)
//            {
//                buf2[c_buf].all = buf3[c_buf].all = buf1[c_buf] = buf4[c_buf].all = buf5[c_buf].all =0;
//            }
//
//        c_buf = 0;
//
//        prev_ready = edrk.ms.ready2;
        clear_wait_synhro_optical_bus();


        return;
    }
//    else
//        prev_ready = edrk.ms.ready2;


    if (edrk.errors.e7.bits.AUTO_SET_MASTER)
    {
        edrk.to_second_pch.bits.MASTER = edrk.auto_master_slave.local.bits.master;

        edrk.auto_master_slave.local.bits.master = 0;
        edrk.auto_master_slave.local.bits.slave  = 0;
        edrk.auto_master_slave.local.bits.try_master = 0;
        edrk.auto_master_slave.local.bits.try_slave = 0;
        edrk.auto_master_slave.local.bits.nothing = 1;


//        edrk.auto_master_slave.prev_remoute.all = edrk.auto_master_slave.remoute.all;
//        edrk.auto_master_slave.prev_local.all = edrk.auto_master_slave.local.all;

 //       edrk.auto_master_slave.status = 10;


        return;
    }

    edrk.auto_master_slave.prev_status = edrk.auto_master_slave.status;

//    c_buf++;
//    if (c_buf>=SIZE_BUF1)
//        c_buf = 0;
//
//    buf1[c_buf] = edrk.auto_master_slave.status;
//    buf2[c_buf].all = edrk.auto_master_slave.local.all;
//    buf3[c_buf].all = edrk.auto_master_slave.remoute.all;
//    buf4[c_buf].all = optical_read_data.data.cmd.all;
//    buf5[c_buf].all = optical_write_data.data.cmd.all;
//

    // сбросим счетчик времени перехода на мастер
    if (edrk.auto_master_slave.local.bits.try_master==0 ||
         (edrk.auto_master_slave.prev_local.bits.try_master != edrk.auto_master_slave.local.bits.try_master && edrk.auto_master_slave.local.bits.try_master==1))
        count_try_master = 0;

    // если шина OPTICAL_BUS сдохла, выходим
    if (edrk.errors.e7.bits.WRITE_OPTBUS==1 || edrk.errors.e7.bits.READ_OPTBUS==1 ||
            edrk.warnings.e7.bits.WRITE_OPTBUS==1 || edrk.warnings.e7.bits.READ_OPTBUS==1)
    {

        if (edrk.errors.e7.bits.WRITE_OPTBUS==1 || edrk.errors.e7.bits.READ_OPTBUS==1)
        {
            // шина не работает, и тот ПЧ включен
            // значит что-то случилось - выключаемся

            edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;

            edrk.auto_master_slave.remoute.bits.nothing = 1;
            edrk.auto_master_slave.remoute.bits.master  = 0;
            edrk.auto_master_slave.remoute.bits.slave   = 0;
            edrk.auto_master_slave.remoute.bits.try_master = 0;
            edrk.auto_master_slave.remoute.bits.try_slave = 0;


            edrk.auto_master_slave.local.bits.master = 0;
            edrk.auto_master_slave.local.bits.slave  = 0;
            edrk.auto_master_slave.local.bits.try_master = 0;
            edrk.auto_master_slave.local.bits.try_slave = 0;
            edrk.auto_master_slave.local.bits.nothing = 1;

            edrk.auto_master_slave.status = 10;
        }
        else
        {
            // шина не работает, и тот ПЧ выключен
            // значит мы сразу мастер
            edrk.warnings.e7.bits.AUTO_SET_MASTER = 1;

            edrk.auto_master_slave.remoute.bits.nothing = 1;
            edrk.auto_master_slave.remoute.bits.master  = 0;
            edrk.auto_master_slave.remoute.bits.slave   = 0;
            edrk.auto_master_slave.remoute.bits.try_master = 0;
            edrk.auto_master_slave.remoute.bits.try_slave = 0;



            edrk.auto_master_slave.local.bits.master = 1;
            edrk.auto_master_slave.local.bits.slave  = 0;
            edrk.auto_master_slave.local.bits.try_master = 0;
            edrk.auto_master_slave.local.bits.try_slave = 0;
            edrk.auto_master_slave.local.bits.nothing = 1;

            edrk.auto_master_slave.status = 2;
        }

        edrk.auto_master_slave.remoute.bits.sync_line_detect = 0;
        edrk.auto_master_slave.remoute.bits.bus_off = 1;
        edrk.auto_master_slave.remoute.bits.sync1_2 = 0;

    }
    else
    {
        edrk.warnings.e7.bits.AUTO_SET_MASTER = 0;

        edrk.auto_master_slave.remoute.bits.bus_off = 0;

        // синхронизируем свои программы через OPTICAL_BUS

        if (wait_synhro_optical_bus()==1)
        {

            edrk.auto_master_slave.status = 50; // wait synhro


        }
        else
        {


            edrk.auto_master_slave.remoute.bits.master = optical_read_data.data.cmd.bit.master;
            edrk.auto_master_slave.remoute.bits.slave = optical_read_data.data.cmd.bit.slave;
            edrk.auto_master_slave.remoute.bits.try_master = optical_read_data.data.cmd.bit.maybe_master;
            edrk.auto_master_slave.remoute.bits.sync1_2 = optical_read_data.data.cmd.bit.sync_1_2;
            edrk.auto_master_slave.remoute.bits.sync_line_detect = optical_read_data.data.cmd.bit.sync_line_detect;
            edrk.auto_master_slave.remoute.bits.tick = optical_read_data.data.cmd.bit.wdog_tick;

            if (optical_read_data.data.cmd.bit.master==0 && optical_read_data.data.cmd.bit.slave==0)
               edrk.auto_master_slave.remoute.bits.nothing = 1;


           //////////////////////////////////////////////////
           //////////////////////////////////////////////////
           // 1

           // тот ПЧ уже мастер
           if (edrk.auto_master_slave.remoute.bits.master)
           {

               // и этот ПЧ мастер почему-то?
               if (edrk.auto_master_slave.local.bits.master)
               {
                   edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;
                   edrk.auto_master_slave.status = 3;
               }
               else
               {
               // этот ПЧ еще не определился, поэтому переход на slave
                if (edrk.auto_master_slave.local.bits.master==0 && edrk.auto_master_slave.local.bits.slave==0)
                {
        //           edrk.auto_master_slave.local.bits.try_slave = 1;
                   // стали slave
                   edrk.auto_master_slave.local.bits.slave = 1;
                   // сняли свой запрос на мастера если он был
                   edrk.auto_master_slave.local.bits.try_master = 0;
                   edrk.auto_master_slave.status = 4;
                }
                else
                {
                    edrk.auto_master_slave.status = 21;
                }
               }
           }
           else
           //////////////////////////////////////////////////
           //////////////////////////////////////////////////
           // 2
           // тот ПЧ уже slave

           if (edrk.auto_master_slave.remoute.bits.slave)
           {

               // и этот ПЧ slave почему-то?
               if (edrk.auto_master_slave.local.bits.slave)
               {

                   // был переход из мастер в slave
                   if (edrk.auto_master_slave.prev_remoute.bits.slave==0)
                   {
                      if (edrk.Go)
                      {
                          // запущен ШИМ
                          edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;
                          edrk.auto_master_slave.status = 5;
                      }
                      else
                      {
                          // пробуем перехватить master
                          edrk.auto_master_slave.local.bits.try_master = 1;
                          edrk.auto_master_slave.status = 6;
                      }
                   }
                   else
                   {
                      edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;
                      edrk.auto_master_slave.status = 7;
                   }

               }
               else
               {

               // этот ПЧ еще не определился, поэтому запрашивает на master
                if (edrk.auto_master_slave.local.bits.master==0 && edrk.auto_master_slave.local.bits.slave==0 && edrk.auto_master_slave.local.bits.try_master==0)
                {
                    if (edrk.flag_second_PCH==0)
                        edrk.auto_master_slave.local.bits.try_master = 1;
                    if (edrk.flag_second_PCH==1)
                        edrk.auto_master_slave.local.bits.try_master = 1;

                    edrk.auto_master_slave.status = 8;
    //               edrk.auto_master_slave.local.bits.slave = 1;
                }
                else
                // этот ПЧ уже в запросе на мастер, а тот ПЧ подтвердил в slave что он не против.
                if (edrk.auto_master_slave.local.bits.master==0 && edrk.auto_master_slave.local.bits.slave==0 && edrk.auto_master_slave.local.bits.try_master==1)
                {
                    // стали мастером
                   edrk.auto_master_slave.local.bits.master = 1;
                   edrk.auto_master_slave.local.bits.try_master = 0;
                   edrk.auto_master_slave.status = 9;
    //               edrk.auto_master_slave.local.bits.slave = 1;
                }
                else
                {
                    edrk.auto_master_slave.status = 22;
                }

               }
           }
           else
           //////////////////////////////////////////////////
           //////////////////////////////////////////////////
           // 3
           // тот ПЧ запрашивает переход на мастер

           if (edrk.auto_master_slave.remoute.bits.master==0
               && edrk.auto_master_slave.remoute.bits.slave==0
               && edrk.auto_master_slave.remoute.bits.try_master)
           {
               // а этот ПЧ slave
               if (edrk.auto_master_slave.local.bits.slave)
               {
                   // вроде не норм, остаемся slave
                   // тут надо подождать некотрое время, пока тот ПЧ не поймет что мы стали слейвом и перейдет из try_master в мастер
                   if (count_wait_slave_try_master<MAX_COUNT_WAIT_SLAVE_TRY_MASTER)
                       count_wait_slave_try_master++;
                   else
                   {
                    edrk.auto_master_slave.status = 10;
                    edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;
                   }
               }
               else
               // а этот ПЧ master
               if (edrk.auto_master_slave.local.bits.master)
               {
                   // тут мы должны принять решение отдавать ли свой мастер другому ПЧ?
                   // пока выставим ошибку
                   edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;
                   edrk.auto_master_slave.status = 11;
               }
               else
               // этот ПЧ не мастер и не слейв и нет запросов от него на мастер
               if (edrk.auto_master_slave.local.bits.master==0 && edrk.auto_master_slave.local.bits.slave==0 && edrk.auto_master_slave.local.bits.try_master==0)
               {
                   // становимся slave
                   edrk.auto_master_slave.local.bits.slave = 1;
                   edrk.auto_master_slave.status = 12;
                   count_wait_slave_try_master = 0; // обнулим счетчик, т.к. нас надо чтоб тот ПЧ понял что мы стали slave
               }
               else
               // этот ПЧ не мастер и не слейв и есть запрос от него на мастер, т.е. оба ПЧ хотят быть мастерами
               if (edrk.auto_master_slave.local.bits.master==0 && edrk.auto_master_slave.local.bits.slave==0 && edrk.auto_master_slave.local.bits.try_master==1)
               {

                   // становимся master через некоторое время (для каждого ПЧ время разное)
                   if (edrk.flag_second_PCH==0)
                   {
                       //оба хотят, но приотритет даем всегда первому
                       edrk.auto_master_slave.local.bits.master = 1;
                       edrk.auto_master_slave.local.bits.try_master = 0;

    //                 if (count_try_master<MAX_COUNT_TRY_MASTER_BS1)
    //                     count_try_master++;
    //                 else
    //                     edrk.auto_master_slave.local.bits.master = 1;
                   }

                   if (edrk.flag_second_PCH==1)
                   {
                       //оба хотят, но приотритет даем всегда первому

                       edrk.auto_master_slave.local.bits.slave = 1;
                       edrk.auto_master_slave.local.bits.try_master = 0;

    //                 if (count_try_master<MAX_COUNT_TRY_MASTER_BS2)
    //                     count_try_master++;
    //                 else
    //                     edrk.auto_master_slave.local.bits.master = 1;
                   }
                   edrk.auto_master_slave.status = 13;
               }
               else
               {
                   edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;
                   edrk.auto_master_slave.status = 100;
               }


           }
           else
           //////////////////////////////////////////////////
           //////////////////////////////////////////////////
           // 4
           // этот ПЧ запрашивает переход на мастер

           if (edrk.auto_master_slave.local.bits.master==0
                      && edrk.auto_master_slave.local.bits.slave==0
                      && edrk.auto_master_slave.local.bits.try_master)
           {
               // становимся master через некоторое время (для каждого ПЧ время разное)
               if (edrk.flag_second_PCH==0)
               {
                 if (count_try_master<MAX_COUNT_TRY_MASTER_BS1)
                 {
                     count_try_master++;
                     edrk.auto_master_slave.status = 14;
                 }
                 else
                 {
                     edrk.auto_master_slave.local.bits.master = 1;
                     edrk.auto_master_slave.local.bits.try_master = 0;
                     edrk.auto_master_slave.status = 15;

                 }
               }

               if (edrk.flag_second_PCH==1)
               {
                 if (count_try_master<MAX_COUNT_TRY_MASTER_BS2)
                 {
                     count_try_master++;
                     edrk.auto_master_slave.status = 14;
                 }
                 else
                 {
                     edrk.auto_master_slave.local.bits.master = 1;
                     edrk.auto_master_slave.local.bits.try_master = 0;
                     edrk.auto_master_slave.status = 15;
                 }
               }



           }
           else
           //////////////////////////////////////////////////
           //////////////////////////////////////////////////
           // 5
           // тот ПЧ ничего не делает

           if (edrk.auto_master_slave.remoute.bits.master==0 && edrk.auto_master_slave.remoute.bits.slave==0 && edrk.auto_master_slave.remoute.bits.try_master==0)
           {
               // а этот ПЧ slave
               if (edrk.auto_master_slave.local.bits.slave)
               {
                   // были в слейве, а тот ПЧ почему-то потерял режим - ошибка или попытка захвата мастера!
                   if (edrk.auto_master_slave.prev_remoute.bits.master)
                   {
                       if (edrk.Go) // при ШИМе вырубаемся.
                       {
                           edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;
                           edrk.auto_master_slave.status = 24;

                       }
                       else
                       {
                         // а тут все ок.
                         edrk.auto_master_slave.local.bits.slave = 0;
                         edrk.auto_master_slave.local.bits.master = 1;

                         edrk.auto_master_slave.status = 23;
                       }
                   }
                   else
                   {
                        edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;
                        edrk.auto_master_slave.status = 16;
                   }
               }
               else
               // а этот ПЧ master
               if (edrk.auto_master_slave.local.bits.master)
               {
                   // тут мы остемся мастером вроде?
                   // но тот ПЧ не подтвердил переход, он должен стать мастером или слейвом
                   err_confirm_mode = 0;
//                   filter_err_count(&count_wait_answer_confirm_mode,
//                                                       MAX_COUNT_WAIT_ANSWER_CONFIRM_MODE,
//                                                       1,
//                                                       0);


                   if (err_confirm_mode)
                   {
                       // мы мастер, но тот ПЧ так и не понял это
                       edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;
                       edrk.auto_master_slave.status = 20;
                   }
                   else
                       edrk.auto_master_slave.status = 17;

               }
               else
               {
                   // тут пытаемся захватить мастер
                   if (edrk.flag_second_PCH==0)
                       edrk.auto_master_slave.local.bits.try_master = 1;
                   if (edrk.flag_second_PCH==1)
                       edrk.auto_master_slave.local.bits.try_master = 1;
                   edrk.auto_master_slave.status = 18;
               }


           }
           else
           //////////////////////////////////////////////////
           //////////////////////////////////////////////////
           // 5
           //
           {
               // что-то пошло не так
               edrk.errors.e7.bits.AUTO_SET_MASTER |= 1;
               edrk.auto_master_slave.status = 19;

           }
           //////////////////////////////////////////////////
           //////////////////////////////////////////////////
           // 6
           //

           //////////////////////////////////////////////////
           //////////////////////////////////////////////////
           // 7
           //

           //////////////////////////////////////////////////
           //////////////////////////////////////////////////
           // 8
           //
        }
    }





//    optical_write_data.cmd.bit. = edrk.auto_master_slave.local.bits.slave;



    edrk.to_second_pch.bits.MASTER = edrk.auto_master_slave.local.bits.master;

    edrk.auto_master_slave.prev_remoute.all = edrk.auto_master_slave.remoute.all;
    edrk.auto_master_slave.prev_local.all = edrk.auto_master_slave.local.all;

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

void clear_errors_master_slave(void)
{

//    if (edrk.errors.e7.bits.AUTO_SET_MASTER)
    {

//    if (edrk.errors.e7.bits.MASTER_SLAVE_SYNC
//            || edrk.errors.e1.bits.NO_INPUT_SYNC_SIGNAL)
//      edrk.ms.count_time_wait_ready1 = 0;

    edrk.ms.count_time_wait_ready2 = 0;

    edrk.ms.errors_count.alive_can_to_another_bs = 0;
    edrk.ms.errors_count.alive_opt_bus_read = 0;
    edrk.ms.errors_count.alive_opt_bus_write = 0;
    edrk.ms.errors_count.alive_sync_line = 0;
    edrk.ms.errors_count.alive_sync_line_local = 0;
    edrk.ms.errors_count.another_rascepitel = 0;
    edrk.ms.errors_count.fast_optical_alarm = 0;
    edrk.ms.errors_count.input_alarm_another_bs = 0;
    edrk.ms.errors_count.input_master_slave = 0;

    edrk.ms.err_lock_signals.alive_can_to_another_bs = 0;
    edrk.ms.err_lock_signals.alive_opt_bus_read = 0;
    edrk.ms.err_lock_signals.alive_opt_bus_write = 0;
    edrk.ms.err_lock_signals.alive_sync_line = 0;
    edrk.ms.err_lock_signals.alive_sync_line_local = 0;
    edrk.ms.err_lock_signals.another_rascepitel = 0;
    edrk.ms.err_lock_signals.fast_optical_alarm = 0;
    edrk.ms.err_lock_signals.input_alarm_another_bs = 0;
    edrk.ms.err_lock_signals.input_master_slave = 0;

    }

}

//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
void who_select_sync_signal(void)
{

//    if (optical_read_data.status == 1)
        sync_data.global_flag_sync_1_2 = (sync_data.local_flag_sync_1_2 || optical_read_data.data.cmd.bit.sync_1_2);
//    else
 //       sync_data.global_flag_sync_1_2 = (sync_data.local_flag_sync_1_2);


    if (sync_data.timeout_sync_signal && optical_read_data.data.cmd.bit.sync_line_detect)
    {
        // этот БС не принимает синхро, а второй принимает, значит на этом отключаем синхронизацию
        // синхронизируется тот борт сам.

        sync_data.enable_do_sync = 0;

        return;
    }

    if (sync_data.timeout_sync_signal==0 && optical_read_data.data.cmd.bit.sync_line_detect==0)
    {
        // этот БС принимает синхро, а второй не принимает, значит на этом принудительно включаем синхронизацию
        // синхронизируется этот борт сам.

        sync_data.enable_do_sync = 1;

        return;
    }

    if (sync_data.sync_ready && sync_data.timeout_sync_signal==0 && optical_read_data.data.cmd.bit.sync_line_detect)
    {


        if (optical_read_data.data.cmd.bit.sync_1_2 && sync_data.enable_do_sync==0)
        {
            // уже есть синхрон, другой БС смог это сделать и он сам это сделал

        }
        else
        if (optical_read_data.data.cmd.bit.sync_1_2 && sync_data.enable_do_sync==1)
        {
            // уже есть синхрон, другой БС смог это сделать и он не сам это сделал, а от нас

        }
        else
        {
        // нет синхронизации, значит выбираем кто это будет делать в автомате
        // этот БС принимает синхро и второй принимает, значит синхронизация
        // выбирается в зависимости от номера БС.
            if (edrk.flag_second_PCH==0)
               sync_data.enable_do_sync = 1;
            else
                sync_data.enable_do_sync = 0;
        }
        return;
    }

}

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



void edrk_init_variables(void) {
    unsigned int i = 0;
    int *pf = (int*)&f;
    for (i = 0; i < sizeof(f) / sizeof(int); i++) {
        *(pf + i) = 0;
    }

    edrk.flag_second_PCH = get_adr_pcb_controller();

    edrk.number_can_box_terminal_cmd = 1;
    edrk.number_can_box_terminal_oscil = 0;

/*    if (edrk.flag_second_PCH==0)
    {
      edrk.number_can_box_terminal_cmd = 1;
      edrk.number_can_box_terminal_oscil = 0;
    }
    else
    {
      edrk.number_can_box_terminal_cmd = 3;
      edrk.number_can_box_terminal_oscil = 2;
    }
*/

//  clear_all_i_phase();
    rotorInit();
    clear_table_remoute();
    initModbusTable();
    clear_modbus_table_in();
    clear_modbus_table_out();
//    init_global_time_struct(FREQ_PWM);
    fillLogArea();

    oscil_can.clear(&oscil_can);
    oscil_can.number_can_box_terminal_oscil = edrk.number_can_box_terminal_oscil;
    oscil_can.number_can_box_terminal_cmd   = edrk.number_can_box_terminal_cmd;


    control_station.clear(&control_station);

    init_detect_overloads();
    edrk_init();

    init_ramp_all_zadanie();
    init_analog_protect_levels();
    init_detect_overloads();
    init_50hz_input_net50hz();


    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_IZAD] = 500;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_KM]  = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_U_ZARYAD] = 820;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_K_U_DISBALANCE] = 200;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_K_PLUS_U_DISBALANCE] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_LIMIT_POWER] = 450;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_UFCONST_VECTOR] = 1;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SCALAR_FOC] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_ENABLE_ON_CHARGE] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_GO] = 1;

    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_DISABLE_ON_PUMP] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_ENABLE_ON_CHARGE] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_DISABLE_ON_QTV] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_DISABLE_ON_UMP] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_MANUAL_DISCHARGE] = 0;

    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_ROTOR_POWER] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_DISABLE_INTERRUPT_SYNC] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_DISABLE_INTERRUPT_TIMER2] = 0;



    init_Uin_rms();
}


//////////////////////////////////////////////////////////
void edrk_init_before_loop(void)
{
#if (MODE_DISABLE_ENABLE_WDOG==1)
    stop_wdog();
#else
    start_wdog();
#endif
}
//////////////////////////////////////////////////////////

#define FREQ_TIMER_3    (FREQ_PWM*2)

void edrk_init_before_main(void)
{
    static int f_cmd1 = 0;
    static int f_cmd2 = 0;
    static int f_cmd3 = 0;
    static int p_f_cmd1 = 0;
    static int p_f_cmd2 = 0;
    static int p_f_cmd3 = 0;


    volatile int final_code = 0;
    int i = 0, k = 0;

    setup_sync_line();
    edrk.disable_interrupt_sync = -1;

    edrk_init_variables();

////////////////////////////////////////
// global timer
////////////////////////////////////////
    init_global_time_struct(FREQ_TIMER_3);
    init_evb_timer3(FREQ_TIMER_3,&global_time_interrupt);
    start_evb_timer3();// run global_time_interrupt
///////////////////////////////////////

    /// для теста 2
/*
    while(1)
    {
       static int f_s_set = 0;
       static int f_s_read = 0;


       if (f_s_set)
           i_sync_pin_on();
       else
           i_sync_pin_off();

       f_s_read = get_status_sync_line();
    }
    */


/// для теста 1
/*
    project.enable_all_interrupt();

    //start_sync_interrupt();

    while(1)
    {
       static int f_s_set = 0;
       static int f_s_read = 0;


       if (f_s_set)
           i_sync_pin_on();
       else
           i_sync_pin_off();

       f_s_read = get_status_sync_line();

       if (f_cmd1 != p_f_cmd1)
       {
           if (f_cmd1)
           {
               start_evb_timer3();
           }
           else
           {
               stop_evb_timer3();
           }
           p_f_cmd1 = f_cmd1;
       }

       if (f_cmd2 != p_f_cmd2)
       {
           if (f_cmd2)
           {
               start_eva_timer2();
           }
           else
           {
               stop_eva_timer2();
           }
           p_f_cmd2 = f_cmd2;
       }

       if (f_cmd3 != p_f_cmd3)
       {
           if (f_cmd3)
           {
               start_sync_interrupt();
           }
           else
           {
               stop_sync_interrupt();
           }
           p_f_cmd3 = f_cmd3;
       }

    }
    /// конец теста
*/
    project.enable_all_interrupt();

    final_code = update_progress_load_hmi(1);

    project.disable_all_interrupt();

    InitXilinxSpartan2E(&PWM_interrupt);

    project.enable_all_interrupt();

    final_code = update_progress_load_hmi(2);

    init_can_box_between_bs1_bs2();

    initVectorControl();


/////////////////////////////
    if (edrk.flag_second_PCH==0)
        InitCan(CAN_BASE_ADR_UNITS_PCH_1, CAN_BASE_ADR_MPU_PCH_1, CAN_BASE_ADR_ALARM_LOG_PCH_1, CAN_BASE_ADR_TERMINAL_PCH_1);
    else
        InitCan(CAN_BASE_ADR_UNITS_PCH_2, CAN_BASE_ADR_MPU_PCH_2, CAN_BASE_ADR_ALARM_LOG_PCH_2, CAN_BASE_ADR_TERMINAL_PCH_2);
/////////////////////////////

    KickDog();

    clear_mem(FAST_LOG);

/*
    //TODO: remove (for test)
    logpar.start_write_fast_log = 1;

    for (k = 0; k < 7000; k++) {
        for (i = 0; i < 21; i++) {
            if (i==0)
//                write_to_mem(FAST_LOG, k);
            write_to_mem(FAST_LOG, 0);
            else
//                write_to_mem(FAST_LOG, 10 + i);
            write_to_mem(FAST_LOG, 0);
        }
        if (logpar.start_write_fast_log) {
            get_log_params_count();
            logpar.start_write_fast_log = 0;
        }
    }

    //END for test
*/

    //Init ADC
//  Init_Adc_Variables();
//  init_eva_timer2(1000, acp_Handler);

    final_code = update_progress_load_hmi(3);

/////////////////////////////////////////
    project.read_errors_controller(); // чтение ADR_ERRORS_TOTAL_INFO

    project.init();
//    project_prepare_config();

    final_code = update_progress_load_hmi(4);

//  initRotPlane();

//    project_prepare_config();
// Загрузка CDS, ADC, HWP и т.д.
    project.reload_all_plates_with_reset();
// поиск отключенных плат
  //  project.find_all_cds();

    project_prepare_config();
    project_run_init_all_plates();

    project.load_cfg_to_plates();

    project.clear_errors_all_plates();


    final_code = update_progress_load_hmi(5);

/////////////////////////////////////////////
    enable_er0_control();


    project.read_errors_controller();

    project_read_errors_controller(); // чтение ADR_ERRORS_TOTAL_INFO
    if(project.controller.read.errors.all || project.controller.read.errors_buses.all)
    {
        xerror(main_er_ID(3),(void *)0);
    }

    final_code = update_progress_load_hmi(6);

////////////////////////////////////////////
    project.reset_errors_controller();
    project.read_errors_controller();
    project.start_parallel_bus();
    project.read_errors_controller();
    project.reset_errors_controller();
    project.read_errors_controller();

    project.stop_parallel_bus();

    project.reset_errors_controller();
    project.read_errors_controller();

    project.start_parallel_bus();
    project.read_errors_controller();

    final_code = update_progress_load_hmi(7);
////////////////////////////////////////////////



#if (TMSPWMGEN==1)
    setup_pwm_out();// назначаем соответствующие ноги как выходы ШИМ
    setup_pwm_int(FREQ_PWM, 0 ,0);
#else //TMSPWMGEN

#if (XPWMGEN==1)
    InitXPWM(FREQ_PWM);
    stop_wdog();
#else

    #error "Ошибка настройки проекта. Не выбран тип ШИМа!!!"

#endif //XPWMGEN
#endif //TMSPWMGEN

    InitPWM_Variables();

    break_resistor_managment_init(FREQ_PWM);

//    start_int13_interrupt();


// Настроили SYNC
    setup_sync_int(); //use timer4
    //start_sync_interrupt();
    edrk.disable_interrupt_sync = 0;


 //   pause_1000(100000);
    final_code = update_progress_load_hmi(8);

//  project.enable_all_interrupt();
//  status_interrupts = __enable_interrupts();

//  pause_1000(100000);


      project.read_errors_controller();
      x_parallel_bus_project.read_status(&x_parallel_bus_project);

//    err_main = ReadMemory(ADR_ERRORS_TOTAL_INFO);
//    if(enable_er0_control() || err_main)
      if (project.controller.read.errors.bit.error_pbus
              || project.controller.read.errors_buses.bit.slave_addr_error
                       || project.controller.read.errors_buses.bit.count_error_pbus)
      {
        xerror(xparall_bus_er_ID(2),(void *)0);

        project.stop_parallel_bus();

        project.reset_errors_controller();
        project.read_errors_controller();

        project.start_parallel_bus();
        project.read_errors_controller();
      }

/*
      while(1)
      {
          project.adc[0].read_pbus(&project.adc[0]);
//          project.adc[1].read_pbus(&project.adc[1]);
          project.cds_tk[3].read_pbus(&project.cds_tk[3]);
          project.read_errors_controller();
      }
*/
//    project_stop_parallel_bus();


    project.start_parallel_bus();
    x_parallel_bus_project.read_status(&x_parallel_bus_project);

// Надо только после запуска PBUS иначе не будет данных длЯ детекта нулЯ
    Init_Adc_Variables();
    final_code = update_progress_load_hmi(9);


/////////////////////////////
// optical bus timer
    if (edrk.flag_second_PCH==0)
        init_eva_timer2(29333,&optical_bus_read_write_interrupt);
    if (edrk.flag_second_PCH==1)
        init_eva_timer2(26777,&optical_bus_read_write_interrupt);

    //start_eva_timer2();// run global_time_interrupt
/////////////////////////////

    /////////////////////////////
    // add bus timer
  //      init_eva_timer1(FREQ_PWM * 1.1,&pwm_analog_ext_interrupt);
  //      start_eva_timer1();// run global_time_interrupt
    /////////////////////////////

    flag_enable_can_from_mpu = 1;

    i_led1_on_off(1);
    i_led2_on_off(0);

    final_code = update_progress_load_hmi(10);

#if (XPWMGEN==1)
    project.enable_int13();
#endif

    start_int13_interrupt();

    pause_1000(10000);



//      project.enable_all_interrupt();


//#if (MODE_DISABLE_ENABLE_WDOG==1)
//    stop_wdog();
//#else
//    start_wdog();
//#endif


    start_sync_interrupt(); // запустили детект SYNC
    start_eva_timer2();// run global_time_interrupt optical_bus_read_write_interrupt
    start_can_interrupt();

    prev_flag_special_mode_rs = flag_special_mode_rs;

}

//////////////////////////////////////////////////////////
void edrk_go_main(void)
{
    static int at=0;
    static int pbus_cmd=1;
    static int prev_pbus_cmd=1;


//    new_fifo_calc_load();

    project.read_errors_controller();

//      project.read_all_pbus();
//      project.read_all_hwp();

    project.read_all_sbus();
    x_parallel_bus_project.read_status(&x_parallel_bus_project);

//      project.write_all_sbus();




//////////////////////
      if ((prev_pbus_cmd != pbus_cmd) && pbus_cmd==0)
      {
//        project.disable_int13();
        project.stop_parallel_bus();
      }

      if ((prev_pbus_cmd != pbus_cmd) && pbus_cmd==1)
      {
//        project.enable_int13();
        project.start_parallel_bus();
      }
      prev_pbus_cmd = pbus_cmd;

    prev_flag_special_mode_rs = flag_special_mode_rs;
/////////////////////

    if (flag_special_mode_rs==0)
    {
        project.read_all_hwp();
        project.write_all_sbus();

        run_edrk();

//        if (at==1)
//        {
//          SendAll2SecondBS();
//          oscil_can.send(&oscil_can);
//          at=0;
//        }

        //Обмен по CAN
        CAN_may_be_send_cycle_fifo();
    }
    else
    {
        project.read_all_pbus();
        project.read_all_hwp();
        project.write_all_sbus();
//          project.disable_int13();

        RS232_WorkingWith(0,1,0);


    }






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


void init_ramp_all_zadanie(void)
{
    _iq rampafloat;

// rmp_fzad
    edrk.zadanie.rmp_fzad.RampLowLimit = _IQ(-MAX_ZADANIE_F/NORMA_FROTOR); //0
    edrk.zadanie.rmp_fzad.RampHighLimit = _IQ(MAX_ZADANIE_F/NORMA_FROTOR);

    rampafloat = _IQ(1.0/(2.0*FREQ_PWM*T_NARAST_ZADANIE_F));
    edrk.zadanie.rmp_fzad.RampPlus = rampafloat;
    edrk.zadanie.rmp_fzad.RampMinus = -rampafloat;

    edrk.zadanie.rmp_fzad.DesiredInput = 0;
    edrk.zadanie.rmp_fzad.Out = 0;

// rmp_oborots_hz
    edrk.zadanie.rmp_oborots_zad_hz.RampLowLimit = _IQ(MIN_ZADANIE_OBOROTS_ROTOR/60.0/NORMA_FROTOR); //0
    edrk.zadanie.rmp_oborots_zad_hz.RampHighLimit = _IQ(MAX_ZADANIE_OBOROTS_ROTOR/60.0/NORMA_FROTOR);

    rampafloat = _IQ(1.0/(2.0*FREQ_PWM*T_NARAST_ZADANIE_OBOROTS_ROTOR));
    edrk.zadanie.rmp_oborots_zad_hz.RampPlus = rampafloat;
    edrk.zadanie.rmp_oborots_zad_hz.RampMinus = -rampafloat;

    edrk.zadanie.rmp_oborots_zad_hz.DesiredInput = 0;
    edrk.zadanie.rmp_oborots_zad_hz.Out = 0;


//
    edrk.zadanie.rmp_Izad.RampLowLimit = _IQ(0); //0
    edrk.zadanie.rmp_Izad.RampHighLimit = _IQ(MAX_ZADANIE_I_M/NORMA_ACP);

    rampafloat = _IQ(1.0/(2.0*FREQ_PWM*T_NARAST_ZADANIE_I_M));
    edrk.zadanie.rmp_Izad.RampPlus = rampafloat;
    edrk.zadanie.rmp_Izad.RampMinus = -rampafloat;

    edrk.zadanie.rmp_Izad.DesiredInput = 0;
    edrk.zadanie.rmp_Izad.Out = 0;

//
    edrk.zadanie.rmp_ZadanieU_Charge.RampLowLimit = _IQ(0); //0
    edrk.zadanie.rmp_ZadanieU_Charge.RampHighLimit = _IQ(MAX_ZADANIE_U_CHARGE/NORMA_ACP);

    rampafloat = _IQ(1.0/(2.0*FREQ_PWM*T_NARAST_ZADANIE_U_CHARGE));
    edrk.zadanie.rmp_ZadanieU_Charge.RampPlus = rampafloat;
    edrk.zadanie.rmp_ZadanieU_Charge.RampMinus = -rampafloat;

    edrk.zadanie.rmp_ZadanieU_Charge.DesiredInput = 0;
    edrk.zadanie.rmp_ZadanieU_Charge.Out = 0;



//
    edrk.zadanie.rmp_k_u_disbalance.RampLowLimit = _IQ(0); //0
    edrk.zadanie.rmp_k_u_disbalance.RampHighLimit = _IQ(MAX_ZADANIE_K_U_DISBALANCE);

    rampafloat = _IQ(1.0/(2.0*FREQ_PWM*T_NARAST_ZADANIE_K_U_DISBALANCE));
    edrk.zadanie.rmp_k_u_disbalance.RampPlus = rampafloat;
    edrk.zadanie.rmp_k_u_disbalance.RampMinus = -rampafloat;

    edrk.zadanie.rmp_k_u_disbalance.DesiredInput = 0;
    edrk.zadanie.rmp_k_u_disbalance.Out = 0;


//
    edrk.zadanie.rmp_kplus_u_disbalance.RampLowLimit = _IQ(0); //0
    edrk.zadanie.rmp_kplus_u_disbalance.RampHighLimit = _IQ(MAX_ZADANIE_KPLUS_U_DISBALANCE);

    rampafloat = _IQ(1.0/(2.0*FREQ_PWM*T_NARAST_ZADANIE_KPLUS_U_DISBALANCE));
    edrk.zadanie.rmp_kplus_u_disbalance.RampPlus = rampafloat;
    edrk.zadanie.rmp_kplus_u_disbalance.RampMinus = -rampafloat;

    edrk.zadanie.rmp_kplus_u_disbalance.DesiredInput = 0;
    edrk.zadanie.rmp_kplus_u_disbalance.Out = 0;



//
    edrk.zadanie.rmp_kzad.RampLowLimit = _IQ(0); //0
    edrk.zadanie.rmp_kzad.RampHighLimit = _IQ(MAX_ZADANIE_K_M);

    rampafloat = _IQ(1.0/(2.0*FREQ_PWM*T_NARAST_ZADANIE_K_M));
    edrk.zadanie.rmp_kzad.RampPlus = rampafloat;
    edrk.zadanie.rmp_kzad.RampMinus = -rampafloat;

    edrk.zadanie.rmp_kzad.DesiredInput = 0;
    edrk.zadanie.rmp_kzad.Out = 0;





//
    edrk.zadanie.rmp_powers_zad.RampLowLimit = _IQ(MIN_ZADANIE_POWER*1000.0/(NORMA_MZZ*NORMA_MZZ)); //0
    edrk.zadanie.rmp_powers_zad.RampHighLimit = _IQ(MAX_ZADANIE_POWER*1000.0/(NORMA_MZZ*NORMA_MZZ));

    rampafloat = _IQ(1.0/(2.0*FREQ_PWM*T_NARAST_ZADANIE_POWER));
    edrk.zadanie.rmp_powers_zad.RampPlus = rampafloat;
    edrk.zadanie.rmp_powers_zad.RampMinus = -rampafloat;

    edrk.zadanie.rmp_powers_zad.DesiredInput = 0;
    edrk.zadanie.rmp_powers_zad.Out = 0;

//
        edrk.zadanie.rmp_limit_powers_zad.RampLowLimit = _IQ(0); //0
        edrk.zadanie.rmp_limit_powers_zad.RampHighLimit = _IQ(MAX_ZADANIE_POWER*1000.0/(NORMA_MZZ*NORMA_MZZ));

        rampafloat = _IQ(1.0/(2.0*FREQ_PWM*T_NARAST_ZADANIE_POWER));
        edrk.zadanie.rmp_limit_powers_zad.RampPlus = rampafloat;
        edrk.zadanie.rmp_limit_powers_zad.RampMinus = -rampafloat;

        edrk.zadanie.rmp_limit_powers_zad.DesiredInput = 0;
        edrk.zadanie.rmp_limit_powers_zad.Out = 0;

//


}

//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
#pragma CODE_SECTION(ramp_all_zadanie,".fast_run");
void ramp_all_zadanie(int flag_set_zero)
{
    //////////////////////////////////////////////
    if (flag_set_zero==0)
      edrk.zadanie.rmp_Izad.DesiredInput = edrk.zadanie.iq_Izad;
    else
    if (flag_set_zero==2)
    {
        edrk.zadanie.rmp_Izad.DesiredInput = 0;
        edrk.zadanie.rmp_Izad.Out = 0;
    }
    else
      edrk.zadanie.rmp_Izad.DesiredInput = 0;

    edrk.zadanie.rmp_Izad.calc(&edrk.zadanie.rmp_Izad);
    edrk.zadanie.iq_Izad_rmp = edrk.zadanie.rmp_Izad.Out;
    //////////////////////////////////////////////
    edrk.zadanie.rmp_ZadanieU_Charge.DesiredInput = edrk.zadanie.iq_ZadanieU_Charge;
    edrk.zadanie.rmp_ZadanieU_Charge.calc(&edrk.zadanie.rmp_ZadanieU_Charge);
    edrk.zadanie.iq_ZadanieU_Charge_rmp = edrk.zadanie.rmp_ZadanieU_Charge.Out;
    //////////////////////////////////////////////
    if (flag_set_zero==0)
        edrk.zadanie.rmp_fzad.DesiredInput = edrk.zadanie.iq_fzad;
    else
    if (flag_set_zero==2)
    {
        edrk.zadanie.rmp_fzad.DesiredInput = 0;
        edrk.zadanie.rmp_fzad.Out = 0;
    }
    else
        edrk.zadanie.rmp_fzad.DesiredInput = 0;

    edrk.zadanie.rmp_fzad.calc(&edrk.zadanie.rmp_fzad);
    edrk.zadanie.iq_fzad_rmp = edrk.zadanie.rmp_fzad.Out;
    //////////////////////////////////////////////
    edrk.zadanie.rmp_k_u_disbalance.DesiredInput = edrk.zadanie.iq_k_u_disbalance;
    edrk.zadanie.rmp_k_u_disbalance.calc(&edrk.zadanie.rmp_k_u_disbalance);
    edrk.zadanie.iq_k_u_disbalance_rmp = edrk.zadanie.rmp_k_u_disbalance.Out;
    //////////////////////////////////////////////
    edrk.zadanie.rmp_kplus_u_disbalance.DesiredInput = edrk.zadanie.iq_kplus_u_disbalance;
    edrk.zadanie.rmp_kplus_u_disbalance.calc(&edrk.zadanie.rmp_kplus_u_disbalance);
    edrk.zadanie.iq_kplus_u_disbalance_rmp = edrk.zadanie.rmp_kplus_u_disbalance.Out;
    //////////////////////////////////////////////
    if (flag_set_zero==0)
        edrk.zadanie.rmp_kzad.DesiredInput = edrk.zadanie.iq_kzad;
    else
    if (flag_set_zero==2)
    {
        edrk.zadanie.rmp_kzad.DesiredInput = 0;
        edrk.zadanie.rmp_kzad.Out = 0;
    }
    else
        edrk.zadanie.rmp_kzad.DesiredInput = 0;
    edrk.zadanie.rmp_kzad.calc(&edrk.zadanie.rmp_kzad);
    edrk.zadanie.iq_kzad_rmp = edrk.zadanie.rmp_kzad.Out;
    //////////////////////////////////////////////
    if (flag_set_zero==0)
        edrk.zadanie.rmp_oborots_zad_hz.DesiredInput = edrk.zadanie.iq_oborots_zad_hz;
    else
    if (flag_set_zero==2)
    {
        edrk.zadanie.rmp_oborots_zad_hz.DesiredInput = 0;
        edrk.zadanie.rmp_oborots_zad_hz.Out = 0;
    }
    else
        edrk.zadanie.rmp_oborots_zad_hz.DesiredInput = 0;

    edrk.zadanie.rmp_oborots_zad_hz.calc(&edrk.zadanie.rmp_oborots_zad_hz);
    edrk.zadanie.iq_oborots_zad_hz_rmp = edrk.zadanie.rmp_oborots_zad_hz.Out;

    //////////////////////////////////////////////
    if (flag_set_zero==0)
        edrk.zadanie.rmp_limit_powers_zad.DesiredInput = edrk.zadanie.iq_limit_power_zad;
    else
    if (flag_set_zero==2)
    {
        edrk.zadanie.rmp_limit_powers_zad.DesiredInput = 0;
        edrk.zadanie.rmp_limit_powers_zad.Out = 0;
    }
    else
        edrk.zadanie.rmp_limit_powers_zad.DesiredInput = 0;

    edrk.zadanie.rmp_limit_powers_zad.calc(&edrk.zadanie.rmp_limit_powers_zad);
    edrk.zadanie.iq_limit_power_zad_rmp = edrk.zadanie.rmp_limit_powers_zad.Out;



    //////////////////////////////////////////////
    if (flag_set_zero==0)
    {
        if (edrk.zadanie.iq_power_zad>edrk.zadanie.iq_limit_power_zad_rmp)
            edrk.zadanie.rmp_powers_zad.DesiredInput = edrk.zadanie.iq_limit_power_zad_rmp;
        else
            edrk.zadanie.rmp_powers_zad.DesiredInput = edrk.zadanie.iq_power_zad;
    }
    else
    if (flag_set_zero==2)
    {
        edrk.zadanie.rmp_powers_zad.DesiredInput = 0;
        edrk.zadanie.rmp_powers_zad.Out = 0;
    }
    else
        edrk.zadanie.rmp_powers_zad.DesiredInput = 0;

    edrk.zadanie.rmp_powers_zad.calc(&edrk.zadanie.rmp_powers_zad);
    edrk.zadanie.iq_power_zad_rmp = edrk.zadanie.rmp_powers_zad.Out;




}

//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//#pragma CODE_SECTION(get_start_ged_from_zadanie,".fast_run");
int get_start_ged_from_zadanie(void)
{

    // uf const
    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_UF_CONST)
    {
        if (edrk.zadanie.iq_fzad_rmp!=0 && edrk.zadanie.iq_kzad_rmp!=0)
            return 1;
        else
            return 0;
    }
    else
    // scalar oborots
    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_SCALAR_OBOROTS)
    {
        if (edrk.zadanie.iq_oborots_zad_hz_rmp!=0 && edrk.zadanie.iq_Izad_rmp!=0
                && edrk.zadanie.iq_power_zad_rmp!=0 && edrk.zadanie.iq_limit_power_zad_rmp!=0)
            return 1;
        else
            return 0;
    }
    else
    // scalar power
    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_SCALAR_POWER)
    {
        if (edrk.zadanie.iq_oborots_zad_hz_rmp!=0 && edrk.zadanie.iq_Izad_rmp!=0
                && edrk.zadanie.iq_power_zad_rmp!=0 && edrk.zadanie.iq_limit_power_zad_rmp!=0)
            return 1;
        else
            return 0;
    }
    else
    // foc oborots
    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_OBOROTS)
    {
        if (edrk.zadanie.iq_oborots_zad_hz_rmp!=0 && edrk.zadanie.iq_Izad_rmp!=0
                && edrk.zadanie.iq_power_zad_rmp!=0 && edrk.zadanie.iq_limit_power_zad_rmp!=0)
            return 1;
        else
            return 0;
    }
    else
    // foc power
    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_POWER)
    {
        if (edrk.zadanie.iq_oborots_zad_hz_rmp!=0 && edrk.zadanie.iq_Izad_rmp!=0
                && edrk.zadanie.iq_power_zad_rmp!=0 && edrk.zadanie.iq_limit_power_zad_rmp!=0)
            return 1;
        else
            return 0;
    }
    else
    {
        return 0;
    }

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

void UpdateTableSecondBS(void)
{
  int cmd;
  int i,k;

  Unites2SecondBS[0]++;

  Unites2SecondBS[1] = global_time.miliseconds;
  Unites2SecondBS[2] = edrk.flag_second_PCH;
  Unites2SecondBS[3] = (edrk.to_shema.bits.QTV_ON_OFF << 1) | (edrk.to_shema.bits.UMP_ON_OFF);
  Unites2SecondBS[4] = edrk.SumSbor;
  Unites2SecondBS[5] = edrk.int_koef_ogran_power;
  Unites2SecondBS[6] = (int)edrk.power_kw;
  Unites2SecondBS[7] = (int)edrk.active_post_upravl;
  Unites2SecondBS[8] = (int)edrk.power_kw;
  Unites2SecondBS[9] =  edrk.Status_Ready.bits.ready1;
  Unites2SecondBS[10] = edrk.Status_Ready.bits.ready_final;
  Unites2SecondBS[11] = edrk.MasterSlave;

  Unites2SecondBS[12] = _IQtoF(vect_control.iqId_min) * NORMA_ACP;


  for (i=0;i<CONTROL_STATION_CMD_LAST;i++)
      Unites2SecondBS[POS_STATION_CMD_ANOTHER_BSU1+i] =  control_station.active_array_cmd[i];


//  Unites2SecondBS[3] = _IQtoIQ15(edrk.zadanie.iq_fzad);
//  Unites2SecondBS[4] = _IQtoIQ15(edrk.zadanie.iq_kzad);
//  Unites2SecondBS[5] = _IQtoIQ15(edrk.zadanie.iq_Izad);
//  Unites2SecondBS[6] = (edrk.zadanie.oborots_zad);
//  Unites2SecondBS[7] = _IQtoIQ15(edrk.zadanie.iq_power_zad);


  if (edrk.flag_second_PCH==0)
  {

//      Unites2SecondBS[5] = Unites[ANOTHER_BSU1_CAN_DEVICE][8];
//      Unites2SecondBS[8] = 0xaa;
//
//      max_count_send_to_can2second_bs = 10;
  }
  else
  {

//      Unites2SecondBS[5] = Unites[ANOTHER_BSU1_CAN_DEVICE][8];
//      Unites2SecondBS[8] = 0x55;
//
//      max_count_send_to_can2second_bs = 10;
  }



}


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

void cross_stend_automats(void)
{
    unsigned int g;

    if (control_station.active_array_cmd[CONTROL_STATION_CMD_CROSS_STEND_AUTOMATS])
    {

       // QPU
       g = Unites[ANOTHER_BSU1_CAN_DEVICE][3] & 0x1;
       if (g)
          edrk.to_shema.bits.CROSS_UMP_ON_OFF = 1;
       else
           edrk.to_shema.bits.CROSS_UMP_ON_OFF = 0;

       //QTV STEND
       g = Unites[ANOTHER_BSU1_CAN_DEVICE][3] & 0x2;
       if (g)
          edrk.to_shema.bits.CROSS_QTV_ON_OFF = 1;
       else
           edrk.to_shema.bits.CROSS_QTV_ON_OFF = 0;

    }
    else
    {
        edrk.to_shema.bits.CROSS_UMP_ON_OFF = 0;
        edrk.to_shema.bits.CROSS_QTV_ON_OFF = 0;
    }



}

//////////////////////////////////////////////////////////
unsigned int read_cmd_sbor_from_bs(void)
{
    unsigned int g;
    g = Unites[ANOTHER_BSU1_CAN_DEVICE][4];
    return g;


}


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

//////////////////////////////////////////////////////////
void read_data_from_bs(void)
{
    int g;

    g = Unites[ANOTHER_BSU1_CAN_DEVICE][5];
    edrk.int_koef_ogran_power_another_bs = g;
    edrk.iq_koef_ogran_power_another_bs = ((float)edrk.int_koef_ogran_power_another_bs);

    g = Unites[ANOTHER_BSU1_CAN_DEVICE][6];
    edrk.power_kw_another_bs = g;
    edrk.iq_power_kw_another_bs = _IQ(((float)edrk.power_kw_another_bs * 1000.0)/NORMA_ACP/NORMA_ACP);

    g = Unites[ANOTHER_BSU1_CAN_DEVICE][7];
    edrk.active_post_upravl_another_bs = g;

    g = Unites[ANOTHER_BSU1_CAN_DEVICE][9];
    edrk.Ready1_another_bs = g;

    g = Unites[ANOTHER_BSU1_CAN_DEVICE][10];
    edrk.Ready2_another_bs = g;

    g = Unites[ANOTHER_BSU1_CAN_DEVICE][11];
    edrk.MasterSlave_another_bs = g;

}

#define MAX_ERRORS_DETECT_CHANGE_ACTIVE_CONTROL 50
void check_change_post_upravl(void)
{
  static int prev_active_post_upravl = -1, prev_active_post_upravl_another_bs = -1;
  int active_post_upravl = -1, active_post_upravl_another_bs = -1;
  static unsigned int count_err = 0;


  active_post_upravl = get_code_active_post_upravl();
  active_post_upravl_another_bs = edrk.active_post_upravl_another_bs;


  if (edrk.Status_Ready.bits.ready_final && edrk.Ready2_another_bs)
  {
      if ((active_post_upravl_another_bs==0 || active_post_upravl==0) && (active_post_upravl==2 || active_post_upravl_another_bs==2))
      {
        // если какой-то БС в СВУ а другой в МЕСТНОЕ
          edrk.errors.e9.bits.CHANGE_ACTIVE_CONTROL_TO_LOCAL_FROM_SVU |=
                          filter_err_count(&count_err,
                           MAX_ERRORS_DETECT_CHANGE_ACTIVE_CONTROL,
                           1,
                           0);
      }
      else
          count_err = 0;
  }


  prev_active_post_upravl = active_post_upravl;
  prev_active_post_upravl_another_bs = active_post_upravl_another_bs;

  edrk.active_post_upravl = active_post_upravl;
}


int get_code_active_post_upravl(void)
{

    if (control_station.active_control_station[CONTROL_STATION_TERMINAL_RS232])
        return 3;
    else
    if (control_station.active_control_station[CONTROL_STATION_TERMINAL_CAN])
        return 4;
    else
    if (control_station.active_control_station[CONTROL_STATION_INGETEAM_PULT_RS485])//(edrk.RemouteFromDISPLAY)
        return 0;
    else
    if (control_station.active_control_station[CONTROL_STATION_MPU_KEY_CAN])
        return 5;
    else
    if (control_station.active_control_station[CONTROL_STATION_ZADATCHIK_CAN])
        return 6;
    else
    if (control_station.active_control_station[CONTROL_STATION_VPU_CAN])
        return 1;
    else
    if (control_station.active_control_station[CONTROL_STATION_MPU_SVU_CAN])
        return 2;
    else
        return 10; //error
}




void init_50hz_input_net50hz(void)
{

    //1. ИнициализациЯ

        pll1.setup.freq_run_pll = (2.0*FREQ_PWM); // частота запуска расчета Гц.
        pll1.setup.rotation_u_cba = 1;//0;//1; // чередование фаз: 0 - правильное A-B-C, 1 - неправильное A-C-B

        pll1.init(&pll1); // расчет и инициализациЯ внутренних переменных

    // Конец Инициализации

}

void calc_pll_50hz(void)
{

    // передача данных в алгоритм.
    pll1.input.Input_U_AB = analog.iqUin_A1B1;
    pll1.input.Input_U_BC = analog.iqUin_B1C1;
    pll1.input.Input_U_CA = analog.iqUin_C1A1;

    // расчет, запускать с частотой указанной в setup.freq_run_pll
     pll1.calc_pll(&pll1);
// Конец расчета


}


void get_freq_50hz(void)
{

    // 3. Получение данных у нормальном виде.

         // получение данных о частотен сети в Гц*100.
         // можно вызывать реже - только длЯ получения данных.
         pll1.get_freq(&pll1);
         edrk.freq_50hz = pll1.output.int_freq_net;
    //


}



#define MAX_COUNT_DETECTS_ZERO_U_ZPT    5

void auto_detect_zero_u_zpt(void)
{
    static unsigned int old_time_u_zpt1=0, count_detects = 0, flag_detect_zero_u_zpt = 0;

    static _iq prev_uzpt1=0;
    static _iq prev_uzpt2=0;
    static _iq delta_u = _IQ(3.0/NORMA_ACP);
    static _iq minimal_detect_u = _IQ(40.0/NORMA_ACP);



    if (edrk.SumSbor==0 && flag_detect_zero_u_zpt==0)
    {
        // нет сбора, значит можем искать ноль Uzpt
        if (detect_pause_sec(5,&old_time_u_zpt1))
        {
            if ( (filter.iqU_1_long>=minimal_detect_u ||
                    filter.iqU_2_long>=minimal_detect_u ||
                    prev_uzpt1-filter.iqU_1_long)>=delta_u ||
                    (prev_uzpt2-filter.iqU_2_long)>=delta_u )
            {
                // напряжение еще падает
                count_detects = 0;
            }
            else
            {
                if (count_detects<MAX_COUNT_DETECTS_ZERO_U_ZPT)
                    count_detects++;
                else
                {
                    if (flag_detect_zero_u_zpt==0)
                    {
                        if (filter.iqU_1_long<=minimal_detect_u &&
                                filter.iqU_2_long<=minimal_detect_u)
                        {
                          analog_zero.iqU_1 = filter.iqU_1_long;
                          analog_zero.iqU_2 = filter.iqU_2_long;
                        }
                    }
                    flag_detect_zero_u_zpt = 1;

                }

            }

            prev_uzpt1 = filter.iqU_1_long;
            prev_uzpt2 = filter.iqU_2_long;
        }  // 1 sec end
    }
    else
    {
        if (flag_detect_zero_u_zpt)
        {
            if (filter.iqU_1_long<-delta_u || filter.iqU_2_long<-delta_u)
            {
                // слишком рано была произведена коррекция, надо бы повторить
                flag_detect_zero_u_zpt = 0;
                analog_zero.iqU_1 = 0;
                analog_zero.iqU_2 = 0;
            }

        }
        count_detects = 0;
    }

}


#pragma CODE_SECTION(calc_rms,".fast_run");
_iq calc_rms(_iq input, _iq input_prev, _iq freq_signal)
{
    static _iq pi_pwm = _IQ(PI*NORMA_FROTOR/(FREQ_PWM/5.0));
    _iq cosw, sinw, wdt, y2, z1, z2, z3, y;

    wdt = _IQmpy(pi_pwm,freq_signal);
    sinw = _IQsinPU(wdt);
    cosw = _IQcosPU(wdt);

    if (cosw==0)
        return 0;

    z1 = input_prev - _IQmpy(input,cosw);
//    z2 = sinw;
    z3 = _IQdiv(z1,sinw);

    y2 = _IQmpy(input,input)+_IQmpy(z3,z3);

//    cosw = _IQsin();

    y  = _IQsqrt(y2);
    return y;
}

