int main(void)
{
	unsigned int nCount;
	unsigned char vEncoder[20]="--------------------";
	int i;
  RCC_Configuration();
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
	NVIC_Configuration();
		EXTI_Configuration();
  USART1_Init();
	USART2_Init();															
	USART3_Init();
	UART4_Init();
	UART5_Init();
	SPI2_Init();
	SysTick_Init();
	//init_NRF24L01();
	RX_Mode();
	//nRF24L01_ISR();
	
  while(1)
{

	//Serial_PutString("While ");


}
}	 
Exemplo n.º 2
0
/***************************************************************************
Declaration : void init_mcu (void)

Function :    Initializes ATmega88 MCU
***************************************************************************/
void init_mcu (void)
{
#ifdef DEBUG
  debug();
#endif
  /* System Clocks Configuration */
  RCC_Configuration();
       
  /* Configure the GPIO ports */
  GPIO_Configuration();
 
  /* Configure EXTI Line9 to generate an interrupt on falling edge */
  EXTI_Configuration();

  /* SPI the GPIO ports */
  SPI_Configuration(); 
   
  /* USART  Configuration as SPI */
  USART1_Configuration();
  
  /* TIM2 Configuration */
  TIM2_Configuration();
  
  /* TIM3 Configuration */
  TIM3_Configuration();
  
  /* TIM4 Configuration */
  TIM4_Configuration();
  
   /* Configure RTC clock source and prescaler */
  RTC_Configuration(); 
   
  /* NVIC configuration */
  NVIC_Configuration();
}
Exemplo n.º 3
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
#ifdef DEBUG
  debug();
#endif
   
  /* Clock configuration */
  RCC_Configuration();

  /* Enable PWR and BKP clock */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

  /* GPIO configuration */
  GPIO_Configuration();

  /* Configure EXTI Line to generate an interrupt on falling edge */
  EXTI_Configuration();

  /* Configure RTC clock source and prescaler */
  RTC_Configuration();

  /* NVIC configuration */
  NVIC_Configuration();

  /* Configure the SysTick to generate an interrupt each 1 millisecond */
  SysTick_Configuration();

  /* Turn on led connected to GPIO_LED Pin6 */
  GPIO_SetBits(GPIO_LED, GPIO_Pin_6); 
  
  while (1)
  {
    /* Insert 1.5 second delay */
    Delay(1500);

    /* Wait till RTC Second event occurs */
    RTC_ClearFlag(RTC_FLAG_SEC);
    while(RTC_GetFlagStatus(RTC_FLAG_SEC) == RESET);

    /* Alarm in 3 second */
    RTC_SetAlarm(RTC_GetCounter()+ 3);
    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();

    /* Turn off led connected to GPIO_LED Pin6 */
    GPIO_ResetBits(GPIO_LED, GPIO_Pin_6); 

    /* Request to enter STOP mode with regulator in low power mode*/
    PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);
    
    /* At this stage the system has resumed from STOP mode -------------------*/
    /* Turn on led connected to GPIO_LED Pin6 */
    GPIO_SetBits(GPIO_LED, GPIO_Pin_6); 

    /* Configures system clock after wake-up from STOP: enable HSE, PLL and select 
       PLL as system clock source (HSE and PLL are disabled in STOP mode) */
    SYSCLKConfig_STOP();
  }
}
Exemplo n.º 4
0
/**
  * @brief   Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* Setup the microcontroller system. Initialize the Embedded Flash Interface,  
     initialize the PLL and update the SystemFrequency variable. */
  SystemInit();

  /* Initialize LEDs and Key Button mounted on STM3210X-EVAL board */       
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_PBInit(Button_KEY, Mode_EXTI);

  /* Enable PWR and BKP clock */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

  /* Configure EXTI Line to generate an interrupt on falling edge */
  EXTI_Configuration();

  /* Configure RTC clock source and prescaler */
  RTC_Configuration();

  /* NVIC configuration */
  NVIC_Configuration();

  /* Configure the SysTick to generate an interrupt each 1 millisecond */
  SysTick_Configuration();

  /* Turn on LED1 */
  STM_EVAL_LEDOn(LED1);
  
  while (1)
  {
    /* Insert 1.5 second delay */
    Delay(1500);

    /* Wait till RTC Second event occurs */
    RTC_ClearFlag(RTC_FLAG_SEC);
    while(RTC_GetFlagStatus(RTC_FLAG_SEC) == RESET);

    /* Alarm in 3 second */
    RTC_SetAlarm(RTC_GetCounter()+ 3);
    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();

    /* Turn off LED1 */
    STM_EVAL_LEDOff(LED1);

    /* Request to enter STOP mode with regulator in low power mode*/
    PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);
    
    /* At this stage the system has resumed from STOP mode -------------------*/
    /* Turn on LED1 */
    STM_EVAL_LEDOn(LED1);

    /* Configures system clock after wake-up from STOP: enable HSE, PLL and select 
       PLL as system clock source (HSE and PLL are disabled in STOP mode) */
    SYSCLKConfig_STOP();
  }
}
Exemplo n.º 5
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
#ifdef DEBUG
  debug();
#endif

  /* Configure the system clocks */
  RCC_Configuration();

  /* Configure GPIOs */
  GPIO_Configuration();

  /* Configures the EXTI Lines */
  EXTI_Configuration();
  
  /* Configures the DMA Channel */
  DMA_Configuration();
  
  /* Configures the USART1 */
  USART_Configuration();
    
#ifdef  VECT_TAB_RAM
  /* Set the Vector Table base location at 0x20000000 */ 
  NVIC_SetVectorTable(NVIC_VectTab_RAM, 0x0);
#else  /* VECT_TAB_FLASH  */
  /* Set the Vector Table base location at 0x08000000 */ 
  NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0);
#endif

  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
  
  /* Enable the DMA1 Channel 5 Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel5_IRQChannel;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Enable the EXTI9_5  Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQChannel;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
  NVIC_Init(&NVIC_InitStructure);
    
  while (1)
  {
    if(LowPowerMode == 1)
    {

      GPIO_ResetBits(GPIO_LED, GPIO_Pin_7 | GPIO_Pin_8);

      /* Request to enter WFI mode */
      __WFI();
      LowPowerMode = 0;
    }

    Delay(0xFFFFF);
    GPIO_WriteBit(GPIO_LED, GPIO_Pin_6, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIO_LED, GPIO_Pin_6)));
  }
}
Exemplo n.º 6
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
#ifdef DEBUG
  debug();
#endif

  /* System Clocks Configuration */
  RCC_Configuration();

  /* GPIO configuration */
  GPIO_Configuration();

  /* Check if the system has resumed from WWDG reset */
  if (RCC_GetFlagStatus(RCC_FLAG_WWDGRST) != RESET)
  { /* WWDGRST flag set */
    /* Set GPIO_LED pin 6 */
    GPIO_SetBits(GPIO_LED, GPIO_Pin_6);

    /* Clear reset flags */
    RCC_ClearFlag();
  }
  else
  { /* WWDGRST flag is not set */
    /* Reset GPIO_LED pin 6 */
    GPIO_ResetBits(GPIO_LED, GPIO_Pin_6);
  }

  /* Configure Key Button EXTI Line to generate an interrupt on falling edge */
  EXTI_Configuration();

  /* NVIC configuration */
  NVIC_Configuration();

  /* WWDG configuration */
  /* Enable WWDG clock */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_WWDG, ENABLE);

  /* WWDG clock counter = (PCLK1/4096)/8 = 244 Hz (~4 ms)  */
  WWDG_SetPrescaler(WWDG_Prescaler_8);

  /* Set Window value to 65 */
  WWDG_SetWindowValue(65);

  /* Enable WWDG and set counter value to 127, WWDG timeout = ~4 ms * 64 = 262 ms */
  WWDG_Enable(127);

  /* Clear EWI flag */
  WWDG_ClearFlag();

  /* Enable EW interrupt */
  WWDG_EnableIT();

  while (1)
  {}
}
Exemplo n.º 7
0
int main()
{
	DBG_Configuration();
	SystemClock_Configuration();
	DelayManager::DelayMs(150);
	RCC_Configuration();
	GPIO_Configuration();
	EXTI_Configuration();
	NVIC_Configuration();
	I2C_Configuration(&i2c);
	USART_Configuration(&uart);
	DMA_I2C_TX_Configuration(&i2cDmaTx);
	//__HAL_LINKDMA(&i2c, hdmatx, i2cDmaTx);

	MX_USB_DEVICE_Init();

	systemMode = LOADING;
	graphMode = SECONDS;

	display.initDisplay(&i2c);
	display.setFont(font5x7);
	display.clearScreen();
	display.printf(12, 50, logoStr);
	display.drawLine(0, 44, 127, 44);
	display.printf(12, 15, ".... LOADING ....");
	display.drawFramebuffer();

	sensorOk = co2sensor.initSensor(&uart);
	systemMode = ACTIVE;
	if (!sensorOk)
	{
		display.clearScreen();
		display.printf(12, 50, logoStr);
		display.drawLine(0, 44, 127, 44);
		display.printf(12, 15, errorStr);
		display.drawFramebuffer();
		errorHandler(NULL);
	}

	osThreadDef(processSensorThread, processSensorTask, osPriorityNormal, 0, 128);
	processSensorTaskHandle = osThreadCreate(osThread(processSensorThread), NULL);

	osThreadDef(processKeysThread, processKeysTask, osPriorityLow, 0, configMINIMAL_STACK_SIZE);
	processKeysTaskHandle = osThreadCreate(osThread(processKeysThread), NULL);

	osThreadDef(drawDataThread, drawDataTask, osPriorityHigh, 0, 256);
	drawDataTaskHandle = osThreadCreate(osThread(drawDataThread), NULL);

	osKernelStart();
	
	while (true)
	{
	}
}
Exemplo n.º 8
0
void Touch_Init()
{
	SPI_TouchConfiguration();
	EXTI_Configuration();
	NVIC_TouchConfiguration();
#ifndef ADJUST_TOUCH
	touch_adjust();
#else	 
	if(get_adjdata())return;//已经校准
	else touch_adjust();  	//屏幕校准,带自动保存
#endif	  
}
Exemplo n.º 9
0
//------------------------------------------------------------------------------
//                          === Initialize Function ===
//------------------------------------------------------------------------------
void Init_Main(void)
{
	RCC_Configuration();
//  RCC_GetClocksFreq(&rcc_clocks);
	GPIO_Configuration();
	NVIC_Configuration();
	DMA_Configuration();
	ADC_Configuration();
//  TIM_Configuration();
	EXTI_Configuration();

	nRF24_init();
//	nRF24_ClearIRQFlags();

	USART1_Init(57600);   // in 36mhz error 0% 
}
Exemplo n.º 10
0
void Platform_Init(void)
{
    RCC_Configuration();
    GPIO_Configuration();
    NVIC_Configuration();
	Timer_Configuration();
	USART_Configuration();			  
	EXTI_Configuration();
    delay_init(72);

	RS485_1_RX;				 //RS485 receive mode
	RS485_2_RX;				 //RS485 receive mode
   
//	IWDG_Configuration(781); //初始化独立看门狗5s

}
Exemplo n.º 11
0
/**
  * @brief  Main program.
  * @param  None
  * @retval : None
  */
int main(void)
{
  /* Configure the system clocks */
  RCC_Configuration();

  /* Configure GPIOs */
  GPIO_Configuration();

  /* Configures the EXTI Lines */
  EXTI_Configuration();
  
  /* Configures the DMA Channel */
  DMA_Configuration();
  
  /* Configures the USART1 */
  USART_Configuration();

  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
  
  /* Enable the DMA1 Channel 5 Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel5_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Enable the EXTI9_5  Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
  NVIC_Init(&NVIC_InitStructure);
    
  while (1)
  {
    if(LowPowerMode == 1)
    {

      GPIO_ResetBits(GPIO_LED, GPIO_Pin_7 | GPIO_Pin_8);

      /* Request to enter WFI mode */
      __WFI();
      LowPowerMode = 0;
    }

    Delay(0xFFFFF);
    GPIO_WriteBit(GPIO_LED, GPIO_Pin_6, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIO_LED, GPIO_Pin_6)));
  }
}
Exemplo n.º 12
0
/**
  * @brief  Main program.
  * @param  None
  * @retval : None
  */
