fork

Dependencies:   mbed

Fork of LG by igor Apu

CyclesSync.c

Committer:
Kovalev_D
Date:
2017-09-27
Revision:
219:2d3475d0dd1b
Parent:
193:a0fe8bfc97e4
Child:
201:76f4123bf22a

File content as of revision 219:2d3475d0dd1b:

/**--------------File Info---------------------------------------------------------------------------------
** File name:           CycleSync.c
** Last modified Date:  2011-09-06
** Last Version:        V1.00
** Descriptions:
**
**--------------------------------------------------------------------------------------------------------
** Created by:          Electrooptica Inc.
** Created date:        2011-09-06
** Version:             V1.00
** Descriptions:        There is the routines for device synchronization
**
**--------------------------------------------------------------------------------------------------------
*********************************************************************************************************/
#include "CyclesSync.h"
#include "CntrlGLD.h"
#include "SIP.h"
#include "el_lin.h"
#include "InputOutput.h"

uint32_t 	Sys_Clock;      //e. counter of system ticks //r. счетчик  временной сетки системы
uint32_t 	Seconds = 0;    //e. seconds from power on //r. число секунд от момента включения питания
int32_t 	time_1_Sec = DEVICE_SAMPLE_RATE_uks;     //e. pseudosecond timer //r. псевдосекундный таймер
uint32_t 	trm_cycl;
uint32_t	count;
int32_t	PrevPeriod = 0;
uint32_t	num;
volatile uint32_t	Latch_Rdy = 0;

int32_t    LatchPhase = INT32_MAX;
uint32_t 	Ext_Latch_ResetEnable = 1;
volatile uint32_t 	data_Rdy = 0;

uint32_t	Delay_UART_Enbl = DELAY_UART_ENBL;
//uint32_t	Delay_UART_Disbl = DELAY_UART_ENBL;

uint32_t 	main_cycle_latch = 0;
uint32_t 	Out_main_cycle_latch; //e. counter of main cycles between external latch pulse appearence
uint32_t 	T_latch, Out_T_latch, temp_T_latch;

/******************************************************************************
** Function name:		Latch_Event
**
** Descriptions:		Routine for latch appearing
**
** parameters:			None
** Returned value:		None
**
******************************************************************************/
/*void Latch_Event()
{
    static unsigned PreLatch = 0;
//  static int cc = 0;
    if (LatchPhase < INT32_MAX) { //Если LatchPhase(флаг защелки) < меньше максимального 32-х битного инта (при инициализации int32_t    LatchPhase = INT32_MAX;) то:
        Latch_Rdy = 1;		   //e. установить флаг для обработки ниже
        if (RgConB) {		   //Если RgConB (дополнительный регистр управления, установлен в еденицу при инициализации в мэйне) утановлен в еденицу то:
            if (PreLatch)		   //e. если мы откладываем защелку
                PreLatch = 0;

            else if ((LatchPhase < LPC_PWM1->TC) && (num == Sys_Clock)) { //e. latch have appeared in current cycle
                Latch_Rdy = 0;	//e. bring it to the next cycle
                PreLatch = 1;
            }
        }
    } else
        Latch_Rdy = 0;				//e. latch is absent*/
//---------------------------temp-------------------------------
    /*	Latch_Rdy = 0;				//e. latch is absent
    if (cc++ == 19)
    {
      cc = 0;
      Latch_Rdy = 1;
      LatchPhase = 2500;
    } 	*/
    //----------------------temp--------------------------------
//}

