Dmitry Kovalev / Mbed 2 deprecated LG

Dependencies:   mbed

Fork of LG by igor Apu

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers CyclesSync.c Source File

CyclesSync.c

00001 /**--------------File Info---------------------------------------------------------------------------------
00002 ** File name:           CycleSync.c
00003 ** Last modified Date:  2011-09-06
00004 ** Last Version:        V1.00
00005 ** Descriptions:
00006 **
00007 **--------------------------------------------------------------------------------------------------------
00008 ** Created by:          Electrooptica Inc.
00009 ** Created date:        2011-09-06
00010 ** Version:             V1.00
00011 ** Descriptions:        There is the routines for device synchronization
00012 **
00013 **--------------------------------------------------------------------------------------------------------
00014 *********************************************************************************************************/
00015 #include "CyclesSync.h"
00016 #include "CntrlGLD.h"
00017 #include "SIP.h"
00018 #include "el_lin.h"
00019 #include "InputOutput.h"
00020 
00021 uint32_t    Sys_Clock;      //e. counter of system ticks //r. счетчик  временной сетки системы
00022 uint32_t    Seconds = 0;    //e. seconds from power on //r. число секунд от момента включения питания
00023 int32_t     time_1_Sec = DEVICE_SAMPLE_RATE_uks;     //e. pseudosecond timer //r. псевдосекундный таймер
00024 uint32_t    trm_cycl;
00025 uint32_t    count;
00026 int32_t PrevPeriod = 0;
00027 uint32_t    num;
00028 volatile uint32_t   Latch_Rdy = 0;
00029 
00030 int32_t    LatchPhase = INT32_MAX;
00031 uint32_t    Ext_Latch_ResetEnable = 1;
00032 volatile uint32_t   data_Rdy = 0;
00033 
00034 uint32_t    Delay_UART_Enbl = DELAY_UART_ENBL;
00035 //uint32_t  Delay_UART_Disbl = DELAY_UART_ENBL;
00036 
00037 uint32_t    main_cycle_latch = 0;
00038 uint32_t    Out_main_cycle_latch; //e. counter of main cycles between external latch pulse appearence
00039 uint32_t    T_latch, Out_T_latch, temp_T_latch;
00040 
00041 /******************************************************************************
00042 ** Function name:       Latch_Event
00043 **
00044 ** Descriptions:        Routine for latch appearing
00045 **
00046 ** parameters:          None
00047 ** Returned value:      None
00048 **
00049 ******************************************************************************/
00050 void Latch_Event()
00051 {
00052     static unsigned PreLatch = 0;
00053 //  static int cc = 0;
00054     if (LatchPhase < INT32_MAX) { //Если LatchPhase(флаг защелки) < меньше максимального 32-х битного инта (при инициализации int32_t    LatchPhase = INT32_MAX;) то:
00055         Latch_Rdy = 1;         //e. установить флаг для обработки ниже
00056         if (RgConB) {          //Если RgConB (дополнительный регистр управления, установлен в еденицу при инициализации в мэйне) утановлен в еденицу то:
00057             if (PreLatch)          //e. если мы откладываем защелку
00058                 PreLatch = 0;
00059 
00060             else if ((LatchPhase < LPC_PWM1->TC) && (num == Sys_Clock)) { //e. latch have appeared in current cycle
00061                 Latch_Rdy = 0;  //e. bring it to the next cycle
00062                 PreLatch = 1;
00063             }
00064         }
00065     } else
00066         Latch_Rdy = 0;              //e. latch is absent
00067 //---------------------------temp-------------------------------
00068     /*  Latch_Rdy = 0;              //e. latch is absent
00069     if (cc++ == 19)
00070     {
00071       cc = 0;
00072       Latch_Rdy = 1;
00073       LatchPhase = 2500;
00074     }   */
00075     //----------------------temp--------------------------------
00076 }
00077 
00078 /******************************************************************************
00079 ** Function name:       QEI_IRQHandler
00080 **
00081 ** Descriptions:        Latch counters by reference meander
00082 **
00083 ** parameters:          None
00084 ** Returned value:      None
00085 **
00086 ******************************************************************************/
00087 __irq void QEI_IRQHandler (void)
00088 {
00089     static uint32_t halfQEIPeriod = 0;
00090 
00091     Cnt_curr =  LPC_QEI->POS;       //e. read accumulated value of counter
00092     if (LPC_QEI->INTSTAT & 0x0008) {
00093         data_Rdy = 0x0004;          //e. data for Cnt_Pls or Cnt_Mns calculation are ready
00094 
00095         if (++halfQEIPeriod & 0x0001) { //e. period elapsed, we can calculate Cnt_Dif
00096             data_Rdy = 0x000C;
00097         }
00098     }
00099     LPC_QEI->CLR = 0x1fff;          //e. reset interrupt request //r. сбросить запрос прерывания
00100 }
00101 /******************************************************************************
00102 ** Function name:       SetIntLatch
00103 **
00104 ** Descriptions:        Set timer for accumulation period
00105 **
00106 ** parameters:          Period of accumulation
00107 ** Returned value:      None
00108 **
00109 ******************************************************************************/
00110 void SetIntLatch(uint32_t cycle)
00111 {
00112     LPC_TIM3->TCR = 0x2;                            //switch off and reset timer3
00113     if (cycle != 0) {
00114         LPC_TIM3->MR0 = (cycle<<2);                     //load new value
00115         LPC_TIM3->TCR = 1;                          //switch on timer3
00116     }
00117 }
00118 /******************************************************************************
00119 ** Function name:       SwitchRefMeandInt
00120 **
00121 ** Descriptions:        Enable/disable interrupt from reference meander
00122 **
00123 ** parameters:          switcher
00124 ** Returned value:      None
00125 **
00126 ******************************************************************************/
00127 void SwitchRefMeandInt(uint32_t s)
00128 {
00129     LPC_QEI->CLR = 0x1fff;          //e. reset all interrupts //r. сбросить все прерывания
00130     if (s)
00131         LPC_QEI->IEC = 0x1fff;          //e.  disable direction changing interrupt //r. запретить прерывание при изменении направления
00132     else
00133         LPC_QEI->IES = 0x0008;          //e.  enable direction changing interrupt //r. разрешить прерывание при изменении направления
00134 }
00135 /******************************************************************************
00136 ** Function name:       ExtLatch_IRQHandler
00137 **
00138 ** Descriptions:        Routine for external latch appearence processing
00139 **
00140 ** parameters:          None
00141 ** Returned value:      None
00142 **
00143 ******************************************************************************/
00144 __irq void EINT3_IRQHandler (void)
00145 {
00146 //LPC_GPIO2->FIOSET = 0x00000020;       //e. turn on the LED
00147     LatchPhase = LPC_PWM1->TC;          //e. read moment of latch
00148     LPC_TIM0->TCR = 1;                  //e. start Mltdrop delay timer
00149     LPC_GPIOINT->IO0IntClr |= 0x0000800;//e. clean interrupt request
00150 //LPC_GPIO2->FIOCLR = 0x00000020;       //e. turn off the LED
00151 }
00152 /******************************************************************************
00153 ** Function name:       IntLatch_IRQHandler
00154 **
00155 ** Descriptions:        Routine for Internal latch appearence processing
00156 **
00157 ** parameters:          None
00158 ** Returned value:      None
00159 **
00160 ******************************************************************************/
00161 __irq void IntLatch_IRQHandler (void)
00162 {
00163 //LPC_GPIO2->FIOSET |= 0x00000080;      // turn on the LED
00164     LatchPhase =(int)LPC_PWM1->TC;          //e. read moment of latch
00165     LPC_TIM3->IR = 0x0001;              //e. clear interrupt flag
00166     num = Sys_Clock;
00167 //  count++;
00168 //LPC_GPIO2->FIOCLR |= 0x00000080;      // turn off the LED
00169 }
00170 
00171 /******************************************************************************
00172 ** Function name:       SwitchMode
00173 **
00174 ** Descriptions:        Switch mode of device functionality
00175 **
00176 ** parameters:          None
00177 ** Returned value:      None
00178 **
00179 ******************************************************************************/
00180 int SwitchMode()
00181 {
00182 //-----------------------disable latch sources ---------------------
00183     SetIntLatch(0);                         //e. disable internal latch
00184     LPC_TIM3->IR = 0x0001;              //e. clear internal latch interrupt request
00185 
00186     LPC_GPIOINT->IO0IntEnR &= ~0x0000800;   //e. disable external latch
00187     LPC_GPIOINT->IO0IntClr |=  0x0000800;   //e. clean external latch interrupt request
00188 
00189     LPC_TIM0->TCR = 2;                      //e. stop and reset the multidrop delay timer
00190     LPC_TIM0->IR = 0x03F;               //e. clear internal latch interrupt request
00191 //----------------------wait while UART and DMA are active-------------
00192     if ( LPC_GPDMACH1->CConfig & DMA_BUSY)              //e. if DMA channel is busy, wait //r. если канал передачи занят, ждать
00193         return 0;
00194     LPC_GPDMACH1->CConfig &=  ~DMAChannelEn;            //e. disable DMA for UART transmition
00195     LPC_GPDMACH2->CConfig &=  ~DMAChannelEn;
00196 
00197     if (!(LPC_UART1->LSR & TRANS_SHIFT_BUF_EMPTY))      //e. transmit buffer is not empty //r. передающий буфер не пуст
00198         return 0;
00199     LPC_UART1->FCR |= 0x4;                              //e. reset TX FIFO
00200 
00201     LPC_TIM0->IR = 0x3F;                        //e. clear all interrupt flags
00202 //---------------------configure a new exchanging parameters------------
00203     if (Device_Mode > 3) {                      //e. external latch mode enabled
00204         LPC_TIM0->MR0 = 10;
00205         LPC_TIM0->MR1 = 50;                     //e. /10 = delay before enable signal (us)
00206 //   LPC_UART1->FCR &= ~0x08;                   //e. TX FIFO is not source for DMA request
00207 
00208 //  LPC_SC->DMAREQSEL = 0xC;                        //e. external latch delay timer is source for DMA request
00209 //  LPC_GPIOINT->IO0IntEnR |= 0x0000800;    //e. enable rising edge interrupt
00210     } else {                                    //e. internal latch mode enabled
00211         LPC_TIM0->MR0 = 10;
00212         LPC_TIM0->MR1 = 5000;                       //e. /10 = delay before enable signal (us)
00213 //  LPC_SC->DMAREQSEL = 0x3;                //e. FIFO generate DMA request
00214 
00215 //  LPC_SC->EXTINT = 0x8;                   //e. clean interrupt request
00216     }
00217 
00218     UART_SwitchSpeed(SRgR & 0x0030);
00219 
00220     if (Device_Mode == DM_INT_LATCH_DELTA_PS)
00221         SetIntLatch(50000);
00222     return 1;
00223 }
00224 
00225 /******************************************************************************
00226 ** Function name:       ServiceTime
00227 **
00228 ** Descriptions:        Routine for pseudoseconds counting
00229 **
00230 ** parameters:          None
00231 ** Returned value:      None
00232 **
00233 ******************************************************************************/
00234 void ServiceTime(void)// псевдосекундный счетчик.
00235 {
00236     time_1_Sec -= PrevPeriod;
00237 
00238     if (time_1_Sec < (PrevPeriod>>1)) { //1 sec elapsed with accurate 0.5 of main period
00239         time_1_Sec = DEVICE_SAMPLE_RATE_uks;
00240         Seconds++;
00241     }
00242     if (Seconds == 3) {
00243         Seconds++;
00244         close_all_loops();
00245     }
00246     Sys_Clock++; //e. increment of the system clock register //r. инкремент регистра временной сетки системы
00247     PrevPeriod = LPC_PWM1->MR0;
00248 } // ServiceTime
00249 
00250 /******************************************************************************
00251 ** Function name:       WDTFeed
00252 **
00253 ** Descriptions:        Feed watchdog timer to prevent it from timeout
00254 **
00255 ** parameters:          None
00256 ** Returned value:      None
00257 **
00258 ******************************************************************************/
00259 void WDTFeed( void )
00260 {
00261     LPC_WDT->FEED = 0xAA;       /* Feeding sequence */
00262     LPC_WDT->FEED = 0x55;
00263     return;
00264 }
00265 
00266 /******************************************************************************
00267 ** Function name:       CounterIquiryCycle_Init
00268 **
00269 ** Descriptions:        CounterIquiryCycle_Init setup demanded GPIOs for PWM1,
00270 **                      reset counter, all latches are enabled, interrupt
00271 **                      on PWMMR0, install PWM interrupt to the VIC table.
00272 **
00273 ** parameters:
00274 ** Returned value:
00275 **
00276 ******************************************************************************/
00277 void CounterIquiryCycle_Init(uint32_t cycle)
00278 {
00279     //PWM1 enabled after reset by default
00280     LPC_SC->PCLKSEL0 &= ~(3<<12);
00281     LPC_SC->PCLKSEL0 |=  (1<<12);       //PWM1 is synchronized by CCLK (100 MHz)(CCLK) PCLKSEL0 - Peripheral Clock Selection registers.
00282 
00283     LPC_PWM1->TCR = TCR_RESET;  /* Counter Reset */ //#define TCR_RESET     0x00000002 инкрементировать счетчик при спадении импульса ПВМ.
00284     LPC_PWM1->MCR = PWMMR0I |PWMMR0R;   //generate interrupt and reset timer counter ( PWMMR0I - прерывание генерируется когда PWMMR0 совподает со значением PWMTC. )
00285     //                                           ( PWMMR0R - сбрасывает PWMTC при совподении PWMTC и PWMMR0. )
00286 
00287     LPC_PWM1->CCR = 0x1;                //разрешить прерывание только при совпадении PWMTC с PWMMR0   (еще что то связано с загрузкой ТС)
00288 
00289 
00290     PrevPeriod = 10000;
00291     LPC_PWM1->MR0 = PrevPeriod;     /* set PWM cycle */// задание периода сброса счетчика.
00292     LPC_PWM1->PCR = PWMENA1;            //e. single edge control mode, PWM1 out enabled only включение выхода ШИМ 1.
00293     LPC_PWM1->LER = LER0_EN ;           //e. enable updating of register
00294     LPC_PWM1->TCR = TCR_CNT_EN | TCR_PWM_EN;    /* counter enable, PWM enable */ //включение счетчика и ШИМ
00295 
00296     NVIC_DisableIRQ(PWM1_IRQn );//запретить прерывание.
00297 
00298 
00299     return ;
00300 }
00301 
00302 __irq void TIMER0_IRQHandler()
00303 {
00304     int val = LPC_TIM0->IR;
00305     LPC_TIM0->IR |= 3;
00306 
00307     if (val & 1) {  //MAT 1.0 interrupt
00308         LPC_GPIO2->FIOSET |= 1<<6;      // turn on the LED
00309         LPC_TIM0->IR |= 1;
00310         return;
00311     }
00312     if (val & 2) { //MAT 1.1 interrupt
00313         LPC_GPIO2->FIOCLR |= 1<<6;      // turn on the LED
00314         LPC_TIM0->IR |= 2;
00315         return;
00316     }
00317     if (val & 4) {  //MAT 0.2 interrupt
00318 //    LPC_GPIO0->FIOSET2 |= 0xFF;               //set P0.23
00319 //  LPC_GPIO2->FIOSET |= 0x00000040;        // turn on the LED
00320 //  LPC_TIM0->IR |= 4;
00321         return;
00322     }
00323     return;
00324 }
00325 
00326 /******************************************************************************
00327 ** Function name:       ExtLatch_Init
00328 **
00329 ** Descriptions:        Initialization of external latch
00330 **
00331 ** parameters:          None
00332 ** Returned value:      None
00333 **
00334 ******************************************************************************/
00335 void ExtLatch_Init()
00336 {
00337     LPC_PINCON->PINSEL4 &= ~0xC000000;      //e. использовать P2.13 как GPIO.
00338     LPC_PINCON->PINSEL0 &= ~0x0C00000;      //e. использовать P0.11 как GPIO.
00339     LPC_GPIO0->FIODIR   &= ~0x0000800;      //e. использовать P0.11 вхлод.
00340     LPC_GPIOINT->IO0IntEnR &= ~0x0000800;   //e. отключить внутреннюю защелку.
00341     LPC_GPIOINT->IO0IntClr |=  0x0000800;   //e. сбросить запросы на прерывания
00342 
00343     NVIC_EnableIRQ(EINT3_IRQn );           // разрешить прерывания.
00344 
00345 //+++++++ initialization of timer for multidrop delay generation+++++++++++++++++++++++
00346     //e.  TIMER0 enabled by default
00347     LPC_SC->PCLKSEL0 &= ~(3<<2);         //e. сбросить частоту таймера 0
00348     LPC_SC->PCLKSEL0 |= (3<<2);          //e. установить частоту таймера 0 на CLK/8.
00349     LPC_TIM0->PR = 0;                          //e. установить делитель частоты в 0.
00350     LPC_TIM0->IR = 0x3F;                     //e. очистить флаги прерываний.
00351     LPC_TIM0->MCR = 1 |(1<<3)|MR1_RESET |MR1_STOP; //e. сбросить и остановить таймер после совпадения  MR1 и TC.
00352     LPC_TIM0->CCR = 0;                   //e. содержимое таймера загружается при появлении переднего фронта защелки.
00353     LPC_TIM0->CTCR = 0;                  //e. timer0 в режиме таймера.
00354 
00355     LPC_TIM0->MR0 = /*Device_blk.Address**/10;          //e. delay before UART transmitter loading
00356     LPC_TIM0->MR1 = /*Device_blk.Address**/5000;        //e. delay before UART transmitter start
00357     //e. set first empty) event of timer
00358     NVIC_DisableIRQ(TIMER0_IRQn );
00359 }
00360 /******************************************************************************
00361 ** Function name:       IntLatch_Init
00362 **
00363 ** Descriptions:        Initialization of iternal latch cycle generation
00364 **
00365 ** parameters:          None
00366 ** Returned value:      None
00367 **
00368 ******************************************************************************/
00369 void IntLatch_Init()
00370 {
00371     LPC_SC->PCONP |= (1<<23);  //включит TIME3(таймер)
00372     //e. by default timer3 mode is not counter (T3CTCR[1,0]=0)
00373 
00374     LPC_SC->PCLKSEL1 &= SYNC_CLCK4;  // частота входного сигнала равна CLCK/4
00375     LPC_SC->PCLKSEL1 |= (1<<14);         // timer 3 input frequency equal to CLCK/4
00376 
00377 //  LPC_PINCON->PINSEL1 |= (3<<16);       //e. CAP 3.1 is connected to P0.24
00378     //e. by default CAP3.0 is connected to timer3
00379     LPC_TIM3->PR = 0;                                             //e. установить предделитель таймера3 на 0.
00380     LPC_TIM3->IR = 0x0001;                                  //e. очистить флаги прерываний.
00381     LPC_TIM3->MCR = MR0_RESET |MR0_INT_EN |MR0_NO_STOP; // установка флагов прерываний которые выполняются при совпадении таймера и МСR.
00382     LPC_TIM3->CCR = 0x0001;                                   //содержимое счетчика загружается по приходу переднего фронта защелки.
00383 
00384     NVIC_EnableIRQ(TIMER3_IRQn );                          //разрешить прерывания.
00385 }
00386 /*****************************************************************************
00387 ** Function name:       WDTInit
00388 **
00389 ** Descriptions:        Initialize watchdog timer, install the
00390 **                      watchdog timer interrupt handler
00391 **
00392 ** parameters:          None
00393 ** Returned value:      true or false, return false if the VIC table
00394 **              is full and WDT interrupt handler can be
00395 **              installed.
00396 **
00397 *****************************************************************************/
00398 uint32_t WDTInit( void )
00399 {
00400     NVIC_DisableIRQ(WDT_IRQn );
00401 
00402     LPC_WDT->TC = WDT_FEED_VALUE;   // once WDEN is set, the WDT will start after feeding
00403     LPC_WDT->MOD = WDEN;
00404 
00405     LPC_WDT->FEED = 0xAA;       // Feeding sequence
00406     LPC_WDT->FEED = 0x55;
00407 
00408     return 1;
00409 }
00410 /******************************************************************************
00411 **                            End Of File
00412 ******************************************************************************/