int main(void)
{
  /* Configure the system clocks */
  RCC_Configuration();

  /* Configure GPIOs */
  GPIO_Configuration();

  /* Configures the EXTI Lines */
  EXTI_Configuration();

  /* Configure one bit for preemption priority */
  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
  
  /* Enable the EXTI0 Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = PreemptionPriorityValue;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
  
  /* Enable the EXTI9_5 Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
  
  /* Configure the SysTick Handler Priority: Preemption priority and subpriority */
  NVIC_SetPriority(SysTick_IRQn, (!PreemptionPriorityValue << 0x03));
  
  while (1)
  {
    if(PreemptionOccured != FALSE)
    {
      GPIO_WriteBit(GPIO_LED, GPIO_Pin_6, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIO_LED, GPIO_Pin_6)));
      Delay(0x5FFFF);
      GPIO_WriteBit(GPIO_LED, GPIO_Pin_7, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIO_LED, GPIO_Pin_7)));
      Delay(0x5FFFF);
      GPIO_WriteBit(GPIO_LED, GPIO_Pin_8, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIO_LED, GPIO_Pin_8)));
      Delay(0x5FFFF);
      GPIO_WriteBit(GPIO_LED, GPIO_Pin_9, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIO_LED, GPIO_Pin_9)));
      Delay(0x5FFFF); 
    }
  }
}
Exemplo n.º 13
0
//------------------------------------------------------------------------------
//                       	=== Initialize Function ===
//------------------------------------------------------------------------------
void Init_Main(void)
{
    RCC_Configuration();
    //RCC_GetClocksFreq(&rcc_clocks);
	GPIO_Configuration();
	NVIC_Configuration();
	DMA_Configuration();
	ADC_Configuration();
	TIM_Configuration();
	EXTI_Configuration();
    Tim_Encoder_initial();
	
    USART1_Init(57600);	// in 36mhz error 0%
    USART3_Init(115200);// in 72mhz error 0%
    //if (SysTick_Config(rcc_clocks.SYSCLK_Frequency / 1000))
    //{ 
        /* Capture error */
    //    while (1);
    //}
}
Exemplo n.º 14
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
    GPIO_InitPara GPIO_InitStructure;
    
    /* Configure the LED1 GPIO */ 
    GD_EVAL_LEDInit(LED1);
    /* Turn on LED1 */
    GD_EVAL_LEDOn(LED1);
    /* Enable PWR clock */
    RCC_APB1PeriphClock_Enable(RCC_APB1PERIPH_PWR, ENABLE);
    /* Configure the EXTI line16 */
    EXTI_Configuration();
    /* NVIC configuration */
    NVIC_Configuration();
    /* Configure the LVD threshold to 2.9V(GD32F130_150) or 4.5V(GD32F170_190), and enable the LVD */
    PWR_LVDConfig(PWR_LVDT_7, ENABLE);

    while(1)
    {
    }
}
Exemplo n.º 15
0
/*..........................................................................*/
void BSP_init(void) {
	SystemInit();         /* initialize STM32 system (clock, PLL and Flash) */

#ifdef Q_SPY
	//初始化QS
    if (QS_INIT((void *)0) == 0) {    /* initialize the QS software tracing */
        Q_ERROR();
    }
#endif

    RCC_APBClockEnable();


	BSP_USART_Init(); ///使能调试串口,开发板上是USART3

	Periph_Lowlevel_Init();	///所有外设初始化

	EXTI_Configuration();

	NVIC_Configuration();

}
Exemplo n.º 16
0
Arquivo: key.c Projeto: mangqu/LED_RTT
void rt_hw_key_init(void)
{
	rt_err_t result;
	/* config gpio */
	{
		EXTI_Configuration();
		NVIC_Configuration();
	}

	key = (struct rt_device_key *)rt_malloc(sizeof(struct rt_device_key));
	if (key == RT_NULL)
		return;	//no memory yet

	/* clear device structure */
	rt_memset(&(key->parent), 0, sizeof(struct rt_device));

	/* init device structure */
	key->parent.type = RT_Device_Class_Unknown;
	key->parent.init = RT_NULL;
	key->parent.control = RT_NULL;
	key->parent.open = RT_NULL;
	key->parent.close = RT_NULL;
	key->parent.write = RT_NULL;
	key->parent.read = RT_NULL;

	key->poll_timer = rt_timer_create("key scan", key_timeout, RT_NULL, 
		RT_TICK_PER_SECOND/20, RT_TIMER_FLAG_PERIODIC);
	key->ops = &_stm32_key_ops;
	
	/* register led to device */
	result = rt_device_register(&(key->parent), "key", RT_DEVICE_FLAG_WRONLY);
	if (result != RT_EOK)
	{
		rt_kprintf("key device register error!\n");
	}
}
Exemplo n.º 17
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* System Clocks Configuration */
  RCC_Configuration();
       
  /* NVIC configuration */
  NVIC_Configuration();

  /* Configure the GPIO ports */
  GPIO_Configuration();

  /* Configure the EXTI Controller */
  EXTI_Configuration();


/* SC_USART configuration ----------------------------------------------------*/
  /* SC_USART configured as follow:
        - Word Length = 9 Bits
        - 0.5 Stop Bit
        - Even parity
        - BaudRate = 12096 baud
        - Hardware flow control disabled (RTS and CTS signals)
        - Tx and Rx enabled
        - USART Clock enabled
        - USART CPOL Low
        - USART CPHA on first edge
        - USART Last Bit Clock Enabled
  */

  /* SC_USART Clock set to 4.5MHz (PCLK1 = 36 MHZ / 8) */
  USART_SetPrescaler(SC_USART, 0x04);
  /* SC_USART Guard Time set to 2 Bit */
  USART_SetGuardTime(SC_USART, 0x2);
  
  USART_ClockInitStructure.USART_Clock = USART_Clock_Enable;
  USART_ClockInitStructure.USART_CPOL = USART_CPOL_Low;
  USART_ClockInitStructure.USART_CPHA = USART_CPHA_1Edge;
  USART_ClockInitStructure.USART_LastBit = USART_LastBit_Enable;
  USART_ClockInit(SC_USART, &USART_ClockInitStructure);

  USART_InitStructure.USART_BaudRate = 12096;
  USART_InitStructure.USART_WordLength = USART_WordLength_9b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1_5;
  USART_InitStructure.USART_Parity = USART_Parity_Even;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_Init(SC_USART, &USART_InitStructure);  

  /* Enable the SC_USART Parity Error Interrupt */
  USART_ITConfig(SC_USART, USART_IT_PE, ENABLE);

  /* Enable SC_USART */
  USART_Cmd(SC_USART, ENABLE);

  /* Enable the NACK Transmission */
  USART_SmartCardNACKCmd(SC_USART, ENABLE);

  /* Enable the Smartcard Interface */
  USART_SmartCardCmd(SC_USART, ENABLE);

  /* Loop while no Smartcard is detected */  
  while(CardInserted == 0)
  {
  }

  /* Read Smartcard ATR response */ 
  for(index = 0; index < 40; index++, Counter = 0)
  {
    while((USART_GetFlagStatus(SC_USART, USART_FLAG_RXNE) == RESET) && (Counter != SC_Receive_Timeout))
    {
      Counter++;
    }

    if(Counter != SC_Receive_Timeout)
    {
      DST_Buffer[index] = USART_ReceiveData(SC_USART);
    }
  }

  /* Decode ATR */
  CardProtocol = SC_decode_Answer2reset(DST_Buffer);

  /* Test if the inserted card is ISO7816-3 T=0 compatible */
  if(CardProtocol == 0)
  {
    /* Inserted card is ISO7816-3 T=0 compatible */
    ATRDecodeStatus = PASSED;
  }
  else 
  { 
    /* Inserted Smartcard is not ISO7816-3 T=0 compatible */
    ATRDecodeStatus = FAILED;
  } 

  while (1)
  {   
  }
}
Exemplo n.º 18
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void) {
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */
  
  /* System Clocks Configuration */
  RCC_Configuration();
  
  /* System Tick Configuration at 1us */
  SysTick_Config(SystemCoreClock / 1000000);
  
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
  
  /* TIM2 Configuration (Client & ATFC Server) */
  TIM2_Configuration();
  
#elif defined USE_EQDAS_SERVER
  
  /* TIM4 Configuration */
  TIM4_Configuration();
  
#endif
  
  /* TIM5 Configuration (GLCD & Ethernet) */
  TIM5_Configuration();
  
  /* TIM6 Configuration (RTC load) */
  //TIM6_Configuration();
  
  /* CLCD Configuration */
  CLCD_Configuration();
  
  /* GLCD Configuration */
  GLCD_Configuration();
  
  /* UART1 Configuration */
  UART_Configuration();
  
  /* RTC configuration by setting the time by Serial USART1 */
  RTC_SetTimeBySerial();
  
  /* Let user set the IP through terminal forcefully */
  //ForceIPSetBySerial();

  /* WIZ820io SPI1 configuration */
  WIZ820io_SPI1_Configuration();
  
  /* W5200 Configuration */
  Set_network();
  
  /* Print WIZ820io configuration */
  printSysCfg();
  
  /* EXTI Configuration */
  EXTI_Configuration();
  
  /* FatFS configuration */
  f_mount(0, &fs);  // mSD
  //f_mount(1, &fs);  // NAND
  
  /* Display Total size of SD card in MB scale */
  SD_TotalSize();
  
  /* Scan all files in mSD card */
  //scan_files(path);
  
  /* MAL configuration */
  //Set_System();
  
  /* UMS configuration */
  //Set_USBClock();
  //USB_Interrupts_Config();
  //USB_Init();
  
  /* loop upon completion of USB Enumeration */
  //while (bDeviceState != CONFIGURED);
  
  /* ATFC Algorithm GPIO */
  ATFC_GPIO_Configuration();
  
  /* ATFC Parameter Initialization */
  ATFCAlgorithmParameterSetup();
  
  /* GPS-UART3 Configuration - This have to be here otherwise it wouldn't work */
  GPS_Configuration();
  
  // For TCP client's connection request delay
  presentTime = my_time;

  /* Create directory and sub directory in accordance with current date */
  filePath = CreateDirectoryAccordingly(GetYearAndMergeToInt(), GetMonthAndMergeToInt(), 
                                        GetDayAndMergeToInt(), RTC_GetCounter() / 3600);
  
  /* Create file in append mode in accordance with current minute */
  CreateFileAppendModeAccordingly(filePath, (RTC_GetCounter() % 3600) / 60);
  
  /* Clear GLCD to better represent waveform */
  GLCD_Clear();
  
  //BKP_WriteBackupRegister(BKP_DR8, 0);
  
  // When everything is set, print message
  printf("\r\n\n - System is ready - ");
  
  while (1) {
    
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
    
    /* Index synchronization routine -----------------------------------------------*/
    if(SyncFlag) { // prevent unpleasant impuse from happening
      // Index synchronization dedicated to GLCD & Ethernet
      if(arrIdx != index) {
        // Index synchronization
        arrIdx = index;
      }
    }
    /* End of index synchronization routine -----------------------------------------*/
    
    if(TimerCount > 999) { // 0 ~ 999 (1000) = 1 sec
      TimerCount = 0;
      
      //my_time++;  // uncomment when tcp connection is needed
      
      /* Setup TCP Client or Server -------------------------------------------------*/
      /* Please open config.h file to choose a proper board you wish to use ---------*/    
      /* Start TCP Client process */
      ProcessTcpClient(SOCK_ZERO);  // TCP Client
      
      /* Parameter setting Server side with port 5050 in default */
      ATFCTcpServer(SOCK_TWO, EQDAS_Conf_PORT);  // SOCK_TWO because of flag conformity
      /*------------------------------------------------------------------------------*/
      
      /* Process Parameter Text Stream -----------------------------------------------*/
      if(PCFlag) {  // EQDAS Client System and ATFC Algorithm Setting
        PCFlag = false;
        
        ProcessParameterStream();
      }
      /* End of Parameter process ----------------------------------------------------*/
    }

    /* 10ms interval between points */
    if(TIM5Count >= 9) {
      TIM5Count = 0;
      
      // Make a copy from raw collected data to temporary array
      CopyToTmpArray(arrIdx);
      
      // Determine KMA scale
      KMAGrade = DetermineKMA(arrIdx);
      
      // Check sign bit and apply to int container
      CheckSignAndToInt(arrIdx); // this function also cuts surplus 1G
      
      /* Switch menu & waveform display through graphic lcd */
      GLCD_AxisViewWithWaveform(mode, arrIdx);
      
      //int mATFCBit;
      //mATFCBit_lcd = mAxisBuf.ATFCBit_lcd[arrIdx];
      
      int AxisDataToATFCAlgorithm, mATFCEventDetection;
      AxisDataToATFCAlgorithm = mAxisBuf.tmp_data_y_lcd[arrIdx];  // Axis Z
      ATFCAlgorithm(AxisDataToATFCAlgorithm);
      mATFCEventDetection = EventDetection;
      
      /* Display KMA Intensity on Graphic LCD */
      GLCD_DisplayKMAIntensity(KMAGrade, mATFCEventDetection);
      
      /* Prevent access to volatile variable warning */
      /* This have to be here in order to correct data to be used in ATFC */      
      /* ATFC Server side for each EQ DAS Client */
      if(EQATFCFlag) {
        int mYear, mMonth, mDay, mHour, mMin, mSec, mTMSec;
        mYear = year; mMonth = month; mDay = day;
        mHour = hour; mMin = minute; mSec = second; mTMSec = arrIdx;
        
        int mX, mY, mZ, mATFCBit;
        mX = mAxisBuf.tmp_data_x_lcd[arrIdx] >> 2;
        mY = mAxisBuf.tmp_data_y_lcd[arrIdx] >> 2;
        mZ = mAxisBuf.tmp_data_z_lcd[arrIdx] >> 2;
        mATFCBit = mATFCEventDetection;
        
        char ATFC_Buf[40];
        sprintf(ATFC_Buf, "%04d%02d%02d_%02d%02d%02d%02d_%+05d_%+05d_%+05d_%d\r\n",
                mYear, mMonth, mDay, mHour, mMin, mSec, mTMSec,
                mX, mY, mZ, mATFCBit);
        // Only when socket is established, allow send data
        if(getSn_SR(SOCK_TWO) == SOCK_ESTABLISHED) {  // SOCK_TWO : PC
          /* send selected data */
          send(SOCK_TWO, (uint8_t*)ATFC_Buf, strlen(ATFC_Buf), (bool)false);
        }
      }
      // Copy to data buffer to be written through FATFS
      //CopyToFatFsDataBuffer(arrIdx);
    }
    
    /* RTC 1Hz interrupt */
    if(RTCTimeDisplay) { // 1Hz calibrated by RTC
      RTCTimeDisplay = false;
      
      int TimeVar;
      TimeVar = RTC_GetCounter();
      /* Compute hour */
      THH = TimeVar / 3600;
      /* Compute minute */
      TMM = (TimeVar % 3600) / 60;
      /* Compute second */
      TSS = (TimeVar % 3600) % 60;
      
      /* Refresh date on every 1s */
      year = GetYearAndMergeToInt();
      month = GetMonthAndMergeToInt();
      day = GetDayAndMergeToInt();
      hour = THH; minute = TMM; second = TSS; tmsecond = 0;
      
      if(ThirtyMinuteMark == 1799) {
        ThirtyMinuteMark = 0;
        ThirtyMinuteFlag = true;
      } else {
        ThirtyMinuteMark++; 
      }
      
      /* Adjust realtime clock deviation */
      if(hour > 23) {
        int i, currentDay, mDay, mHour, mMin, mSec;
        mDay = hour / 24;
        
        for(i=0; i<mDay; i++) {
          IncreaseSingleDay();
          if(i == mDay - 1) {
            currentDay = (GetMonthAndMergeToInt() * 100) + GetDayAndMergeToInt();
            BKP_WriteBackupRegister(BKP_DR3, currentDay); // Save Month and Date
          }
        }
        mHour = THH % 24;
        mMin = TMM;
        mSec = TSS;
        
        /* Change the current time */
        RTC_SetCounter(mHour*3600 + mMin*60 + mSec);
      }
    }
    
#endif
    
    if(ParseGPS) {
      ParseGPS = false;
      
      char *srcstr = "$GPRMC";
      char *token = ",";  char *processedString;
      char StringYear[3], StringMonth[3], StringDay[3], StringHour[3], StringMinute[3], StringSecond[3];
      int GPSYear, GPSMonth, GPSDay, GPSHour, GPSMinute, GPSSecond;
      if(strncmp((char const*)GPS_Buffer, srcstr, 6) == 0) {
        //printf("GPS_Buffer = %s\r\n\r\n", (char*)GPS_Buffer);
        processedString = strtok((char*)GPS_Buffer, token);
        processedString = strtok(NULL, token);
        
        strncpy(StringHour, processedString, 2); StringHour[2] = 0;
        strncpy(StringMinute, processedString+2, 2); StringMinute[2] = 0;
        strncpy(StringSecond, processedString+4, 2); StringSecond[2] = 0;
        
        GPSHour = atoi(StringHour) + 9; // Current Hour = StringHour + 9
        GPSMinute = atoi(StringMinute);
        GPSSecond = atoi(StringSecond);
        
        int i; for(i=4; i!=0 ; i--) processedString = strtok(NULL, token);
        
        strncpy(StringYear, processedString+4, 2); StringYear[2] = 0;
        strncpy(StringMonth, processedString+2, 2); StringMonth[2] = 0;
        strncpy(StringDay, processedString, 2); StringDay[2] = 0;
        
        GPSYear = atoi(StringYear) + 2000;  // Currnet Year = StringYear + 2000
        GPSMonth = atoi(StringMonth);
        GPSDay = atoi(StringDay);
        
        /* The Year is chosen as criteria to the time */
        if( (GPSYear == GetYearAndMergeToInt()) && ThirtyMinuteFlag ) { // only when year matches between RTC and GPS
          ThirtyMinuteFlag = false;
          
          if(GPSMonth != GetMonthAndMergeToInt() || GPSDay != GetDayAndMergeToInt() ||
             GPSHour != THH || GPSMinute != TMM || GPSSecond != TSS) {
            /* Change the month and day */
            TranslateIntoMonth(GPSMonth);
            TranslateIntoDay(GPSDay);
            
            /* Save year data to unresettable backup register addr. no. 3 */
            int MMDD; MMDD = (GPSMonth * 100) + GPSDay;
            BKP_WriteBackupRegister(BKP_DR3, MMDD); // Save Month and Date  
            
            /* Change the current time */
            RTC_SetCounter(GPSHour*3600 + GPSMinute*60 + GPSSecond);
            
            printf("GPSHour = %d\r\n", GPSHour);
            printf("GPSMinute = %d\r\n", GPSMinute);
            printf("GPSSecond = %d\r\n\r\n", GPSSecond);
            
            printf("GPSYear = %d\r\n", GPSYear);
            printf("GPSMonth = %d\r\n", GPSMonth);
            printf("GPSDay = %d\r\n\r\n", GPSDay);
            
            printf("GPS-to-System synchronization complete!\r\n\r\n");
          }
        }
      }
    }
    
    if(ParseUSART1) {
      ParseUSART1 = false;
      
      // run some test on SDIO
      //SDIO_TEST();

#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
      
      /* Print WIZ820io configuration */
      printSysCfg();

      printf("\r\n");
      printf("BKP_DR1 = %d\r\n", BKP_ReadBackupRegister(BKP_DR1));
      printf("BKP_DR2 = %d\r\n", BKP_ReadBackupRegister(BKP_DR2));
      printf("BKP_DR3 = %d\r\n", BKP_ReadBackupRegister(BKP_DR3));
      printf("BKP_DR4 = %d\r\n", BKP_ReadBackupRegister(BKP_DR4));
      printf("BKP_DR5 = %d\r\n", BKP_ReadBackupRegister(BKP_DR5));
      printf("BKP_DR6 = %d\r\n", BKP_ReadBackupRegister(BKP_DR6));
      printf("BKP_DR7 = %d\r\n", BKP_ReadBackupRegister(BKP_DR7));
      printf("BKP_DR8 = %d\r\n", BKP_ReadBackupRegister(BKP_DR8));
      printf("BKP_DR9 = %d\r\n", BKP_ReadBackupRegister(BKP_DR9));
      printf("BKP_DR10 = %d\r\n", BKP_ReadBackupRegister(BKP_DR10));
      printf("BKP_DR11 = %d\r\n", BKP_ReadBackupRegister(BKP_DR11));
      printf("BKP_DR12 = %d\r\n", BKP_ReadBackupRegister(BKP_DR12));
      printf("BKP_DR13 = %d\r\n", BKP_ReadBackupRegister(BKP_DR13));
      printf("BKP_DR14 = %d\r\n", BKP_ReadBackupRegister(BKP_DR14));
      printf("BKP_DR15 = %d\r\n", BKP_ReadBackupRegister(BKP_DR15));
      printf("BKP_DR16 = %d\r\n\r\n", BKP_ReadBackupRegister(BKP_DR16));
      
      printf("RX_BUF = %s\r\n", RX_BUF);
      
      /*
      printf("\r\nstrlen(HEADER) : %d %s", strlen(HEADER), HEADER);
      
      printf("\r\nf_mkdir1 : ");
      char *dirPath = "0:/20130517";
      res = f_mkdir(dirPath);
      FPrintFatResult(res);
      
      printf("\r\nf_mkdir2 : ");
      dirPath = "0:/20130517/22H-23H";
      res = f_mkdir(dirPath);
      FPrintFatResult(res);
      
      char *filePath = "0:/20130517/2-23H/test.txt";
      // Create log file on the drive 0
      res = open_append(&fsrc, filePath);
      FPrintFatResult(res);
      
      if(res == FR_OK) {
        printf("test.txt successfully created\r\n");
        
        // Write buffer to file
        int bytesWritten;
        bytesWritten = f_printf(&fsrc, HEADER);
        printf("\r\n%d of bytesWritten", bytesWritten);
        
        // Close file
        f_close(&fsrc);
        
      } else if ( res == FR_EXIST ) {
        printf("\r\ntest.txt already exist");
      }
      */
      
      
#elif (defined) USE_EQDAS_SERVER
      
      char buffer[40];
      sprintf(buffer, "%s_%s_%s_%s_%s\r\n",
                DAQBoardOne[arrIdx].Date,
                DAQBoardOne[arrIdx].Time,
                DAQBoardOne[arrIdx].AxisX,
                DAQBoardOne[arrIdx].AxisY,
                DAQBoardOne[arrIdx].AxisZ);
      printf("\r\nRX_BUF : %s, strlen(RX_BUF) : %d", (char*)RX_BUF, strlen((char*)RX_BUF));
      printf("\r\nstrlen(buffer) = %d\n%s", strlen(buffer), buffer);
      
#endif
    
    }
    
// following routine is only necessary when the board works as server
#if defined USE_EQDAS_SERVER
    
    /* Server also needs to have get CLCD going while running */
    /* RTC 1Hz interrupt */
    if(RTCTimeDisplay) { // 1Hz calibrated by RTC
      RTCTimeDisplay = false;
      
      /* Adjust realtime clock deviation */
      if(hour > 23) {
        int i, currentDay, mDay, mHour, mMin, mSec;
        mDay = hour / 24;
        
        for(i=0; i<mDay; i++) {
          IncreaseSingleDay();
          if(i == mDay - 1) {
            currentDay = (GetMonthAndMergeToInt() * 100) + GetDayAndMergeToInt();
            BKP_WriteBackupRegister(BKP_DR3, currentDay); // Save Month and Date
          }
        }
        
        mHour = THH % 24;
        mMin = TMM;
        mSec = TSS;
        
        /* Change the current time */
        RTC_SetCounter(mHour*3600 + mMin*60 + mSec);
      }
      
      /* Display current time */
      Time_Display(RTC_GetCounter());
    }
    
    /* EQ-DAQ-01 Parsing routine ------------------------------------------------- */
    /* Set E1Flag indicate that we have valid connection from EQ-DAQ-01(port 5050) */
    if(E1Flag) {
      E1Flag = false; // clear flag since this routine excutes ceaselessly over time
      
      ProcessTextStream(EQ_ONE, (char*)RX_BUF, E1Order);
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag && !E2Flag) { // only when PC is connected and EQ-DAQ-02 is not connected
        // Send directly to PC
        SingleBoardDataToSendToPC(EQ_ONE, E1Order-10);
      }
      
      if(E1Order < 99) E1Order++;
      else E1Order = 0;
    }
    
    /* EQ-DAQ-02 Parsing routine ------------------------------------------------- */
    /* Set E2Flag indicate that we have valid connection from EQ-DAQ-02(port 6060) */
    if(E2Flag) {
      E2Flag = false;
      
      ProcessTextStream(EQ_TWO, (char*)RX_BUF, E2Order);
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag && !E1Flag) { // only when PC is connected and EQ-DAQ-01 is not connected
        // Send directly to PC
        //SendToPC(EQ_TWO, E2Order);
      }
      
      if(E2Order < 99) E2Order++;
      else E2Order = 0;
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag) {
        // Send directly to PC
        MultipleBoardDataToSendToPC(EQ_BOTH, E1Order-10, E2Order-10);
      }
    }
    
    /* Process server socket with each port */
    ProcessTcpServer(SOCK_ZERO, 5050);  // designated as for EQM-DAQ-01 with port 5050
    ProcessTcpServer(SOCK_ONE, 6060);   // designated as for EQM-DAQ-02 with port 6060
    ProcessTcpServer(SOCK_TWO, 7070);   // designated as for PC-CLIENT  with port 7070
    ProcessTcpServer(SOCK_THREE, 8080); // designated as for PC_DUMP    with port 8080
    
    /*
    ProcessTcpServer(SOCK_FOUR, 9090);   // designated as for TOBEUSED with port 9090
    ProcessTcpServer(SOCK_FIVE, 10010);   // designated as for TOBEUSED with port 10010
    ProcessTcpServer(SOCK_SIX, 10020);    // designated as for TOBEUSED with port 10020
    ProcessTcpServer(SOCK_SEVEN, 10030);  // designated as for TOBEUSED with port 10030
    */
      