/******************************************************************************
** Function name:		QEI_IRQHandler
**
** Descriptions:		Latch counters by reference meander
**
** parameters:			None
** Returned value:		None
**
******************************************************************************/
__irq void QEI_IRQHandler (void)
{
    static uint32_t halfQEIPeriod = 0;

    Cnt_curr =  LPC_QEI->POS;		//e. read accumulated value of counter
    if (LPC_QEI->INTSTAT & 0x0008) {
        data_Rdy = 0x0004;			//e. data for Cnt_Pls or Cnt_Mns calculation are ready

        if (++halfQEIPeriod & 0x0001) {	//e. period elapsed, we can calculate Cnt_Dif
            data_Rdy = 0x000C;
        }
    }
    LPC_QEI->CLR = 0x1fff;			//e. reset interrupt request //r. сбросить запрос прерывания
}
/******************************************************************************
** Function name:		SetIntLatch
**
** Descriptions:		Set timer for accumulation period
**
** parameters:			Period of accumulation
** Returned value:		None
**
******************************************************************************/
void SetIntLatch(uint32_t cycle)
{
    LPC_TIM3->TCR = 0x2;							//switch off and reset timer3
    if (cycle != 0) {
        LPC_TIM3->MR0 = (cycle<<2);						//load new value
        LPC_TIM3->TCR = 1;							//switch on timer3
    }
}
/******************************************************************************
** Function name:		SwitchRefMeandInt
**
** Descriptions:		Enable/disable interrupt from reference meander
**
** parameters:			switcher
** Returned value:		None
**
******************************************************************************/
void SwitchRefMeandInt(uint32_t s)
{
    LPC_QEI->CLR = 0x1fff; 			//e. reset all interrupts //r. сбросить все прерывания
    if (s)
        LPC_QEI->IEC = 0x1fff;			//e.  disable direction changing interrupt //r. запретить прерывание при изменении направления
    else
        LPC_QEI->IES = 0x0008;			//e.  enable direction changing interrupt //r. разрешить прерывание при изменении направления
}
/******************************************************************************
** Function name:		ExtLatch_IRQHandler
**
** Descriptions:		Routine for external latch appearence processing
**
** parameters:			None
** Returned value:		None
**
******************************************************************************/
/*__irq void EINT3_IRQHandler (void)
{
//LPC_GPIO2->FIOSET = 0x00000020;		//e. turn on the LED
    LatchPhase = LPC_PWM1->TC;			//e. read moment of latch
    LPC_TIM0->TCR = 1;					//e. start Mltdrop delay timer
    LPC_GPIOINT->IO0IntClr |= 0x0000800;//e. clean interrupt request
//LPC_GPIO2->FIOCLR = 0x00000020;		//e. turn off the LED
}*/
/******************************************************************************
** Function name:		IntLatch_IRQHandler
**
** Descriptions:		Routine for Internal latch appearence processing
**
** parameters:			None
** Returned value:		None
**
******************************************************************************/
__irq void IntLatch_IRQHandler (void)
{
//LPC_GPIO2->FIOSET |= 0x00000080;		// turn on the LED
    LatchPhase =(int)LPC_PWM1->TC;			//e. read moment of latch
    LPC_TIM3->IR = 0x0001;				//e. clear interrupt flag
    num = Sys_Clock;//
//	count++;
//LPC_GPIO2->FIOCLR |= 0x00000080;		// turn off the LED
}

/******************************************************************************
** Function name:		SwitchMode
**
** Descriptions:		Switch mode of device functionality
**
** parameters:			None
** Returned value:		None
**
******************************************************************************/
int SwitchMode()
{
//-----------------------disable latch sources ---------------------
    SetIntLatch(0); 	   					//e. disable internal latch
    LPC_TIM3->IR = 0x0001;				//e. clear internal latch interrupt request

    LPC_GPIOINT->IO0IntEnR &= ~0x0000800;	//e. disable external latch
    LPC_GPIOINT->IO0IntClr |=  0x0000800;	//e. clean external latch interrupt request

    LPC_TIM0->TCR = 2;						//e. stop and reset the multidrop delay timer
    LPC_TIM0->IR = 0x03F;				//e. clear internal latch interrupt request
//----------------------wait while UART and DMA are active-------------
    if ( LPC_GPDMACH1->CConfig & DMA_BUSY)				//e. if DMA channel is busy, wait //r. если канал передачи занят, ждать
        return 0;
    LPC_GPDMACH1->CConfig &=  ~DMAChannelEn;			//e. disable DMA for UART transmition
    LPC_GPDMACH2->CConfig &=  ~DMAChannelEn;

    if (!(LPC_UART1->LSR & TRANS_SHIFT_BUF_EMPTY))      //e. transmit buffer is not empty //r. передающий буфер не пуст
        return 0;
    LPC_UART1->FCR |= 0x4;								//e. reset TX FIFO

    LPC_TIM0->IR = 0x3F;				 		//e. clear all interrupt flags
//---------------------configure a new exchanging parameters------------
    if (Device_Mode > 3) {	   					//e. external latch mode enabled
        LPC_TIM0->MR0 = 10;
        LPC_TIM0->MR1 = 50;						//e. /10 = delay before enable signal (us)
//   LPC_UART1->FCR &= ~0x08;  					//e. TX FIFO is not source for DMA request

// 	LPC_SC->DMAREQSEL = 0xC;						//e. external latch delay timer is source for DMA request
//	LPC_GPIOINT->IO0IntEnR |= 0x0000800;	//e. enable rising edge interrupt
    } else {					   				//e. internal latch mode enabled
        LPC_TIM0->MR0 = 10;
        LPC_TIM0->MR1 = 5000;						//e. /10 = delay before enable signal (us)
//	LPC_SC->DMAREQSEL = 0x3;   				//e. FIFO generate DMA request

//	LPC_SC->EXTINT = 0x8;					//e. clean interrupt request
    }

    UART_SwitchSpeed(SRgR & 0x0030);

    if (Device_Mode == DM_INT_LATCH_DELTA_PS)
        SetIntLatch(50000);
    return 1;
}
/******************************************************************************
** Function name:		ServiceTime
**
** Descriptions:		Routine for pseudoseconds counting
**
** parameters:			None
** Returned value:		None
**
******************************************************************************/
void ServiceTime(void)// псевдосекундный счетчик.
{
    time_1_Sec -= PrevPeriod;

    if (time_1_Sec < (PrevPeriod>>1)) { //1 sec elapsed with accurate 0.5 of main period
        time_1_Sec = DEVICE_SAMPLE_RATE_uks;
        Seconds++;
    }
    if (Seconds == 3) {
        Seconds++;
       // close_all_loops();
    }
    Sys_Clock++; //e. increment of the system clock register //r. инкремент регистра временной сетки системы
    PrevPeriod = LPC_PWM1->MR0;
} // ServiceTime