#endif
      
  }
Exemplo n.º 19
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void) {
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */
  
  /* System Clocks Configuration */
  RCC_Configuration();
  
  /* System Tick Configuration at 1us */
  SysTick_Config(SystemCoreClock / 1000000);
  
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
  
  /* TIM2 Configuration */
  TIM2_Configuration();
  
  /* TIM3 Configuration */
  TIM3_Configuration();
  
  /* TIM6 Configuration (RTC load) */
  TIM6_Configuration();
  
#elif defined USE_EQDAS_SERVER
  
  /* TIM4 Configuration */
  TIM4_Configuration();
  
#endif
  
  /* CLCD Configuration */
  CLCD_Configuration();
  
  /* GLCD Configuration */
  GLCD_Configuration();
  
  /* UART1 Configuration */
  UART_Configuration();
  
  /* RTC configuration by setting the time by Serial USART1 */
  //RTC_SetTimeBySerial();

  /* WIZ820io SPI1 configuration */
  WIZ820io_SPI1_Configuration();
  
  /* W5200 Configuration */
  Set_network();
  
  /* Print WIZ820io configuration */
  printSysCfg();
  
  /* EXTI Configuration */
  EXTI_Configuration();
  
  /* FatFS configuration */
  f_mount(0, &fs);  // mSD
  //f_mount(1, &fs);  // NAND
  
  /* Display Total size of SD card in MB scale */
  SD_TotalSize();
  
  /* Scan all files in mSD card */
  scan_files(path);
  
  /* MAL configuration */
  //Set_System();
  
  /* UMS configuration */
  //Set_USBClock();
  //USB_Interrupts_Config();
  //USB_Init();
  
  /* loop upon completion of USB Enumeration */
  //while (bDeviceState != CONFIGURED);
  
  /* ATFC Algorithm GPIO */
  ATFC_GPIO_Configuration();
  
  /* ATFC Parameter Initialization */
  ATFCAlgorithmParameterSetup();
  
  // For TCP client's connection request delay
  presentTime = my_time;
  
  /* Clear CLCD before branch into main */
  CLCD_Clear();
  
  /* Alarm in 3 second */
  //RTC_SetAlarm(RTC_GetCounter() + 3);
  /* Wait until last write operation on RTC registers has finished */
  //RTC_WaitForLastTask();

  /* Create directory and sub directory in accordance with current date */
  //filePath = CreateDirectoryAccordingly(GetYearAndMergeToInt(), GetMonthAndMergeToInt(), 
                                        //GetDayAndMergeToInt(), RTC_GetCounter() / 3600);
  
  /* Create file in append mode in accordance with current minute */
  //CreateFileAppendModeAccordingly(filePath, (RTC_GetCounter() % 3600) / 60);
  
  // When everything is set, print message
  printf("\r\n\n - System is ready - ");
  
  while (1) {
    
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
    
    if(TimerCount > 1000) { // 0 ~ 999 (1000) = 1 sec
      TimerCount = 0;
      
      /*
      int x, y, z;
      x = mAxisBuf.tmp_data_x_lcd[index];
      y = mAxisBuf.tmp_data_y_lcd[index];
      z = mAxisBuf.tmp_data_z_lcd[index];
    
      char Serial_Buf[37];
      int hour, minute, second, tmsecond;
      hour = THH; minute = TMM; second = TSS; tmsecond = 0;
      sprintf(Serial_Buf, "%04d%02d%02d_%02d%02d%02d%02d_%+05d_%+05d_%+05d\r\n", 
                year, month, day, hour, minute, second, tmsecond, x, y, z);
      printf(Serial_Buf);
      */
      
      //my_time++;  // uncomment when tcp connection is needed
      
      /* Process Parameter Text Stream */
      if(PCFlag) {  // EQDAS Client System and ATFC Algorithm Setting
        PCFlag = false;
        
        ProcessParameterStream();
      }
    }
    
    /* Clock generated by TIM3 */
    if(ClientTimerCounter > 10) {  // 0 ~ 999 (1000) = 1 sec
      ClientTimerCounter = 0;
      
      int mAlgorithmContainer;
      
      year = GetYearAndMergeToInt();
      month = GetMonthAndMergeToInt();
      day = GetDayAndMergeToInt();
      hour = THH; minute = TMM; second = TSS; tmsecond = 0;
      
      int mYear, mMonth, mDay, mHour, mMin, mSec, mTMSec;
      mYear = year; mMonth = month; mDay = day;
      mHour = hour; mMin = minute; mSec = second; mTMSec = tmsecond;
      
      x = mAxisBuf.tmp_data_x_lcd[arrIdx];
      y = mAxisBuf.tmp_data_y_lcd[arrIdx];
      z = mAxisBuf.tmp_data_z_lcd[arrIdx];

      if(flag_uart) { // prevent unpleasant impuse
        // Index synchronization
        arrIdx = index; 
        
        // Make a copy from raw collected data to temporary array
        CopyToTmpArray(arrIdx);
          
        // Copy to Temporary GAL array
        CopyToTmpGalArray(arrIdx);
        
        // Calculate GAL and copy to single temporary GAL value
        CalculateGalAndCopyToGal(arrIdx);
        
        // Determine KMA scale
        DetermineKMA(arrIdx);
  
        // Check sign bit and apply to int container
        CheckSignAndToInt(arrIdx); // this function also cuts surplus 1G 
        
        /* Switch menu & waveform display through graphic lcd */
        GLCD_AxisViewWithWaveform(mode, arrIdx, x, y, z);
        
        if(GoATFCFlag) {
          // Apply ATFC Algorithm to Axis x
          ATFCAlgorithm(mAxisBuf.tmp_data_x_lcd[arrIdx]);
        }
      }

      if(EventDetection) {
        GPIO_WriteBit(GPIOE, GPIO_Pin_15, Bit_SET);
        mAlgorithmContainer = x;
      } else {
        GPIO_WriteBit(GPIOE, GPIO_Pin_15, Bit_RESET);
        mAlgorithmContainer = 0; 
      }
      
      // Copy to data buffer to be written through FATFS
      //CopyToFatFsDataBuffer(arrIdx);
      
      /* EQDAQ01, 02 Client Routine ---------------------------------------------*/
      /* E1Flag or E2Flag set when client board successfully connect to server --*/
      /* Refer to wiz820.c line no. 300 for which flag to be set */
      if(E1Flag) {
        char E1_Buf[45];
        sprintf(E1_Buf, "%04d%02d%02d_%02d%02d%02d%02d_%+05d_%+05d_%+05d_%+05d\r\n", 
                mYear, mMonth, mDay, mHour, mMin, mSec, mTMSec,
                x, y, z, mAlgorithmContainer);
        // Only when socket is established, allow send data
        if(getSn_SR(SOCK_TWO) == SOCK_ESTABLISHED) {
          /* send selected data */
          CountSendByte = send(SOCK_TWO, (uint8_t*)E1_Buf, strlen(E1_Buf), (bool)false);
        }
      }
      
      if(E2Flag) {
        char E2_Buf[45];
        sprintf(E2_Buf, "%04d%02d%02d_%02d%02d%02d%02d_%+05d_%+05d_%+05d\r\n", 
                mYear, mMonth, mDay, mHour, mMin, mSec, mTMSec, x, y, z);
        // Only when socket is established, allow send data
        if(getSn_SR(SOCK_ZERO) == SOCK_ESTABLISHED) {
          /* send selected data */
          send(SOCK_ZERO, (uint8_t*)E2_Buf, strlen(E2_Buf), (bool)false);
        }
      }
    }
    
    /* do RTC work on every second */
    if(RTCTIM6Count > 1000) {
      RTCTIM6Count = 0;
      
      if(InitialThirteenSeconds == 12) {
         InitialThirteenSeconds = 0;
         GoATFCFlag = true;
      } else {
        if(!GoATFCFlag) {
           InitialThirteenSeconds++;
        }
      }
      
      /* RTC 1Hz interrupt */
      if(RTCTimeDisplay) { // 1Hz calibrated by RTC
        RTCTimeDisplay = false; 
        
        /* Display current time */
        Time_Display(RTC_GetCounter());
      }
      
      /* RTC Alarm interrupt */
      if(RTCAlarmFlag) {
        RTCAlarmFlag = false;
        
        printf("\r\nRTC Alarm Actviated!");
      } 
    }
    
    /* Save log to file process ------------------------------------------------*/
    /* Save process needs to be run every single cycle due to delay might occur */
    if(GoAppendDataFlag) {  // every 500 sample (equals 5 sec), go save file.
      GoAppendDataFlag = false;
      
      int bytesWritten = 0;
      
      if(EachSecFlag) {
        // it means that DATA1_BUF is full and ready to flush out
        // be sure to empty out DATA1_BUF or will overflow and cause system to halt.
        
        /* Append first data for the duration of 1 second */
        bytesWritten = f_printf(&fsrc, DATA1_BUF);
        printf("\r\n%d of bytesWritten", bytesWritten);
        
        if(FileRecordCompleteFlag) {
          FileRecordCompleteFlag = false;
          printf("\r\nFile Record Complete!");
          /* Close the file */
          f_close(&fsrc);
        }
        
        // Reset DATA1_BUF
        memset(DATA1_BUF, 0, sizeof(DATA1_BUF)); 
      } else {
        /* Append another second of data */
        bytesWritten = f_printf(&fsrc, DATA2_BUF);
        printf("\r\n%d of bytesWritten", bytesWritten);
        
        if(FileRecordCompleteFlag) {
          FileRecordCompleteFlag = false;
          printf("\r\nFile Record Complete!");
          /* Close the file */
          f_close(&fsrc); 
        }
        
        // Reset DATA2_BUF
        memset(DATA2_BUF, 0, sizeof(DATA2_BUF));
      }
    }
    
#endif
    
    if(ParseUSART1) {
      ParseUSART1 = false;
      
      // run some test on SDIO
      //SDIO_TEST();

#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
      
      /* Print WIZ820io configuration */
      printSysCfg();

      printf("\r\n");
      printf("\r\nBKP_DR1 = %d", BKP_ReadBackupRegister(BKP_DR1));
      printf("\r\nBKP_DR2 = %d", BKP_ReadBackupRegister(BKP_DR2));
      printf("\r\nBKP_DR3 = %d", BKP_ReadBackupRegister(BKP_DR3));
      printf("\r\nBKP_DR4 = %d", BKP_ReadBackupRegister(BKP_DR4));
      printf("\r\nBKP_DR5 = %d", BKP_ReadBackupRegister(BKP_DR5));
      printf("\r\nBKP_DR6 = %d", BKP_ReadBackupRegister(BKP_DR6));
      printf("\r\nBKP_DR7 = %d", BKP_ReadBackupRegister(BKP_DR7));
      printf("\r\nBKP_DR8 = %d", BKP_ReadBackupRegister(BKP_DR8));
      printf("\r\nBKP_DR9 = %d", BKP_ReadBackupRegister(BKP_DR9));
      printf("\r\nBKP_DR10 = %d", BKP_ReadBackupRegister(BKP_DR10));
      printf("\r\nBKP_DR11 = %d", BKP_ReadBackupRegister(BKP_DR11));
      printf("\r\nBKP_DR12 = %d", BKP_ReadBackupRegister(BKP_DR12));
      printf("\r\nBKP_DR13 = %d", BKP_ReadBackupRegister(BKP_DR13));
      printf("\r\nBKP_DR14 = %d", BKP_ReadBackupRegister(BKP_DR14));
      printf("\r\nBKP_DR15 = %d", BKP_ReadBackupRegister(BKP_DR15));
      printf("\r\nBKP_DR16 = %d", BKP_ReadBackupRegister(BKP_DR16));
      
#elif (defined) USE_EQDAS_SERVER
      
      char buffer[37];
      sprintf(buffer, "%s_%s_%s_%s_%s\r\n",
                DAQBoardOne[arrIdx].Date,
                DAQBoardOne[arrIdx].Time,
                DAQBoardOne[arrIdx].AxisX,
                DAQBoardOne[arrIdx].AxisY,
                DAQBoardOne[arrIdx].AxisZ);
      printf("\r\nRX_BUF : %s, strlen(RX_BUF) : %d", (char*)RX_BUF, strlen((char*)RX_BUF));
      printf("\r\nstrlen(buffer) = %d\n%s", strlen(buffer), buffer);
      
      /*
      char *original = "-3843,+4095,+2069";
      char target[20];
      strncpy(target, original, strlen(original));
      
      char *one, *two, *three;
      char *AfterToken;
      AfterToken = strtok(target, ",");
      one = AfterToken;
      AfterToken = strtok(NULL, ",");
      two = AfterToken;
      AfterToken = strtok(NULL, ",");
      three = AfterToken;
      AfterToken = strtok(NULL, ",");
      if(AfterToken != NULL) printf("AfterToken is not empty");
      
      printf("\r\none : %s, two : %s, three : %s", one, two, three);*/
      
#endif
    
    }
    
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
    
    /*
    for(i=0; i<100; i++) {
      if(flag_uart) {
      // Make a copy from raw collected data to temporary array
      CopyToTmpArray(i);
        
      // Copy to Temporary GAL array
      CopyToTmpGalArray(i);
      
      // Calculate GAL and copy to single temporary GAL value
      CalculateGalAndCopyToGal(i);
      
      // Determine KMA scale
      DetermineKMA(i);

      // Check sign bit and apply to int container
      CheckSignAndToInt(i); // this function also cuts surplus 1G 
      }
    }
    */
    
// following routine is only necessary when the board works as server
#elif defined USE_EQDAS_SERVER
    
    /* EQ-DAQ-01 Parsing routine ------------------------------------------------- */
    /* Set E1Flag indicate that we have valid connection from EQ-DAQ-01(port 5050) */
    if(E1Flag) {
      E1Flag = false; // clear flag since this routine excutes ceaselessly over time
      
      ProcessTextStream(EQ_ONE, (char*)RX_BUF, E1Order);
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag) {        
        // Send directly to PC
        SendToPC(E1Order);
      }
      
      if(E1Order < 99) E1Order++;
      else E1Order = 0;
    }
    
    /* EQ-DAQ-02 Parsing routine ------------------------------------------------- */
    /* Set E2Flag indicate that we have valid connection from EQ-DAQ-02(port 6060) */
    if(E2Flag) {
      E2Flag = false;
      
      ProcessTextStream(EQ_TWO, (char*)RX_BUF, E2Order);
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag) {        
        // Send directly to PC
        SendToPC(E2Order);
      }
      
      if(E2Order < 99) E2Order++;
      else E2Order = 0;
    }

#endif

/* Setup TCP Client or Server -----------------------------------------------------*/
/* Please open config.h file to choose a proper board you wish to use */    
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)    

      /* Start TCP Client process */
      ProcessTcpClient(SOCK_ZERO);  // TCP Client
    
      /* Parameter setting Server side with port 5050 in default */
      ATFCTcpServer(SOCK_TWO, EQDAS_Conf_PORT);  // SOCK_TWO because of flag conformity
    
#elif defined USE_EQDAS_SERVER
    
      /* Process server socket with each port */
      ProcessTcpServer(SOCK_ZERO, 5050);  // designated as for EQM-DAQ-01 with port 5050
      ProcessTcpServer(SOCK_ONE, 6060);   // designated as for EQM-DAQ-02 with port 6060
      ProcessTcpServer(SOCK_TWO, 7070);   // designated as for PC-CLIENT  with port 7070
      ProcessTcpServer(SOCK_THREE, 8080); // designated as for PC_DUMP    with port 8080
      
      /*
      ProcessTcpServer(SOCK_FOUR, 9090);   // designated as for TOBEUSED with port 9090
      ProcessTcpServer(SOCK_FIVE, 10010);   // designated as for TOBEUSED with port 10010
      ProcessTcpServer(SOCK_SIX, 10020);    // designated as for TOBEUSED with port 10020
      ProcessTcpServer(SOCK_SEVEN, 10030);  // designated as for TOBEUSED with port 10030
      */
      