/******************************************************************************
** Function name:		WDTFeed
**
** Descriptions:		Feed watchdog timer to prevent it from timeout
**
** parameters:			None
** Returned value:		None
**
******************************************************************************/
void WDTFeed( void )
{
    LPC_WDT->FEED = 0xAA;		/* Feeding sequence */
    LPC_WDT->FEED = 0x55;
    return;
}

/******************************************************************************
** Function name:		CounterIquiryCycle_Init
**
** Descriptions:		CounterIquiryCycle_Init setup demanded GPIOs for PWM1,
**						reset counter, all latches are enabled, interrupt
**						on PWMMR0, install PWM interrupt to the VIC table.
**
** parameters:
** Returned value:
**
******************************************************************************/
void CounterIquiryCycle_Init(uint32_t cycle)
{
    //PWM1 enabled after reset by default
    LPC_SC->PCLKSEL0 &= ~(3<<12);
    LPC_SC->PCLKSEL0 |=  (1<<12);	 	//PWM1 is synchronized by CCLK (100 MHz)(CCLK) PCLKSEL0 - Peripheral Clock Selection registers.

    LPC_PWM1->TCR = TCR_RESET;	/* Counter Reset */ //#define TCR_RESET		0x00000002 инкрементировать счетчик при спадении импульса ПВМ.
    LPC_PWM1->MCR = PWMMR0I |PWMMR0R; 	//generate interrupt and reset timer counter ( PWMMR0I - прерывание генерируется когда PWMMR0 совподает со значением PWMTC. )
    //                                           ( PWMMR0R - сбрасывает PWMTC при совподении PWMTC и PWMMR0. )

    LPC_PWM1->CCR = 0x1;				//разрешить прерывание только при совпадении PWMTC с PWMMR0	 (еще что то связано с загрузкой ТС)


    PrevPeriod = 10000;
    LPC_PWM1->MR0 = PrevPeriod;		/* set PWM cycle */// задание периода сброса счетчика.
    LPC_PWM1->PCR = PWMENA1;  			//e. single edge control mode, PWM1 out enabled only включение выхода ШИМ 1.
    LPC_PWM1->LER = LER0_EN ;  			//e. enable updating of register
    LPC_PWM1->TCR = TCR_CNT_EN | TCR_PWM_EN;	/* counter enable, PWM enable */ //включение счетчика и ШИМ

    NVIC_DisableIRQ(PWM1_IRQn);//запретить прерывание.


    return ;
}

__irq void TIMER0_IRQHandler()
{
    int val = LPC_TIM0->IR;
    LPC_TIM0->IR |= 3;

    if (val & 1) {	//MAT 1.0 interrupt
        LPC_GPIO2->FIOSET |= 1<<6;		// turn on the LED
        LPC_TIM0->IR |= 1;
        return;
    }
    if (val & 2) { //MAT 1.1 interrupt
        LPC_GPIO2->FIOCLR |= 1<<6;		// turn on the LED
        LPC_TIM0->IR |= 2;
        return;
    }
    if (val & 4) {	//MAT 0.2 interrupt
//    LPC_GPIO0->FIOSET2 |= 0xFF;				//set P0.23
//	LPC_GPIO2->FIOSET |= 0x00000040;		// turn on the LED
//	LPC_TIM0->IR |= 4;
        return;
    }
    return;
}