#endif
      
  }
}
Exemplo n.º 20
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void) {
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */
  
  /* System Clocks Configuration */
  RCC_Configuration();
  
  /* System Tick Configuration at 1us */
  SysTick_Config(SystemCoreClock / 1000000);
  
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
  
  /* TIM2 Configuration */
  TIM2_Configuration();
  
  /* TIM3 Configuration (10ms for Network Transmission)*/
  TIM3_Configuration();
  
  /* TIM5 Configuration (GLCD Time Share)*/
  TIM5_Configuration();
  
  /* TIM6 Configuration (RTC load) */
  TIM6_Configuration();
  
#elif defined USE_EQDAS_SERVER
  
  /* TIM4 Configuration */
  TIM4_Configuration();
  
#endif
  
  /* CLCD Configuration */
  CLCD_Configuration();
  
  /* GLCD Configuration */
  GLCD_Configuration();
  
  /* UART1 Configuration */
  UART_Configuration();
  
  /* GPS-UART3 Configuration */
  //GPS_Configuration();
  
  /* RTC configuration by setting the time by Serial USART1 */
  RTC_SetTimeBySerial();
  
  /* Forcefully let user set the IP through terminal */
  //ForceIPSetBySerial();

  /* WIZ820io SPI1 configuration */
  WIZ820io_SPI1_Configuration();
  
  /* W5200 Configuration */
  Set_network();
  
  /* Print WIZ820io configuration */
  printSysCfg();
  
  /* EXTI Configuration */
  EXTI_Configuration();
  
  /* FatFS configuration */
  f_mount(0, &fs);  // mSD
  //f_mount(1, &fs);  // NAND
  
  /* Display Total size of SD card in MB scale */
  SD_TotalSize();
  
  /* Scan all files in mSD card */
  scan_files(path);
  
  /* MAL configuration */
  //Set_System();
  
  /* UMS configuration */
  //Set_USBClock();
  //USB_Interrupts_Config();
  //USB_Init();
  
  /* loop upon completion of USB Enumeration */
  //while (bDeviceState != CONFIGURED);
  
  /* ATFC Algorithm GPIO */
  ATFC_GPIO_Configuration();
  
  /* ATFC Parameter Initialization */
  ATFCAlgorithmParameterSetup();
  
  // For TCP client's connection request delay
  presentTime = my_time;
  
  /* Clear CLCD before branch into main */
  CLCD_Clear();

  /* Create directory and sub directory in accordance with current date */
  filePath = CreateDirectoryAccordingly(GetYearAndMergeToInt(), GetMonthAndMergeToInt(), 
                                        GetDayAndMergeToInt(), RTC_GetCounter() / 3600);
  
  /* Create file in append mode in accordance with current minute */
  CreateFileAppendModeAccordingly(filePath, (RTC_GetCounter() % 3600) / 60);
  
  // When everything is set, print message
  printf("\r\n\n - System is ready - ");
  
  while (1) {
    
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
    
    if(TimerCount > 1000) { // 0 ~ 999 (1000) = 1 sec
      TimerCount = 0;
      
      /*
      int x, y, z;
      x = mAxisBuf.tmp_data_x_lcd[index];
      y = mAxisBuf.tmp_data_y_lcd[index];
      z = mAxisBuf.tmp_data_z_lcd[index];
    
      char Serial_Buf[37];
      int hour, minute, second, tmsecond;
      hour = THH; minute = TMM; second = TSS; tmsecond = 0;
      sprintf(Serial_Buf, "%04d%02d%02d_%02d%02d%02d%02d_%+05d_%+05d_%+05d\r\n", 
                year, month, day, hour, minute, second, tmsecond, x, y, z);
      printf(Serial_Buf);
      */
      
      //my_time++;  // uncomment when tcp connection is needed
      
      /* Process Parameter Text Stream */
      /*
      if(PCFlag) {  // EQDAS Client System and ATFC Algorithm Setting
        PCFlag = false;
        
        ProcessParameterStream();
      }
      */
    }
    
    /* GLCD Time Share */
    if(TIM5GLCDCount > 95) {  // Allocate proper time to share mcu resource with network
      TIM5GLCDCount = 0;
      
      /* Graphic LCD Copy and Process Routine -------------------------------------- */
      if(SyncFlag) { // prevent unpleasant impuse
        // Index synchronization dedicate to GLCD
        arrGLCDIdx = index;
        
        // Make a copy from raw collected data to temporary array
        CopyToTmpArray(arrGLCDIdx);
          
        // Copy to Temporary GAL array
        //CopyToTmpGalArray(arrIdx);
        
        // Calculate GAL and copy to single temporary GAL value
        //CalculateGalAndCopyToGal(arrIdx);
        
        // Determine KMA scale
        KMAGrade = DetermineKMA(arrGLCDIdx);
    
        // Check sign bit and apply to int container
        CheckSignAndToInt(arrGLCDIdx); // this function also cuts surplus 1G
      }
      
      int mATFCBit_lcd;
      mATFCBit_lcd = mAxisBuf.ATFCBit_lcd[arrGLCDIdx];
      
      /* Switch menu & waveform display through graphic lcd */
      GLCD_AxisViewWithWaveform(mode, arrGLCDIdx);
      
      /* Display KMA Intensity on Graphic LCD */
      GLCD_DisplayKMAIntensity(KMAGrade, mATFCBit_lcd);
    }
    
    /* Clock generated by TIM3 */
    if(ClientTimerCounter > 10) {  // 0 ~ 999 (1000) = 1 sec
      ClientTimerCounter = 0;
      
      year = GetYearAndMergeToInt();
      month = GetMonthAndMergeToInt();
      day = GetDayAndMergeToInt();
      hour = THH; minute = TMM; second = TSS; tmsecond = 0;
      
      int mYear, mMonth, mDay, mHour, mMin, mSec, mTMSec;
      mYear = year; mMonth = month; mDay = day;
      mHour = hour; mMin = minute; mSec = second; mTMSec = tmsecond;

      if(SyncFlag) {
        // Index synchronization
        arrIdx = index;
      
        // Make a copy from raw collected data to temporary net array
        CopyToNetArray(arrIdx);
        
        // Check sign bit and apply to int container
        CheckSignAndToIntForNet(arrIdx); // this function also cuts surplus 1G
      }
      
      /* Prevent access to volatile variable warning */
      /* This have to be here in order to correct data to be used in ATFC */
      int mX, mY, mZ, mATFCBit;
      mX = mAxisNetBuf.axis_x_for_net[arrIdx];
      mY = mAxisNetBuf.axis_y_for_net[arrIdx];
      mZ = mAxisNetBuf.axis_z_for_net[arrIdx];
      mATFCBit = mAxisNetBuf.ATFCBit_net[arrIdx];
      
      /* EQDAQ01, 02 Client Routine ---------------------------------------------*/
      /* E1Flag or E2Flag set when client board successfully connect to server --*/
      /* Refer to wiz820.c line no. 406 for which flag to be set */
      if(E1Flag) {
        char E1_Buf[45];
        sprintf(E1_Buf, "%04d%02d%02d_%02d%02d%02d%02d_%+05d_%+05d_%+05d_%d\r\n", 
                mYear, mMonth, mDay, mHour, mMin, mSec, mTMSec,
                mX, mY, mZ, mATFCBit);
        // Only when socket is established, allow send data
        if(getSn_SR(SOCK_ZERO) == SOCK_ESTABLISHED) {
          /* send selected data */
          CountSendByte = send(SOCK_ZERO, (uint8_t*)E1_Buf, strlen(E1_Buf), (bool)false);
        }
      }
      
      if(E2Flag) {
        char E2_Buf[45];
        sprintf(E2_Buf, "%04d%02d%02d_%02d%02d%02d%02d_%+05d_%+05d_%+05d_%d\r\n", 
                mYear, mMonth, mDay, mHour, mMin, mSec, mTMSec,
                mX, mY, mZ, mATFCBit);
        // Only when socket is established, allow send data
        if(getSn_SR(SOCK_ZERO) == SOCK_ESTABLISHED) {
          /* send selected data */
          send(SOCK_ZERO, (uint8_t*)E2_Buf, strlen(E2_Buf), (bool)false);
        }
      }
    }
    
    /* do RTC work on every second */
    if(RTCTIM6Count > 1000) {
      RTCTIM6Count = 0;
      
      if(InitialThirteenSeconds == 12) {
         InitialThirteenSeconds = 0;
         GoATFCFlag = true;
      } else {
        if(!GoATFCFlag) {
           InitialThirteenSeconds++;
        }
      }
      
      /* RTC 1Hz interrupt */
      if(RTCTimeDisplay) { // 1Hz calibrated by RTC
        RTCTimeDisplay = false;
        
        /* Adjust realtime clock deviation */
        if(hour > 23) {
          int i, currentDay, mDay, mHour, mMin, mSec;
          mDay = hour / 24;
          
          for(i=0; i<mDay; i++) {
            IncreaseSingleDay();
            if(i == mDay - 1) {
              currentDay = (GetMonthAndMergeToInt() * 100) + GetDayAndMergeToInt();
              BKP_WriteBackupRegister(BKP_DR3, currentDay); // Save Month and Date
            }
          }
          
          mHour = THH % 24;
          mMin = TMM;
          mSec = TSS;
          
          /* Change the current time */
          RTC_SetCounter(mHour*3600 + mMin*60 + mSec);
        }
        
        /* Display current time */
        Time_Display(RTC_GetCounter());
        
        int OrderCount;
        for(OrderCount = 0; OrderCount < 100; OrderCount++) {
          // Copy to data buffer to be written through FATFS
          CopyToFatFsDataBuffer(OrderCount); 
        }
      }
      
      /* RTC Alarm interrupt */
      if(RTCAlarmFlag) {
        RTCAlarmFlag = false;
        
        printf("\r\nRTC Alarm Actviated!");
      } 
    }
    
#endif
    
    if(ParseGPS) {
      ParseGPS = false;
      
      printf("%s", GPS_Buffer);
    }
    
    if(ParseUSART1) {
      ParseUSART1 = false;
      
      // run some test on SDIO
      //SDIO_TEST();

#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
      
      /* Print WIZ820io configuration */
      printSysCfg();

      printf("\r\n");
      printf("\r\nBKP_DR1 = %d", BKP_ReadBackupRegister(BKP_DR1));
      printf("\r\nBKP_DR2 = %d", BKP_ReadBackupRegister(BKP_DR2));
      printf("\r\nBKP_DR3 = %d", BKP_ReadBackupRegister(BKP_DR3));
      printf("\r\nBKP_DR4 = %d", BKP_ReadBackupRegister(BKP_DR4));
      printf("\r\nBKP_DR5 = %d", BKP_ReadBackupRegister(BKP_DR5));
      printf("\r\nBKP_DR6 = %d", BKP_ReadBackupRegister(BKP_DR6));
      printf("\r\nBKP_DR7 = %d", BKP_ReadBackupRegister(BKP_DR7));
      printf("\r\nBKP_DR8 = %d", BKP_ReadBackupRegister(BKP_DR8));
      printf("\r\nBKP_DR9 = %d", BKP_ReadBackupRegister(BKP_DR9));
      printf("\r\nBKP_DR10 = %d", BKP_ReadBackupRegister(BKP_DR10));
      printf("\r\nBKP_DR11 = %d", BKP_ReadBackupRegister(BKP_DR11));
      printf("\r\nBKP_DR12 = %d", BKP_ReadBackupRegister(BKP_DR12));
      printf("\r\nBKP_DR13 = %d", BKP_ReadBackupRegister(BKP_DR13));
      printf("\r\nBKP_DR14 = %d", BKP_ReadBackupRegister(BKP_DR14));
      printf("\r\nBKP_DR15 = %d", BKP_ReadBackupRegister(BKP_DR15));
      printf("\r\nBKP_DR16 = %d", BKP_ReadBackupRegister(BKP_DR16));
      
      /*
      printf("\r\nstrlen(HEADER) : %d %s", strlen(HEADER), HEADER);
      
      printf("\r\nf_mkdir1 : ");
      char *dirPath = "0:/20130517";
      res = f_mkdir(dirPath);
      FPrintFatResult(res);
      
      printf("\r\nf_mkdir2 : ");
      dirPath = "0:/20130517/22H-23H";
      res = f_mkdir(dirPath);
      FPrintFatResult(res);
      
      char *filePath = "0:/20130517/2-23H/test.txt";
      // Create log file on the drive 0
      res = open_append(&fsrc, filePath);
      FPrintFatResult(res);
      
      if(res == FR_OK) {
        printf("test.txt successfully created\r\n");
        
        // Write buffer to file
        int bytesWritten;
        bytesWritten = f_printf(&fsrc, HEADER);
        printf("\r\n%d of bytesWritten", bytesWritten);
        
        // Close file
        f_close(&fsrc);
        
      } else if ( res == FR_EXIST ) {
        printf("\r\ntest.txt already exist");
      }
      */
      
      
#elif (defined) USE_EQDAS_SERVER
      
      char buffer[37];
      sprintf(buffer, "%s_%s_%s_%s_%s\r\n",
                DAQBoardOne[arrIdx].Date,
                DAQBoardOne[arrIdx].Time,
                DAQBoardOne[arrIdx].AxisX,
                DAQBoardOne[arrIdx].AxisY,
                DAQBoardOne[arrIdx].AxisZ);
      printf("\r\nRX_BUF : %s, strlen(RX_BUF) : %d", (char*)RX_BUF, strlen((char*)RX_BUF));
      printf("\r\nstrlen(buffer) = %d\n%s", strlen(buffer), buffer);
      
      /*
      char *original = "-3843,+4095,+2069";
      char target[20];
      strncpy(target, original, strlen(original));
      
      char *one, *two, *three;
      char *AfterToken;
      AfterToken = strtok(target, ",");
      one = AfterToken;
      AfterToken = strtok(NULL, ",");
      two = AfterToken;
      AfterToken = strtok(NULL, ",");
      three = AfterToken;
      AfterToken = strtok(NULL, ",");
      if(AfterToken != NULL) printf("AfterToken is not empty");
      
      printf("\r\none : %s, two : %s, three : %s", one, two, three);*/
      
#endif
    
    }
    
// following routine is only necessary when the board works as server
#if defined USE_EQDAS_SERVER
    
    /* Server also needs to have get CLCD going while running */
    /* RTC 1Hz interrupt */
    if(RTCTimeDisplay) { // 1Hz calibrated by RTC
      RTCTimeDisplay = false;
      
      /* Adjust realtime clock deviation */
      if(hour > 23) {
        int i, currentDay, mDay, mHour, mMin, mSec;
        mDay = hour / 24;
        
        for(i=0; i<mDay; i++) {
          IncreaseSingleDay();
          if(i == mDay - 1) {
            currentDay = (GetMonthAndMergeToInt() * 100) + GetDayAndMergeToInt();
            BKP_WriteBackupRegister(BKP_DR3, currentDay); // Save Month and Date
          }
        }
        
        mHour = THH % 24;
        mMin = TMM;
        mSec = TSS;
        
        /* Change the current time */
        RTC_SetCounter(mHour*3600 + mMin*60 + mSec);
      }
      
      /* Display current time */
      Time_Display(RTC_GetCounter());
    }
    
    /* EQ-DAQ-01 Parsing routine ------------------------------------------------- */
    /* Set E1Flag indicate that we have valid connection from EQ-DAQ-01(port 5050) */
    if(E1Flag) {
      E1Flag = false; // clear flag since this routine excutes ceaselessly over time
      
      ProcessTextStream(EQ_ONE, (char*)RX_BUF, E1Order);
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag && !E2Flag) { // only when PC is connected and EQ-DAQ-02 is not connected
        // Send directly to PC
        //SendToPC(EQ_ONE, E1Order);
      }
      
      if(E1Order < 99) E1Order++;
      else E1Order = 0;
    } 
    
    /* EQ-DAQ-02 Parsing routine ------------------------------------------------- */
    /* Set E2Flag indicate that we have valid connection from EQ-DAQ-02(port 6060) */
    if(E2Flag) {
      E2Flag = false;
      
      ProcessTextStream(EQ_TWO, (char*)RX_BUF, E2Order);
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag && !E1Flag) { // only when PC is connected and EQ-DAQ-01 is not connected
        // Send directly to PC
        //SendToPC(EQ_TWO, E2Order);
      }
      
      if(E2Order < 99) E2Order++;
      else E2Order = 0;
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag) {
        // Send directly to PC
        MultipleBoardDataToSendToPC(EQ_BOTH, E1Order, E2Order);
      }
    }

#endif

/* Setup TCP Client or Server -----------------------------------------------------*/
/* Please open config.h file to choose a proper board you wish to use -------------*/    
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
      
      /* Start TCP Client process */
      ProcessTcpClient(SOCK_ZERO);  // TCP Client
      
      /* Parameter setting Server side with port 5050 in default */
      ATFCTcpServer(SOCK_TWO, EQDAS_Conf_PORT);  // SOCK_TWO because of flag conformity
      