/******************************************************************************
** Function name:		ExtLatch_Init
**
** Descriptions:		Initialization of external latch
**
** parameters:			None
** Returned value:		None
**
******************************************************************************/
void ExtLatch_Init()
{
    LPC_PINCON->PINSEL4 &= ~0xC000000;		//e. использовать P2.13 как GPIO.
    LPC_PINCON->PINSEL0 &= ~0x0C00000;		//e. использовать P0.11 как GPIO.
    LPC_GPIO0->FIODIR   &= ~0x0000800;		//e. использовать P0.11 вхлод.
    LPC_GPIOINT->IO0IntEnR &= ~0x0000800;	//e. отключить внутреннюю защелку.
    LPC_GPIOINT->IO0IntClr |=  0x0000800;	//e. сбросить запросы на прерывания

    NVIC_EnableIRQ(EINT3_IRQn);	          // разрешить прерывания.

//+++++++ initialization of timer for multidrop delay generation+++++++++++++++++++++++
    //e.  TIMER0 enabled by default
    LPC_SC->PCLKSEL0 &= ~(3<<2);		 //e. сбросить частоту таймера 0
    LPC_SC->PCLKSEL0 |= (3<<2);		 	 //e. установить частоту таймера 0 на CLK/8.
    LPC_TIM0->PR = 0;					       //e. установить делитель частоты в 0.
    LPC_TIM0->IR = 0x3F;				     //e. очистить флаги прерываний.
    LPC_TIM0->MCR = 1 |(1<<3)|MR1_RESET |MR1_STOP; //e. сбросить и остановить таймер после совпадения  MR1 и TC.
    LPC_TIM0->CCR = 0; 			 		 //e. содержимое таймера загружается при появлении переднего фронта защелки.
    LPC_TIM0->CTCR = 0; 				 //e. timer0 в режиме таймера.

    LPC_TIM0->MR0 = /*Device_blk.Address**/10;	 		//e. delay before UART transmitter loading
    LPC_TIM0->MR1 = /*Device_blk.Address**/5000;		//e. delay before UART transmitter start
    //e. set first empty) event of timer
    NVIC_DisableIRQ(TIMER0_IRQn);
}
/******************************************************************************
** Function name:		IntLatch_Init
**
** Descriptions:		Initialization of iternal latch cycle generation
**
** parameters:			None
** Returned value:		None
**
******************************************************************************/
void IntLatch_Init()
{
    LPC_SC->PCONP |= (1<<23);  //включит TIME3(таймер)
    //e. by default timer3 mode is not counter (T3CTCR[1,0]=0)

    LPC_SC->PCLKSEL1 &= SYNC_CLCK4;	 // частота входного сигнала равна CLCK/4
    LPC_SC->PCLKSEL1 |= (1<<14);		 // timer 3 input frequency equal to CLCK/4

//	LPC_PINCON->PINSEL1 |= (3<<16);	      //e. CAP 3.1 is connected to P0.24
    //e. by default CAP3.0 is connected to timer3
    LPC_TIM3->PR = 0;					                          //e. установить предделитель таймера3 на 0.
    LPC_TIM3->IR = 0x0001;			                      	//e. очистить флаги прерываний.
    LPC_TIM3->MCR = MR0_RESET |MR0_INT_EN |MR0_NO_STOP;	// установка флагов прерываний которые выполняются при совпадении таймера и МСR.
    LPC_TIM3->CCR = 0x0001; 			                      //содержимое счетчика загружается по приходу переднего фронта защелки.

    NVIC_EnableIRQ(TIMER3_IRQn);	                      //разрешить прерывания.
}
/*****************************************************************************
** Function name:		WDTInit
**
** Descriptions:		Initialize watchdog timer, install the
**						watchdog timer interrupt handler
**
** parameters:			None
** Returned value:		true or false, return false if the VIC table
**				is full and WDT interrupt handler can be
**				installed.
**
*****************************************************************************/
uint32_t WDTInit( void )
{
    NVIC_DisableIRQ(WDT_IRQn);

    LPC_WDT->TC = WDT_FEED_VALUE;	// once WDEN is set, the WDT will start after feeding
    LPC_WDT->MOD = WDEN;

    LPC_WDT->FEED = 0xAA;		// Feeding sequence
    LPC_WDT->FEED = 0x55;

    return 1;
}
/******************************************************************************
**                            End Of File
******************************************************************************/