#elif defined USE_EQDAS_SERVER
      
      /* Process server socket with each port */
      ProcessTcpServer(SOCK_ZERO, 5050);  // designated as for EQM-DAQ-01 with port 5050
      ProcessTcpServer(SOCK_ONE, 6060);   // designated as for EQM-DAQ-02 with port 6060
      ProcessTcpServer(SOCK_TWO, 7070);   // designated as for PC-CLIENT  with port 7070
      ProcessTcpServer(SOCK_THREE, 8080); // designated as for PC_DUMP    with port 8080
      
      /*
      ProcessTcpServer(SOCK_FOUR, 9090);   // designated as for TOBEUSED with port 9090
      ProcessTcpServer(SOCK_FIVE, 10010);   // designated as for TOBEUSED with port 10010
      ProcessTcpServer(SOCK_SIX, 10020);    // designated as for TOBEUSED with port 10020
      ProcessTcpServer(SOCK_SEVEN, 10030);  // designated as for TOBEUSED with port 10030
      */
      
#endif
      
  }
}
Exemplo n.º 21
0
void init(void)
{
	SystemInit();
	//Setup SystickTimer
	if (SysTick_Config(SystemCoreClock / 1000)){ColorfulRingOfDeath();}

	GPIO_Configuration();

#ifdef USE_MICROUSB
	USBD_Init(&USB_OTG_dev,
	            USB_OTG_FS_CORE_ID,
	            &USR_desc,
	            &USBD_CDC_cb,
	            &USR_cb);
#endif

#ifdef USE_SDIO
	UB_Fatfs_Init();
#endif

#ifdef USE_ADC
	ADC_Configuration();
#endif

#ifdef USE_I2C
	I2C_Configuration();
#endif

#ifdef USE_SPI
	SPI_Configuration();
#endif

#ifdef USE_ENCODER
	TIM_encoder_Configuration();
#endif

#ifdef USE_USART1
	USART1_Configuration();
#endif

#ifdef USE_USART2
	USART2_Configuration();
#endif

#ifdef USE_USART3
	USART3_Configuration();
#endif

#ifdef USE_CAN
	CAN_Configuration();
#endif

#ifdef USE_PWM
	TIM_pwm_Configuration();
#endif

#ifdef USE_EXTI
	EXTI_Configuration();
#endif
	NVIC_Configuration();
}
Exemplo n.º 22
0
/**
  * @brief   Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */     

  /* Initialize LEDs and Key Button mounted on STM3210X-EVAL board */       
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_PBInit(BUTTON_KEY, BUTTON_MODE_EXTI);

  /* Enable PWR and BKP clock */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

  /* Configure EXTI Line to generate an interrupt on falling edge */
  EXTI_Configuration();

  /* Configure RTC clock source and prescaler */
  RTC_Configuration();

  /* NVIC configuration */
  NVIC_Configuration();

  /* Configure the SysTick to generate an interrupt each 1 millisecond */
  SysTick_Configuration();

  /* Turn on LED1 */
  STM_EVAL_LEDOn(LED1);
  
  while (1)
  {
    /* Insert 1.5 second delay */
    Delay(1500);

    /* Wait till RTC Second event occurs */
    RTC_ClearFlag(RTC_FLAG_SEC);
    while(RTC_GetFlagStatus(RTC_FLAG_SEC) == RESET);

    /* Alarm in 3 second */
    RTC_SetAlarm(RTC_GetCounter()+ 3);
    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();

    /* Turn off LED1 */
    STM_EVAL_LEDOff(LED1);

    /* Request to enter STOP mode with regulator in low power mode*/
    PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);
    
    /* At this stage the system has resumed from STOP mode -------------------*/
    /* Turn on LED1 */
    STM_EVAL_LEDOn(LED1);

    /* Configures system clock after wake-up from STOP: enable HSE, PLL and select 
       PLL as system clock source (HSE and PLL are disabled in STOP mode) */
    SYSCLKConfig_STOP();
  }
}
Exemplo n.º 23
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void) {
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */
  
  /* System Clocks Configuration */
  RCC_Configuration();
  
  /* System Tick Configuration at 1us */
  SysTick_Config(SystemCoreClock / 1000000);
  
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
  
  /* TIM2 Configuration */
  TIM2_Configuration();
  
  /* TIM3 Configuration */
  TIM3_Configuration();
  
  /* TIM6 Configuration (RTC load) */
  TIM6_Configuration();
  
#elif defined USE_EQDAS_SERVER
  
  /* TIM4 Configuration */
  TIM4_Configuration();
  
#endif
  
  /* UART1 Configuration */
  UART_Configuration();

  /* WIZ820io SPI1 configuration */
  WIZ820io_SPI1_Configuration();
  
  /* W5200 Configuration */
  Set_network();
  
  /* EXTI Configuration */
  EXTI_Configuration();
  
  /* CLCD Configuration */
  CLCD_Configuration();
  
  /* GLCD Configuration */
  GLCD_Configuration();
  
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
  
  /* RTC configuration by setting the time by Serial USART1 */
  RTC_SetTimeBySerial();
  
#endif
  
  /* FatFS configuration */
  f_mount(0, &fs);  // mSD
  //f_mount(1, &fs);  // NAND
  
  /* Display Total size of SD card in MB scale */
  SD_TotalSize();
  
  /* Scan all files in mSD card */
  scan_files(path);
  
  /* MAL configuration */
  //Set_System();
  
  /* UMS configuration */
  //Set_USBClock();
  //USB_Interrupts_Config();
  //USB_Init();
  
  /* loop upon completion of USB Enumeration */
  //while (bDeviceState != CONFIGURED);
  
  // For TCP client's connection request delay
  presentTime = my_time;
  
  /* Clear CLCD before branch into main */
  CLCD_Clear();
  
  /* Alarm in 3 second */
  //RTC_SetAlarm(RTC_GetCounter() + 3);
  /* Wait until last write operation on RTC registers has finished */
  //RTC_WaitForLastTask();
  
  // When everything is set, print message
  printf("\r\n\n - System is ready - ");
  
  while (1) {
    
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
    
    if(TimerCount >= 999) { // 0 ~ 999 (1000) = 1 sec
      TimerCount = 0;
      
      /*
      int x, y, z;
      x = mAxisBuf.tmp_data_x_lcd[index];
      y = mAxisBuf.tmp_data_y_lcd[index];
      z = mAxisBuf.tmp_data_z_lcd[index];
    
      char Serial_Buf[37];
      int hour, minute, second, tmsecond;
      hour = THH; minute = TMM; second = TSS; tmsecond = 0;
      sprintf(Serial_Buf, "%04d%02d%02d_%02d%02d%02d%02d_%+05d_%+05d_%+05d\r\n", 
                year, month, day, hour, minute, second, tmsecond, x, y, z);
      printf(Serial_Buf);
      */
      
      //my_time++;  // uncomment when tcp connection is needed

    }
    
    /* Clock generated by TIM3 */
    if(ClientTimerCounter >= 99) {  // 0 ~ 999 (1000) = 1 sec
      ClientTimerCounter = 0;
      
      arrIdx = index;
      
      year = GetYearAndMergeToInt();
      month = GetMonthAndMergeToInt();
      day = GetDayAndMergeToInt();
      hour = THH; minute = TMM; second = TSS; tmsecond = 0;
      
      /* EQDAQ01, 02 Client Routine ---------------------------------------------*/
      /* E1Flag or E2Flag set when client board successfully connect to server --*/
      /* Refer to wiz820.c line no. 300 for which flag to be set */
      if(E1Flag) {
        int x, y, z;
        x = mAxisBuf.tmp_data_x_lcd[arrIdx];
        y = mAxisBuf.tmp_data_y_lcd[arrIdx];
        z = mAxisBuf.tmp_data_z_lcd[arrIdx];
      
        char E1_Buf[20];        
        sprintf(E1_Buf, "%04d%02d%02d_%02d%02d%02d%02d_%+05d_%+05d_%+05d\r\n", 
                year, month, day, hour, minute, second, tmsecond, x, y, z);
        // Only when socket is established, allow send data
        if(getSn_SR(SOCK_ZERO) == SOCK_ESTABLISHED) {
          /* send selected data */
          CountSendByte = send(SOCK_ZERO, (uint8_t*)E1_Buf, strlen(E1_Buf), (bool)false);
        }
      }
      
      if(E2Flag) {
        int x, y, z;
        x = mAxisBuf.tmp_data_x_lcd[arrIdx];
        y = mAxisBuf.tmp_data_y_lcd[arrIdx];
        z = mAxisBuf.tmp_data_z_lcd[arrIdx];
        
        char E2_Buf[20];
        sprintf(E2_Buf, "%04d%02d%02d_%02d%02d%02d%02d_%+05d_%+05d_%+05d\r\n", 
                year, month, day, hour, minute, second, tmsecond, x, y, z);
        // Only when socket is established, allow send data
        if(getSn_SR(SOCK_ZERO) == SOCK_ESTABLISHED) {
          /* send selected data */
          send(SOCK_ZERO, (uint8_t*)E2_Buf, strlen(E2_Buf), (bool)false);
        }
      }
    }
    
    /* do RTC work on every 0.5 sec */
    if(RTCTIM6Count >= 499) {
      RTCTIM6Count = 0;
      
      /* RTC 1Hz interrupt */
      if(RTCTimeDisplay) { // 1Hz calibrated by RTC
        RTCTimeDisplay = false; 
        
        /* Display current time */
        Time_Display(RTC_GetCounter());
      }
      
      /* RTC Alarm interrupt */
      if(RTCAlarmFlag) {
        RTCAlarmFlag = false;
        
        printf("\r\nRTC Alarm Actviated!");
      } 
    }
    
#endif
    
    if(ParseUSART1) {
      ParseUSART1 = false;
      
      // print system configuration
      //printSysCfg();
      
      // run some test on SDIO
      //SDIO_TEST();

#if (defined USE_EQDAS01) || (defined USE_EQDAS02)

      
      
#elif (defined) USE_EQDAS_SERVER
      
      char buffer[37];
      sprintf(buffer, "%s_%s_%s_%s_%s\r\n",
                DAQBoardOne[arrIdx].Date,
                DAQBoardOne[arrIdx].Time,
                DAQBoardOne[arrIdx].AxisX,
                DAQBoardOne[arrIdx].AxisY,
                DAQBoardOne[arrIdx].AxisZ);
      printf("\r\nRX_BUF : %s, strlen(RX_BUF) : %d", (char*)RX_BUF, strlen((char*)RX_BUF));
      printf("\r\nstrlen(buffer) = %d\n%s", strlen(buffer), buffer);
      
      /*
      char *original = "-3843,+4095,+2069";
      char target[20];
      strncpy(target, original, strlen(original));
      
      char *one, *two, *three;
      char *AfterToken;
      AfterToken = strtok(target, ",");
      one = AfterToken;
      AfterToken = strtok(NULL, ",");
      two = AfterToken;
      AfterToken = strtok(NULL, ",");
      three = AfterToken;
      AfterToken = strtok(NULL, ",");
      if(AfterToken != NULL) printf("AfterToken is not empty");
      
      printf("\r\none : %s, two : %s, three : %s", one, two, three);*/
      
#endif
    
    }
    
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)
    
    for(i=0; i<100; i++) {
      // Make a copy from raw collected data to temporary array
      CopyToTmpArray(i);
        
      // Copy to Temporary GAL array
      CopyToTmpGalArray(i);
      
      // Calculate GAL and copy to single temporary GAL value
      CalculateGalAndCopyToGal(i);
      
      // Determine KMA scale
      DetermineKMA(i);
      
      // Check sign bit and apply to int container
      CheckSignAndToInt(i); // this function also cuts surplus 1G
      
      // Copy to data buffer to be written through FATFS
      //CopyToFatFsDataBuffer(arrIdx);
    }
    
    /* Save log to file process */
    if(GoAppendDataFlag) {  // every 500 sample (equals 5 sec), go save file.
      GoAppendDataFlag = false;
      
      int bytesWritten = 0;
      
      /* Open or create a log file and ready to append */
      //char *filePath = "/20130517/22H-23H/test.txt";
      //res = open_append(&fsrc, filePath);
      //FPrintFatResult(res);
      
      if(FiveSecFlag) {
        // it means that DATA1_BUF is full and ready to flush out
        // be sure to empty out DATA1_BUF or will overflow and cause system to halt.
        
        /* Append 5 second of data */
        bytesWritten = f_printf(&fsrc, DATA1_BUF);
    
        /* Close the file */
        f_close(&fsrc);
        
        printf("\r\n%d of bytesWritten", bytesWritten);
        
        // Reset DATA1_BUF
        memset(DATA1_BUF, 0, sizeof(DATA1_BUF));
        
      } else {
        // here means that DATA2_BUF is full and ready to flush out
        // be sure to empty out DATA2_BUF or will overflow and cause system to halt.
        
        /* Append 5 second of data */
        bytesWritten = f_printf(&fsrc, DATA2_BUF);

        /* Close the file */
        f_close(&fsrc);
        
        printf("\r\n%d of bytesWritten", bytesWritten);
        
        // Reset DATA2_BUF
        memset(DATA2_BUF, 0, sizeof(DATA2_BUF));
      }
    }
    
// following routine is only necessary when the board works as server
#elif defined USE_EQDAS_SERVER
    
    /* EQ-DAQ-01 Parsing routine ------------------------------------------------- */
    /* Set E1Flag indicate that we have valid connection from EQ-DAQ-01(port 5050) */
    if(E1Flag) {
      E1Flag = false; // clear flag since this routine excutes ceaselessly over time
      
      ProcessTextStream(EQ_ONE, (char*)RX_BUF, E1Order);
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag) {        
        // Send directly to PC
        SendToPC(E1Order);
      }
      
      if(E1Order < 99) E1Order++;
      else E1Order = 0;
    }
    
    /* EQ-DAQ-02 Parsing routine ------------------------------------------------- */
    /* Set E2Flag indicate that we have valid connection from EQ-DAQ-02(port 6060) */
    if(E2Flag) {
      E2Flag = false;
      
      ProcessTextStream(EQ_TWO, (char*)RX_BUF, E2Order);
      
      /* PC Client Parsing routine ------------------------------------------------- */
      /* Set PCFlag indicate that we have valid connection from PC Client(port 7070) */
      if(PCFlag) {        
        // Send directly to PC
        SendToPC(E2Order);
      }
      
      if(E2Order < 99) E2Order++;
      else E2Order = 0;
    }

#endif

/* Setup TCP Client or Server -----------------------------------------------------*/
/* Please open config.h file to choose a proper board you wish to use */    
#if (defined USE_EQDAS01) || (defined USE_EQDAS02)    

      /* Start TCP Client process */
      ProcessTcpClient(SOCK_ZERO);
    
#elif defined USE_EQDAS_SERVER
    
      /* Process server socket with each port */
      ProcessTcpServer(SOCK_ZERO, 5050);  // designated as for EQM-DAQ-01 with port 5050
      ProcessTcpServer(SOCK_ONE, 6060);   // designated as for EQM-DAQ-02 with port 6060
      ProcessTcpServer(SOCK_TWO, 7070);   // designated as for PC-CLIENT  with port 7070
      ProcessTcpServer(SOCK_THREE, 8080); // designated as for PC_DUMP    with port 8080
      
      /*
      ProcessTcpServer(SOCK_FOUR, 9090);   // designated as for TOBEUSED with port 9090
      ProcessTcpServer(SOCK_FIVE, 10010);   // designated as for TOBEUSED with port 10010
      ProcessTcpServer(SOCK_SIX, 10020);    // designated as for TOBEUSED with port 10020
      ProcessTcpServer(SOCK_SEVEN, 10030);  // designated as for TOBEUSED with port 10030
      */
      
#endif
      
  }
}
void factory_test_1st (void)
{
	int i;
	//uint16 adc_val = 0;
	int fail_count;

	// check A0~A3
	if (teststep == 0)
	{
		fail_count = 0;
#if 0
		for(i = 0; i < 4; i++)
		{
			adc_val = ADC_DualConvertedValueTab[i];
			if (adc_val > 100) //TODO
			{
				delay_ms(1);
		    	//printf("########## A%d[%d] OK.\r\n", i, adc_val);
			}
			else
			{
				fail_count += 1;
		    	printf("########## A%d[%d] Fail.\r\n", i, adc_val);
			}
		}
#endif
		if(fail_count == 0)
		{
			printf("########## A0 = %d || A1 = %d || A2 = %d || A3 = %d\r\n", ADC_DualConvertedValueTab[0]
			                                                                , ADC_DualConvertedValueTab[1]
			                                                                , ADC_DualConvertedValueTab[2]
			                                                                , ADC_DualConvertedValueTab[3]);
		}

		teststep = 1;
	}

	// check RS422
	if (teststep == 1)
	{
		printf("########## RS422 TX:TEST\r\n");
		UART2_flush();
		UART_write(FACTORY_TEST_STR, sizeof(FACTORY_TEST_STR));
		UART_write("\r", 1);
		teststep = 2;
	}

	// check SW1~SW3
	if (teststep == 2)
	{
		Delay(10000000);
		EXTI_Configuration();
		USART1_flush();
		teststep = 3;
	}

#if 0
		// check VCC, Temperature
		if (teststep == 5)
		{
			adc_val = ADC_DualConvertedValueTab[0];

			if (adc_val > 4000)
			{
				printf("########## VCC[%d] OK.\r\n", adc_val);

				adc_val = ADC_DualConvertedValueTab[1];
				if (adc_val > 100) //TODO
					printf("########## Temperature[%d] OK.\r\n", adc_val);
				else
					printf("########## Temperature[%d] Fail.\r\n", adc_val);
	    		teststep = 6;
			}
		}
#endif

	//check_factory_uart1();
}
Exemplo n.º 25
0
    int main()
  {
    
    
    RCC_Config();  // to read and write to AFIO_remap AFIO_clock must first be eanble
    NVIC_Config();
    TIM_Config(); 
    GPIO_Config();
    EXTI_Configuration();
    initUsart();
    //initBT();
    
              // Only for debug the clock tree  *********************************************** 
          // Put the clock configuration into RCC_APB2PeriphClockCmd 
          RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); 
          /* Output clock on MCO pin ---------------------------------------------*/ 
          GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; 
          GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; 
          GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; 
          GPIO_Init(GPIOA, &GPIO_InitStructure); 
          //  RCC_MCOConfig(RCC_MCO_HSE); // Put on MCO pin the: freq. of external crystal 
          RCC_MCOConfig(RCC_MCO_SYSCLK);  // Put on MCO pin the: System clock selected  
          // 
    //RTCInit();
    
    RCC_GetClocksFreq(&RCC_Clocks);   
    
    writeStringUSART2("\033[2J"); //clear usart 2 screen
    writeStringUSART1("\033[2J");  //clear usart 1 screen
    writeStringUSART1("     <<<<- Welcome To Hinkens Cobra Bluetooth ->>>>\n\n\r");


    
    

    while(1)
    {

        if(GPIO_ReadInputDataBit(GPIOB, COBRA_BOARDSWITCH)== false) writeStringUSART1("On Hook\n\r");
        else            //Luren är lyft
        {
            writeStringUSART1("Phone is off hook!\n\r Dial: \n\r");
            acceptCall(); //accept incoming call
            Delay(Delay_10ms);
            //for(counter = 0 ; counter < 10 ; counter++)
            while(TIM_GetITStatus(TIM2, TIM_IT_Update) == RESET) //
            {
                
                dialed_number = 0;
                while(GPIO_ReadInputDataBit(GPIOB, COBRA_DIALING)== true && GPIO_ReadInputDataBit(GPIOB, COBRA_BOARDSWITCH)== true)//Wait for user to start dialing
                {
                  //writeStringUSART1("Timer Counter: %d\r\n",TIM_GetCounter(TIM2));
                  if(state == 1 && dialingFlag == true) //check if timer has run out and user has started a call
                  {
                    writeStringUSART1("time is up dialing number: ");
                    for (int x = 0; x < counter; x++)
                    {
                      //printf("%d", number[x] );
                    }
                    sendPhoneNumber(number, counter);
                    writeStringUSART1("\r\n");
                    dialingFlag = false;
                    state =  0;
                    counter = 0;
                  }
                    
                }
                Delay(Delay_100ms); //Wait for switch to debounce
          
                while(GPIO_ReadInputDataBit(GPIOB, COBRA_DIALING) == false)
                {    
                     dialingFlag = true;
                     state = 0;
                     TIM_SetCounter(TIM2, 0);
                     TIM_Cmd(TIM2, ENABLE); //Start timer
                     
                     //RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
                     Delay(Delay_10ms);
                     Delay(Delay_10ms);
                      //Now count how many times the mechnical switch toggles
                     if(GPIO_ReadInputDataBit(GPIOB, COBRA_PULSE)== false && pulseFlag == 1)
                     {
                       pulseFlag = 0;
                       dialed_number ++;
                     }
                     else if(GPIO_ReadInputDataBit(GPIOB, COBRA_PULSE) == true && pulseFlag == 0)
                     {
                       pulseFlag = 1;
                        //Do notthing just idle..
                     }
                     
                  Delay(Delay_10ms);   

                }
                Delay(Delay_100ms);
                if(dialed_number != 0) // to handle the error of a extra loop after dialed number
                {
                  dialed_number--; //Rotary always has one extra closure that must be taken off
                  number[counter] = dialed_number;
                  counter ++;
                }

                if(GPIO_ReadInputDataBit(GPIOB, COBRA_BOARDSWITCH)== false) //Hunng upp
                {
                  hangUp(); //hang-up command to bluettooh
                  writeStringUSART1("Hung up!\n\r");
                  counter = 0;
                  break;
                }

              
                //printf("%d\n\r", dialed_number);
                    
            }//end for loop
        }
        
        Delay(Delay_100ms);
    
    }//end while(1)

  }//end main()
Exemplo n.º 26
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main()
{
    //uint8_t tx_size[8] = { 2, 2, 2, 2, 2, 2, 2, 2 };
    //uint8_t rx_size[8] = { 2, 2, 2, 2, 2, 2, 2, 2 };
    //uint8_t mac_addr[6] = {0x00, 0x08, 0xDC, 0x11, 0x22, 0x33};
    //uint8_t src_addr[4] = {192, 168,  0,  80};
    //uint8_t gw_addr[4]  = {192, 168,  0,  1};
    //uint8_t sub_addr[4] = {255, 255, 255,  0};
    //uint8_t dns_server[4] = {8, 8, 8, 8};           // for Example domain name server
    //uint8_t tmp[8];
	//int ret;
	int i;
#if defined (_MAIN_DEBUG_) && defined (_USE_SDCARD_)
	int ret;
#endif
#if defined(F_APP_FTP)
	wiz_NetInfo gWIZNETINFO;
#endif
#if defined(F_APP_DHCP) || defined(F_APP_DNS)
	S2E_Packet *value = get_S2E_Packet_pointer();
#endif
#if defined(F_APP_DNS)
	uint8_t dns_server_ip[4];
#endif

    /* External Clock */
    CRG_PLL_InputFrequencySelect(CRG_OCLK);

    /* Set System init */
    SystemInit();

    /* UART Init */
    UART_StructInit(&UART_InitStructure);
    UART_Init(UART_DEBUG,&UART_InitStructure);

    /* SysTick_Config */
    SysTick_Config((GetSystemClock()/1000));

    /* Set WZ_100US Register */
    setTIC100US((GetSystemClock()/10000));
    //getTIC100US();	
    //printf(" GetSystemClock: %X, getTIC100US: %X, (%X) \r\n", 
    //      GetSystemClock, getTIC100US(), *(uint32_t *)TIC100US);        

	LED_Init(LED1);
	LED_Init(LED2);
	LED_Init(LED3);

	LED_Off(LED1);
	LED_Off(LED2);
	LED_Off(LED3);

	g_sdcard_done = 0;

	BOOT_Pin_Init();
	Board_factory_Init();
	EXTI_Configuration();

	/* Load Configure Information */
	load_S2E_Packet_from_storage();
	UART_Configuration();

	/* Check MAC Address */
	check_mac_address();

	Timer0_Configuration();

    // ADC initialize
    ADC_Init();

#ifdef _MAIN_DEBUG_
	uint8_t tmpstr[6] = {0,};

	ctlwizchip(CW_GET_ID,(void*)tmpstr);
    printf("\r\n============================================\r\n");
	printf(" WIZnet %s EVB Demo v%d.%.2d\r\n", tmpstr, VER_H, VER_L);
	printf("============================================\r\n");
	printf(" WIZwiki Platform based WEBBoot Example\r\n");
	printf("============================================\r\n");
#endif

#ifdef __DEF_USED_IC101AG__ //For using IC+101AG
    *(volatile uint32_t *)(0x41003068) = 0x64; //TXD0 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x4100306C) = 0x64; //TXD1 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003070) = 0x64; //TXD2 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003074) = 0x64; //TXD3 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003050) = 0x64; //TXE  - set PAD strengh and pull-up
#endif

#ifdef __DEF_USED_MDIO__ 
    /* mdio Init */
    mdio_init(GPIOB, MDC, MDIO );
    /* PHY Link Check via gpio mdio */
    while( link() == 0x0 )
    {
        printf(".");  
        delay(500);
    }
    printf("PHY is linked. \r\n");  
#else
    delay(1000);
    delay(1000);
#endif

	Mac_Conf();
#if defined(F_APP_DHCP)
	if(value->options.dhcp_use)		// DHCP
	{
		uint32_t ret;
		uint8_t dhcp_retry = 0;

#ifdef _MAIN_DEBUG_
		printf(" - DHCP Client running\r\n");
#endif

		DHCP_init(SOCK_DHCP, TX_BUF);
		reg_dhcp_cbfunc(w5500_dhcp_assign, w5500_dhcp_assign, w5500_dhcp_conflict);

		while(1)
		{
			ret = DHCP_run();

			if(ret == DHCP_IP_LEASED)
			{
#ifdef _MAIN_DEBUG_
				printf(" - DHCP Success: DHCP Leased time : %ld Sec.\r\n\r\n", getDHCPLeasetime());
#endif
				break;
			}
			else if(ret == DHCP_FAILED)
			{
				dhcp_retry++;
#ifdef _MAIN_DEBUG_
				if(dhcp_retry <= 3) printf(" - DHCP Timeout occurred and retry [%d]\r\n", dhcp_retry);
#endif
			}

			if(dhcp_retry > 3)
			{
#ifdef _MAIN_DEBUG_
				printf(" - DHCP Failed\r\n\r\n");
#endif
				value->options.dhcp_use = 0;
				Net_Conf();
				break;
			}

			do_udp_config(SOCK_CONFIG);
		}
	}
	else 								// Static
	{
		Net_Conf();
	}
#else
	Net_Conf();
#endif

#ifdef _MAIN_DEBUG_
	display_Net_Info();
#endif

#if defined(F_APP_ATC)
	atc_init(&rxring, &txring);

	op_mode = OP_DATA;
#endif

	TFTP_init(SOCK_TFTP, socket_buf);

	ret = application_update();

    printf("[DEBUG] check trigger:%d ret:%d \r\n", get_bootpin_Status(), ret);
	if((get_bootpin_Status() == 1) && (ret != TFTP_FAIL)) {
		uint32_t tmp;

#if !defined(MULTIFLASH_ENABLE)
		tmp = *(volatile uint32_t *)APP_BASE;
#else
		tmp = *(volatile uint32_t *)flash.flash_app_base;
#endif

		if((tmp & 0xffffffff) != 0xffffffff) {
		    printf("[DEBUG] application_jump\r\n");
			application_jump();
		}
	}

#ifdef _USE_SDCARD_
	// SD card Initialization
	ret = mmc_mount();
	if(ret <= 0)
	{
#ifdef _MAIN_DEBUG_
		printf("\r\n - Can't mount SD card: Please Reboot WIZ750WEB Board or Insert SD card\r\n");
#endif
		//while(!(ret = mmc_mount()));
	}

	if(ret > 0)
	{
#ifdef _MAIN_DEBUG_
		display_SDcard_Info(ret);
#endif
	}
#endif

	httpServer_init(TX_BUF, RX_BUF, MAX_HTTPSOCK, socknumlist);
#ifdef _USE_WATCHDOG_
	reg_httpServer_cbfunc(NVIC_SystemReset, IWDG_ReloadCounter); // Callback: STM32 MCU Reset / WDT Reset (IWDG)
#else
	reg_httpServer_cbfunc(NVIC_SystemReset, NULL); // Callback: STM32 MCU Reset
#endif
	IO_status_init();

#if defined(F_APP_FTP)
	ctlnetwork(CN_GET_NETINFO, (void*) &gWIZNETINFO);
	ftpd_init(gWIZNETINFO.ip);	// Added by James for FTP
#endif

#ifdef _USE_WATCHDOG_
	// IWDG Initialization: STM32 Independent WatchDog
	IWDG_Configureation();
#endif

	while (1) {
#ifdef _USE_WATCHDOG_
		IWDG_ReloadCounter(); // Feed IWDG
#endif

#if defined(F_APP_ATC)
		atc_run();
#endif
		
		if(g_op_mode == NORMAL_MODE) {
			do_udp_config(SOCK_CONFIG);
		} else {
			if(TFTP_run() != TFTP_PROGRESS)
				g_op_mode = NORMAL_MODE;
		}

#if defined(F_APP_DHCP)
		if(value->options.dhcp_use)
			DHCP_run();
#endif

		for(i = 0; i < MAX_HTTPSOCK; i++)	httpServer_run(i);	// HTTP server handler

#if defined(F_APP_FTP)
		ftpd_run(FTP_DBUF);
#endif

#ifdef _USE_WATCHDOG_
		IWDG_ReloadCounter(); // Feed IWDG
#endif

	}

    return 0;
}
Exemplo n.º 27
0
/**
\brief The program starts executing here.
*/
int mote_main(void) {
   uint8_t i;
   
   // clear local variables
   memset(&app_vars,0,sizeof(app_vars_t));
   
   // initialize board
   board_init();
   GPIO_Configuration();
   EXTI_Configuration();
   
   GPIOD->BRR = (uint32_t)GPIO_Pin_2;
   
#ifdef RADIO_SLEEP
   PORT_PIN_RADIO_SLP_TR_CNTL_HIGH();
#ifdef RADIO_SLEEP_IN_RUN_MOdE
   while(1);
#endif
   board_sleep();
#endif
   
#ifdef RADIO_TRXOFF
   board_sleep();
#endif
 
   // add callback functions radio
   radio_setOverflowCb(cb_radioTimerOverflows);
   radio_setCompareCb(cb_radioTimerCompare);
   radio_setStartFrameCb(cb_startFrame);
   radio_setEndFrameCb(cb_endFrame);
   
   // prepare packet
   app_vars.packet_len = sizeof(app_vars.packet);
   for (i=0;i<app_vars.packet_len;i++) {
      app_vars.packet[i] = ID;
   }

   // start bsp timer
   bsp_timer_set_callback(cb_timer);
   bsp_timer_scheduleIn(TIMER_PERIOD);
   
   // prepare radio
   radio_rfOn();
   radio_setFrequency(CHANNEL);
   
   // switch in RX by default
   radio_rxEnable();
   app_vars.state = APP_STATE_RX;
   
#ifdef RADIO_RX_ON
   leds_all_off();
   board_sleep();
#endif
   
   // start by a transmit
   app_vars.flags |= APP_FLAG_TIMER;

   while (1) {
      // sleep while waiting for at least one of the flags to be set
      while (app_vars.flags==0x00) {
         board_sleep();
      }
      // handle and clear every flag
      while (app_vars.flags) {

    	  if (app_vars.flags & APP_FLAG_START_FRAME) {
            // start of frame
            
            switch (app_vars.state) {
               case APP_STATE_RX:
                  // started receiving a packet
                  leds_error_on();
                  break;
               case APP_STATE_TX:
                  // started sending a packet
                  leds_sync_on();
                  break;
            }
            // clear flag
            app_vars.flags &= ~APP_FLAG_START_FRAME;
         }
         
         if (app_vars.flags & APP_FLAG_END_FRAME) {
            // end of frame
            
            switch (app_vars.state) {
               case APP_STATE_RX:
                  // done receiving a packet
            	   app_vars.packet_len = sizeof(app_vars.packet);
            	     for (i=0;i<app_vars.packet_len;i++) {
            	        app_vars.packet[i] = 0;
            	     }
                  // get packet from radio
                  radio_getReceivedFrame(app_vars.packet,
                                         &app_vars.packet_len,
                                         sizeof(app_vars.packet),
                                         &app_vars.rxpk_rssi,
                                         &app_vars.rxpk_lqi,
                                         &app_vars.rxpk_crc);
                  
                  leds_error_off();
                  break;
               case APP_STATE_TX:
                  // done sending a packet
                  
                  // switch to RX mode
                  radio_rxEnable();
                  app_vars.state = APP_STATE_RX;
                  
                  leds_sync_off();
                  break;
            }
            // clear flag
            app_vars.flags &= ~APP_FLAG_END_FRAME;
         }
         
         if (app_vars.flags & APP_FLAG_TIMER) {
            // timer fired
            
            if (app_vars.state==APP_STATE_RX) {
               // stop listening
               radio_rfOff();
               
               // prepare packet
               app_vars.packet_len = sizeof(app_vars.packet);
               for (i=0;i<app_vars.packet_len;i++) {
                  app_vars.packet[i] = ID;
               }
               
               // start transmitting packet
               radio_loadPacket(app_vars.packet,app_vars.packet_len);
               radio_txEnable();
               
#ifdef RADIO_PLL_ON
               leds_all_off();
               board_sleep();
#endif
               
               radio_txNow();
#ifdef RADIO_BUSY_TX
               leds_all_off();
               while(1) { //keep sending
                    PORT_PIN_RADIO_SLP_TR_CNTL_HIGH();
                    PORT_PIN_RADIO_SLP_TR_CNTL_LOW();
               }
               board_sleep();
#endif
               
               app_vars.state = APP_STATE_TX;
            }
            
            // clear flag
            app_vars.flags &= ~APP_FLAG_TIMER;
         }
      }
   }
}
Exemplo n.º 28
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured,
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */

  /* System clocks configuration ---------------------------------------------*/
  RCC_Configuration();

  /* NVIC configuration ------------------------------------------------------*/
  NVIC_Configuration();

  /* GPIO configuration ------------------------------------------------------*/
  GPIO_Configuration();

  /* EXTI configuration ------------------------------------------------------*/
  EXTI_Configuration();

  /* DMA1 channel1 configuration ----------------------------------------------*/
  DMA_DeInit(DMA1_Channel1);
  DMA_InitStructure.DMA_PeripheralBaseAddr = ADC1_DR_Address;
  DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)ADC_RegularConvertedValueTab;
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
  DMA_InitStructure.DMA_BufferSize = 64;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
  DMA_Init(DMA1_Channel1, &DMA_InitStructure);

  /* Enable DMA1 channel1 */
  DMA_Cmd(DMA1_Channel1, ENABLE);

  /* ADC1 configuration ------------------------------------------------------*/
  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
  ADC_InitStructure.ADC_ScanConvMode = ENABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_Ext_IT11_TIM8_TRGO;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_NbrOfChannel = 2;
  ADC_Init(ADC1, &ADC_InitStructure);

  /* ADC1 regular channels configuration */
  ADC_RegularChannelConfig(ADC1, ADC_Channel_4, 1, ADC_SampleTime_28Cycles5);
  ADC_RegularChannelConfig(ADC1, ADC_Channel_14, 2, ADC_SampleTime_28Cycles5);

  /* Regular discontinuous mode channel number configuration */
  ADC_DiscModeChannelCountConfig(ADC1, 1);
  /* Enable regular discontinuous mode */
  ADC_DiscModeCmd(ADC1, ENABLE);

  /* Enable ADC1 external trigger conversion */
  ADC_ExternalTrigConvCmd(ADC1, ENABLE);

  /* Set injected sequencer length */
  ADC_InjectedSequencerLengthConfig(ADC1, 2);
  /* ADC1 injected channel configuration */
  ADC_InjectedChannelConfig(ADC1, ADC_Channel_11, 1, ADC_SampleTime_28Cycles5);
  ADC_InjectedChannelConfig(ADC1, ADC_Channel_12, 2, ADC_SampleTime_28Cycles5);
  /* ADC1 injected external trigger configuration */
  ADC_ExternalTrigInjectedConvConfig(ADC1, ADC_ExternalTrigInjecConv_Ext_IT15_TIM8_CC4);
  /* Enable ADC1 injected external trigger conversion */
  ADC_ExternalTrigInjectedConvCmd(ADC1, ENABLE);

  /* Enable JEOC interrupt */
  ADC_ITConfig(ADC1, ADC_IT_JEOC, ENABLE);

  /* Enable ADC1 DMA */
  ADC_DMACmd(ADC1, ENABLE);

  /* Enable ADC1 */
  ADC_Cmd(ADC1, ENABLE);

  /* Enable ADC1 reset calibration register */
  ADC_ResetCalibration(ADC1);
  /* Check the end of ADC1 reset calibration register */
  while(ADC_GetResetCalibrationStatus(ADC1));

  /* Start ADC1 calibration */
  ADC_StartCalibration(ADC1);
  /* Check the end of ADC1 calibration */
  while(ADC_GetCalibrationStatus(ADC1));

  while (1)
  {
  }
}
Exemplo n.º 29
0
/*******************************************************************************
* Function Name  : Set_System
* Description    : Configures Main system clocks & power.
* Input          : None.
* Return         : None.
*******************************************************************************/
void Set_System(void)
{
  /* SYSCLK, HCLK, PCLK2 and PCLK1 configuration -----------------------------*/   
     
  /* RCC system reset(for debug purpose) */
  RCC_DeInit();

  /* Enable HSE */
  RCC_HSEConfig(RCC_HSE_ON);

  /* Wait till HSE is ready */
  HSEStartUpStatus = RCC_WaitForHSEStartUp();

  if(HSEStartUpStatus == SUCCESS)
  {
    /* Enable Prefetch Buffer */
    FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);

    /* Flash 2 wait state */
    FLASH_SetLatency(FLASH_Latency_2);
 
    /* HCLK = SYSCLK */
    RCC_HCLKConfig(RCC_SYSCLK_Div1); 
  
    /* PCLK2 = HCLK */
    RCC_PCLK2Config(RCC_HCLK_Div1); 

    /* PCLK1 = HCLK/2 */
    RCC_PCLK1Config(RCC_HCLK_Div2);

    /* On STICE the PLL output clock is fixed to 72 MHz */
    RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);

    /* Enable PLL */ 
    RCC_PLLCmd(ENABLE);

    /* Wait till PLL is ready */
    while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET)
    {
    }

    /* Select PLL as system clock source */
    RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);

    /* Wait till PLL is used as system clock source */
    while(RCC_GetSYSCLKSource() != 0x08)
    {
    }
  }

   /* Enable USART1, GPIOA, GPIOD and AFIO clocks RCC_APB2Periph_USART1 |*/
  RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA
                         | RCC_APB2Periph_AFIO | RCC_APB2Periph_USART1, ENABLE);

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
						   
  /* Configure the used GPIOs*/
  GPIO_Configuration();
  
  /* Configure the EXTI lines for Key and Tamper push buttons*/
  EXTI_Configuration();
  
  UART_Configuration();
  SYSTICK_Configuration();
}
Exemplo n.º 30
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
#ifdef DEBUG
  debug();
#endif
  
  /* Configure the system clocks */
  RCC_Configuration();

  /* Configure GPIOs */
  GPIO_Configuration();

  /* Configures the EXTI Lines */
  EXTI_Configuration();
  
#ifdef  VECT_TAB_RAM  
  /* Set the Vector Table base location at 0x20000000 */ 
  NVIC_SetVectorTable(NVIC_VectTab_RAM, 0x0); 
#else  /* VECT_TAB_FLASH  */
  /* Set the Vector Table base location at 0x08000000 */ 
  NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0);   
#endif  

  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

  NVIC_InitStructure.NVIC_IRQChannel = EXTI15_10_IRQChannel;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
  
  NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQChannel;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
  NVIC_Init(&NVIC_InitStructure);
 
  while (1)
  {
    if(LowPowerMode == 1)
    {
      LowPowerMode = 0;

      /* Toggle GPIO_LED pin 6 */
      GPIO_WriteBit(GPIO_LED, GPIO_Pin_6, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIO_LED, GPIO_Pin_6)));
      
      #ifdef  WFISLEEPONEXIT
        NVIC_SystemLPConfig(NVIC_LP_SLEEPONEXIT, ENABLE);
      #endif

      #ifdef  WFISLEEPNOW
        NVIC_SystemLPConfig(NVIC_LP_SLEEPONEXIT, DISABLE);
        __WFI();
      #endif

      #ifdef  WFESEVONPEND
        NVIC_SystemLPConfig(NVIC_LP_SEVONPEND, ENABLE);
        /* Boost the execution priority to 0: no further exception can be asserted */
		NVIC_SETPRIMASK();
		#ifdef RTC_Alarm_WFEWakeUp
		  /* Set the RTC Alarm interrupt after 6s */
          RTC_SetAlarm(0xFFFFFFFA);
          /* Wait until last write operation on RTC registers has finished */
          RTC_WaitForLastTask();
          /* Set the Counter to 0xFFFFFFF5 */
          RTC_SetCounter(0xFFFFFFF5);
          /* Wait until last write operation on RTC registers has finished */
          RTC_WaitForLastTask();
		#endif		
        __WFE();
      #endif

      #ifdef  WFESEVONEVENT
       NVIC_SystemLPConfig(NVIC_LP_SEVONPEND, DISABLE);
		#ifdef RTC_Alarm_WFEWakeUp
		  /* Set the RTC Alarm interrupt after 6s */
          RTC_SetAlarm(0xFFFFFFFA);
          /* Wait until last write operation on RTC registers has finished */
          RTC_WaitForLastTask();
          /* Set the Counter to 0xFFFFFFF5 */
          RTC_SetCounter(0xFFFFFFF5);
          /* Wait until last write operation on RTC registers has finished */
          RTC_WaitForLastTask();
		#endif	   
        __WFE();
      #endif
    }

    Delay(0xFFFFF);

	/* Toggle GPIO_LED pin 9 */
    GPIO_WriteBit(GPIO_LED, GPIO_Pin_9, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIO_LED, GPIO_Pin_9)));
  }
}