//******************************************************************************
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_stm32f4xx.s) before to branch to application main.
	   To reconfigure the default setting of SystemInit() function, refer to
	   system_stm32f4xx.c file
	 */
	uint32_t i = 0;
	uint32_t j = 0;
	
	STM_EVAL_LEDInit(LED_BLUE);
	STM_EVAL_LEDInit(LED_GREEN);
	STM_EVAL_LEDInit(LED_ORANGE);
	STM_EVAL_LEDInit(LED_RED);
	
	UART_Configuration();
	
	while(1) /* Infinite loop */
	{
		STM_EVAL_LEDToggle(LED_BLUE);
		STM_EVAL_LEDToggle(LED_GREEN);
		STM_EVAL_LEDToggle(LED_ORANGE);
		STM_EVAL_LEDToggle(LED_RED);
		for(i=0;i<0x00FFFFFF;++i){__NOP();};
		printf("j = %i\n",j++);
	}
}
Example #2
0
/**
 *******************************************************************************
 *    Main function
 *******************************************************************************
 */
int main()
{		
  	RCC_Configuration();				/*!< Configure the system clocks      */   
  	NVIC_Configuration();			    /*!< NVIC Configuration               */ 
	UART_Configuration ();				/*!< UART configuration               */

	uart_printf ("\n\r\n\r");
	uart_printf ("\r System initial...                  ");
	uart_printf (" [OK]. \n");
	uart_printf ("\r System Clock have been configured as 60MHz!\n\n");

    uart_printf ("\r +------------------------------------------------+ \n");
	uart_printf ("\r | CooCox RTOS Demo for Cortex-M3 MCU(STM32F10x). |	\n");
	uart_printf ("\r | Demo in Keil MCBSTM32 Board.                   | \n");
	uart_printf ("\r +------------------------------------------------+ \n\n");



	uart_printf ("\r Initial CooCox RTOS...              ");
	CoInitOS();							/*!< Initial CooCox RTOS 			  */
	uart_printf (" [OK]. \n");


	uart_printf ("\r Create a \"task_init\" task...        ");
	CoCreateTask(task_init, (void *)0, 10,&task_init_Stk[TASK_STK_SIZE-1], TASK_STK_SIZE);
	uart_printf (" [OK]. \n");


	uart_printf ("\r Start multi-task.                   ");
	CoStartOS();


	while (1);
}
Example #3
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 Tick Configuration at 1us */
  SysTick_Config(SystemCoreClock / 100000);
       
  /* System Clocks Configuration */
  RCC_Configuration();
  
  /* UART1 Configuration */
  UART_Configuration();
  
  /* CLCD Configuration */
  CLCD_Configuration();
  
  while (1) {
    if(ParseUSART1) {
      ParseUSART1 = false;
      
      printSysCfg();
    }
  }
  
}
Example #4
0
int main(void)
{
    // init sys
    SystemInit();

    // init peripheral
    UART_Configuration();
    delay_init();   
    KEY_GPIO_Init();
    TIM3_Int_Init(100,7199);
    Motor_Init();
    RGB_LED_Init();
    DHT11_Init();
    IR_Init();

    // init vars
    GenProtocolInit();
    BuzProtocolInit();
    UartInit();

    while(1)
    {
        // handle uart msg
        HandleMsg();
        
        // handle key events
        HandleKey();        

        // business logic tick 
        BuzTick();  
    }
}
Example #5
0
void RTC_Basic(void)
{
    SystemInit();
	UART_Configuration(UART);
    __disable_irq();
    /* enable RTC interrupt */
    NVIC_ClearPendingIRQ(INTRTC_IRQn);
    TSB_CG->IMCGF = CG_IMCGC_RTC_EDGE;
    TSB_CG->IMCGF = CG_IMCGC_RTC_INTEN;
    NVIC_EnableIRQ(INTRTC_IRQn);

    Date_Struct.LeapYear = RTC_LEAP_YEAR_2;
    Date_Struct.Year = (uint8_t) 10;
    Date_Struct.Month = (uint8_t) 12;
    Date_Struct.Date = (uint8_t) 31;
    Date_Struct.Day = RTC_FRI;

    Time_Struct.HourMode = RTC_12_HOUR_MODE;
    Time_Struct.Hour = (uint8_t) 11;
    Time_Struct.AmPm = RTC_PM_MODE;
    Time_Struct.Min = (uint8_t) 59;
    Time_Struct.Sec = (uint8_t) 50;

    RTC_DisableClock();
    RTC_DisableAlarm();

    /* Reset RTC sec counter */
    RTC_ResetClockSec();
    /* Set RTC Time value */
    RTC_SetTimeValue(&Time_Struct);
    /* Set RTC Date value */
    RTC_SetDateValue(&Date_Struct);

    /* Enable 1Hz interrupt */
    RTC_SetAlarmOutput(RTC_PULSE_1_HZ);
    /* Enable RTCINT */
    RTC_SetRTCINT(ENABLE);
    __enable_irq();

    /* waiting for RTC register set finish */
    while (fRTCSetting_ok != 1U) {
        /* Do nothing */
    }
    fRTCSetting_ok = 0U;

    /* Enable RTC Clock function */
    RTC_EnableClock();

    while (1) {
        if (fRTCSetting_ok == 1U) {
            fRTCSetting_ok = 0U;
            demo0();
            demo1();
        } else {
            /* Do nothing */
        }
    }
}
Example #6
0
void KWUP_Demo(void)
{
    KWUP_SettingTypeDef keySetting;
    KWUP_PortStatus portStatus;
    SystemInit();
	UART_Configuration(UART);
    /* set PJ4,PJ5 to Key0,1 */
    TSB_PJ_FR2_PJ4F2 = 1U;
    TSB_PJ_PUP_PJ4UP = 1U;
    TSB_PJ_IE_PJ4IE = 1U;

    TSB_PJ_FR2_PJ5F2 = 1U;
    TSB_PJ_PUP_PJ5UP = 1U;
    TSB_PJ_IE_PJ5IE = 1U;

	UART_Print(UART, "This is an example for KWUP operation\n\r");
    /* enable KWUP interrupt */
    NVIC_ClearPendingIRQ(INTKWUP_IRQn);
    NVIC_EnableIRQ(INTKWUP_IRQn);

    keySetting.KeyN = KWUP_INPUT_0;
    keySetting.PullUpCtrl = KWUP_PUP_CTRL_BY_DYNAMIC;
    keySetting.ActiveState = KWUP_ACTIVE_BY_RISING_EDGE;
    keySetting.INTNewState = ENABLE;
    KWUP_SetConfig(&keySetting);

    KWUP_SetPullUpConfig(KWUP_CYCLES_4_FS, KWUP_CYCLES_256_FS);

    KWUP_ClearINTReq();

    /* enable low power mode release interrupt to KWUP */
    TSB_CG->IMCGF = 0x1000U;
    TSB_CG->IMCGF += 0x0100U;

    do {
        portStatus = KWUP_GetPortStatus();
		UART_Print(UART, "Please press key(PJ5) to enter low power mode\n\r");
		while(portStatus.Bit.Key1 != 0U)/* press key(PJ5) */
		{
			portStatus = KWUP_GetPortStatus();
		}
		UART_Print(UART, "enter low power mode\n\r");
		/* enter low power mode */
		UART_Print(UART, "press KEY(PJ4) to release low power mode\n\r");
		__WFI();

		/* press KEY(PJ4) to release low power mode */
		UART_Print(UART, "release low power mode\n\r");
        
    }while (1);
}
Example #7
0
int main()
{

    /*System clock configuration*/
    SystemInit();
	
    /* UART configuration */
    UART_Configuration();
   
    UartPuts(UART1,"*****W7500 RNG TEST*****\r\n");

	  // Read Power up random value
	  rng_data = RNG_ReadRandomNumber();
	  printf("Initial random number = %d\r\n", rng_data);
	
	  // RNG Initialize : Change RNG mode to manual RUN
	  RNG_Init ();
	  
	  // RNG RUN & STOP
	  RNG_Run(ENABLE);
		__NOP();
		__NOP();
		RNG_Run(DISABLE);
		
		// Read Manual RUN RNG Data
		rng_data = RNG_ReadRandomNumber();
	  printf("manual run & stop random number = %d\r\n", rng_data);
	
	  // Change Seed value & polynimials
    RNG_SetSeedvalue(0x30002001);
	  RNG_SetPolynomial(0x90001011);
		
		// RNG RUN & STOP again
		RNG_Run(ENABLE);
		__NOP();
		__NOP();
		RNG_Run(DISABLE);
		
		// Read 2nd Manual RUN RNG data
		rng_data = RNG_ReadRandomNumber();
		printf("updated polynomial & seed value\r\n");
	  printf("manual run & stop random number = %d\r\n", rng_data);
	  printf("\r\n");
}
Example #8
0
void FC_Basic(void)
{
    FunctionalState tmp_value_sec0, tmp_value_sec1, tmp_value_block;
	
	UART_Configuration(UART);
	UART_Print(UART, "This is an example for FC\n\r");

	/* Set security function "ENABLE" */
	FC_SetSecurityBit(ENABLE);
	UART_Print(UART, "Enable the Security Function\n\r");
	/* Get security register value */
	tmp_value_sec0 = FC_GetSecurityBit();
	if (tmp_value_sec0 != ENABLE) {
		UART_Print(UART, "Security register value is disable\n\r");
	}else{
		UART_Print(UART, "Security register value is enable\n\r");
	}

	/* Set security function "DISABLE" */
	FC_SetSecurityBit(DISABLE);
	UART_Print(UART, "Disable the Security Function\n\r");
	/* Get security register value */
	tmp_value_sec1 = FC_GetSecurityBit();
	if (tmp_value_sec1 != DISABLE) {
		UART_Print(UART, "Security register value is enable\n\r");
	}else{
		UART_Print(UART, "Security register value is diable\n\r");
	}

	/* Get Block 0 Protection status */
	tmp_value_block = FC_GetBlockProtectState(FC_BLOCK_0);
	UART_Print(UART, "Getting Block 0 Protection status\n\r");
	if (tmp_value_block != DISABLE) {
		UART_Print(UART, "The status is enable\n\r");
	}else{
		UART_Print(UART, "The status is diable\n\r");
	}
	
	/* Wait for Ready */
	while (FC_GetBusyState() != DONE) {
		/* Do nothing */
	};

}
Example #9
0
void TB0_print(void)
{
    TMRB_InitTypeDef myTMRB;
	  WDT_Disable();
    UART_Configuration(UART0);

	  UART_Print(UART0, "This is a TIMER example!\n\r\n\r");
    myTMRB.Mode = TMRB_INTERVAL_TIMER;
    myTMRB.ClkDiv = TMRB_CLK_DIV_8;
    myTMRB.Cycle = TMRB_1ms;    /* Specific value depends on system clock */
    myTMRB.UpCntCtrl = TMRB_AUTO_CLEAR;
    myTMRB.Duty = TMRB_1ms / 2U;        /* Specific value depends on system clock */

    TMRB_Enable(TSB_TB0);
    TMRB_Init(TSB_TB0, &myTMRB);
    TMRB_SetRunState(TSB_TB0, TMRB_RUN);
    NVIC_EnableIRQ(INTTB0_IRQn);
    while (1) {
        /* Do nothing */
    }
}
Example #10
0
void  BSP_Init (void)
{
	SystemInit();
	UART_Configuration();	
//	KEY_GPIO_Init();
//	TIM3_Int_Init(100,7199);
	

	//应用初始化,包括电机、LED、温湿度、红外;
//	Motor_Init();	
//	RGB_LED_Init();
//	LT8900IO_Init();
//	LT_init();

//	RF_Init();
//	IrInit();
//	DHT11_Init();
//BSP_LED_Init();                 /* Initialize the LED  */
//	Init_Uart_on_Chip(9600);
//	BSP_KEY_Init();  
//初始化各类型数据帧
	McuStatusInit();
}
Example #11
0
void BSP_Configuration (void)
{
	GetCPUInfo ();	
	BSP_PowerInit ();
	BSP_PowerDown ();
	BSP_PowerUp ();	
	_BSP_NvicInit ();	
	UART_Configuration ();
	DisplayCPUInfo ();	
	/* SSD1906驱动初始化 使其初始化为RGB模式 */
	ILI_Configuration ();
	LIG_Configuration ();
	SSD1906_Configurationg ();
	STK_Configuration ();
	/* 继电器配置成断开连接 */
	RL_Configuration ();
	if(UM_GET_SYSTEMPARA&PARA_BEEP_MASK){
		API_GUI_OpenSpeak ();
		speak_jif = jiffies+30;
	}
	/* AD7687初始化配置 SPI模式,SCK与WV_Configuration共用,FTM初始化,采用中断方式采集 */
	AD7687_Configuration ();
	/* 波形发生器初始化配置,配置ML2035和AD5453,采用模拟SPI,在使用时,将SCK初始化为IO模式,在恢复SPI */
	WV_Configuration ();
	/* ADG409模拟开关芯片配置,通道一 */
	ADG_Configuration ();
	/* RTC初始化 */
	RTC_Init ();
	/* BAT电量初始化 */
	BSP_BatterCheckInit ();
	RF_Init ();
	//SN74121_Init ();
	//STK_Configuration ();
	STK_delay10ms(50);
	GUI_Get_Keymsg ();
	WDOG_Init (60000);
}
Example #12
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();
}
Example #13
0
File: SRAM.c Project: coocox/Mplib
/* The demo is for external 16-bit SRAM, separate bus mode */
void SRAM(void)
{
    uint8_t chip = 0xFFU;
    SMC_IFConfigTypeDef config = { 0U };
    uint8_t bus_w = 0xFFU;
    uint8_t bus_r = 0xFFU;
    SMC_CyclesTypeDef cycles_w = { 0U };
    SMC_CyclesTypeDef cycles_r = { 0U };
    SMC_OpModeTypeDef opmode_w = { 0U };
    SMC_OpModeTypeDef opmode_r = { 0U };
    SMC_DirectCMDTypeDef cmd = { 0U };
	uint8_t retval = 0U;

	UART_Configuration(UART);
	UART_Print(UART, "This is an example for SMC\n\r");
	UART_Print(UART, "Initializing the SRAM...\n\r");

    /* Initial process demo */

    /* Herein describe SRAM model number and basic infomation */
    /* CS0: 0x60000000 ~ 0x60FFFFFF(16MB) */
    /* CS1: 0x61000000 ~ 0x61FFFFFF(16MB) */
    /* CS2: 0x62000000 ~ 0x62FFFFFF(16MB) */
    /* CS3: 0x63000000 ~ 0x63FFFFFF(16MB) */
    chip = SMC_CS2;

    bus_w = SMC_BUS_MULTIPLEX;  /* Address bus and data bus are multiplexed */
    SMC_SetBusMode(bus_w);

    bus_r = SMC_GetBusMode();
    if (bus_w != bus_r) {
        retval |= 0x01U;
    }

    SMC_GetIFConfig(&config);
    if (config.MemoryType != SMC_MULTIPLEX_SRAM) {
        /* If multiplex bus mode, MemoryType is SMC_MULTIPLEX_SRAM */
        retval = 0x02U;
    }
    if (config.MemoryWidth != SMC_DATA_BUS_16BIT) {
        /* SMC_DATA_BUS_16BIT can not be read out if no external memory, */
        /* and default value of "0x02" will be read out. */
        retval |= 0x04U;
    }
    if ((config.MemoryChips) != SMC_MEMORY_CHIPS_4) {
        retval |= 0x08U;
    }

    /* Set cycles time according to AC timing of SRAM datasheet,base clock: SMCCLK(fsys*1/2) */

    /* Separate bus mode:tCEOE + SMCCLK*1clk <= tRC  */
    /* Multiplex bus mode:tCEOE + SMCCLK*2clk <= tRC */
    cycles_w.RC_Time = SMC_READ_CYCLE_TIME_5;
    /* Separate bus mode:tWP + SMCCLK*2clk <= tWC  */
    /* Multiplex bus mode:tWP + SMCCLK*3clk <= tWC */
    cycles_w.WC_Time = SMC_WRITE_CYCLE_TIME_5;
    cycles_w.CEOE_Time = SMC_CEOE_DELAY_CYCLE_TIME_1;
    cycles_w.WP_Time = SMC_WE_PULSE_CYCLE_TIME_1;

    /* PC_Time is only effective for separate bus mode */
    /* It's necessary to also set to pass parameter check in multiplex bus mode */
    cycles_w.PC_Time = SMC_PAGE_CYCLE_TIME_5;

    cycles_w.TR_Time = SMC_TURN_AROUND_CYCLE_TIME_1;
    SMC_SetCycles(&cycles_w);

    opmode_w.BusWidth = SMC_DATA_BUS_16BIT;
    opmode_w.ReadBurstLen = SMC_READ_BURST_4BEAT;
    opmode_w.ALE = ENABLE;      /* ALE must be enabled in multiplex bus mode */
    SMC_SetOpMode(&opmode_w);

    /* Make sure SMC_SetCycles and SMC_SetOpMode are performed before SMC_SendDirectCMD */
    cmd.CmdType = SMC_CMD_UPDATEREGS;
    cmd.ChipSelect = chip;
    SMC_SendDirectCMD(&cmd);

    /* Read cycles and opmode for verify */
    SMC_GetCycles(chip, &cycles_r);
    if (memcmp(&cycles_r, &cycles_w, sizeof(SMC_CyclesTypeDef)) != 0) {
        retval |= 0x10U;
    }

    SMC_GetOpMode(chip, &opmode_r);
    opmode_w.StartAddr = SMC_START_ADDR_CHIP0 | (uint8_t) chip; /* For compare with read out opmode */
    if (memcmp(&opmode_r, &opmode_w, sizeof(SMC_OpModeTypeDef)) != 0) {
        retval |= 0x20U;
    }

    /* check retval to see if SRAM initialization is sucessful or not */
    if (retval == 0U) {
		UART_Print(UART, "SRAM initialization is sucessful!\n\r");/* Sucessful */
    } else {
		UART_Print(UART, "SRAM initialization is failed!\n\r");/* Failed */
    }
}
Example #14
0
void CEC_STANDBY(void)
{
    uint32_t Index = 0U;
    uint32_t temp = 0U;
    TSB_WD_MOD_WDTE = 0U;
    TSB_WD->CR = 0x000000B1;
    SystemInit();
	UART_Configuration(UART0);
    /*initial cec port */
    TSB_PK->CR = 0x01U;
    TSB_PK->FR1 = 0x01U;
    TSB_PK->IE = 0x01U;
    /*initial cec frame data buffer */
    CEC_RxFrame.Initiator = CEC_UNKNOWN;
    CEC_RxFrame.Destination = CEC_UNKNOWN;
    CEC_RxFrame.Opcode = 0xFFU;
    CEC_RxFrame.current_num = 0x0U;
    CEC_RxFrame.Max_num = 0x0U;
    CEC_RxFrame.current_state = DATA_INIT;
    for (Index = 0U; Index < 17U; Index++) {
        CEC_RxFrame.CEC_Data[Index] = 0xFFU;
    }
    CEC_RxFrameTmp = CEC_RxFrame;
    CEC_TxFrame = CEC_RxFrame;
    /*initial cec register */
    CEC_Enable();
    CEC_SWReset();
    while (CEC_GetRxState() == ENABLE);
    while (CEC_GetTxState() == BUSY);
    CEC_DefaultConfig();

    /*initial cec interupt */
    __disable_irq();
    TSB_CG->IMCGB = 0x00300000U;
    TSB_CG->IMCGD = 0x00000030U;
    TSB_CG->IMCGB = 0x00310000U;
    TSB_CG->IMCGD = 0x00000031U;
    TSB_CG->ICRCG = 0x06U;
    TSB_CG->ICRCG = 0x0cU;
    NVIC_EnableIRQ(INTCECRX_IRQn);
    NVIC_EnableIRQ(INTCECTX_IRQn);
    __enable_irq();

    /*set logical address TV */
    CEC_SetLogicalAddr(CEC_TV);
    /*Enable CEC reception */
    CEC_SetRxCtrl(ENABLE);

    while (1) {
        /*Recieve new frame or not */
        if (CEC_RxFrameTmp.current_state == DATA_END) {
            CEC_RxFrame = CEC_RxFrameTmp;
            CEC_RxFrameTmp.current_num = 0U;
            CEC_RxFrameTmp.current_state = DATA_INIT;
            temp = CEC_RxFrame.current_num;

            if (temp > 0U) {
                UART_Print(UART0, "CEC Message: ");
                for (Index = 0U; Index < temp; Index++) {
                    UART_Print(UART0, "0x%2x " + CEC_RxFrame.CEC_Data[Index]);
                }
                UART_Print(UART0, "\n");
            }

            for (Index = 0U; Index < 17U; Index++) {
                CEC_RxFrameTmp.CEC_Data[Index] = 0xFFU;
            }
            /*CEC message is "Active Source" */
            if (CEC_RxFrame.CEC_Data[1] == 0x82U) {
                CEC_Send_Frame(CEC_TV, CEC_BROADCAST, 0x36U, 0U, CEC_RxFrame.CEC_Data);
            }
        }
    }
}
Example #15
0
/* SSP_LoopBack function */
void SSP_LoopBack(void)
{
    SSP_InitTypeDef initSSP;
    SSP_FIFOState fifoState;
	
    uint16_t datTx = 0U;        /* must use 16bit type */
    uint32_t cntTx = 0U;
    uint32_t cntRx = 0U;

    uint16_t receive = 0U;
    uint16_t Rx_Buf[MAX_BUFSIZE] = { 0U };
    uint16_t Tx_Buf[MAX_BUFSIZE] = { 0U };

    SystemInit();

    /* enable the LED on board to display some info */
    UART_Configuration(UART);
    UART_Print(UART, "This is an example for SSP module!\n\r");

    /* configure the SSP module */
    initSSP.FrameFormat = SSP_FORMAT_SPI;

    /* default is to run at maximum bit rate */
    initSSP.PreScale = 2U;
    initSSP.ClkRate = 1U;
    /* define BITRATE_MIN to run at minimum bit rate */
    /*   BitRate = fSYS / (PreScale x (1 + ClkRate)) */
#ifdef BITRATE_MIN
    initSSP.PreScale = 254U;
    initSSP.ClkRate = 255U;
#endif
    initSSP.ClkPolarity = SSP_POLARITY_LOW;
    initSSP.ClkPhase = SSP_PHASE_FIRST_EDGE;
    initSSP.DataSize = 16U;
    initSSP.Mode = SSP_MASTER;
    SSP_Init(&initSSP);


    /* enable loop back mode for self test */
    SSP_SetLoopBackMode(ENABLE);

    /* enable and run SSP module */
    SSP_Enable();

    while (1) {
        
        datTx++;
        
        /* send data if Tx FIFO is available */
        fifoState = SSP_GetFIFOState(SSP_TX);
        if ((fifoState == SSP_FIFO_EMPTY) || (fifoState == SSP_FIFO_NORMAL)) {
            SSP_SetTxData(datTx);
            if (cntTx < MAX_BUFSIZE) {
                Tx_Buf[cntTx] = datTx;
                cntTx++;
            } else {
                /* do nothing */
            }
        } else {
            /* do nothing */
        }


        /* check if there is data arrived */
        fifoState = SSP_GetFIFOState(SSP_RX);
        if ((fifoState == SSP_FIFO_FULL) || (fifoState == SSP_FIFO_NORMAL)) {
            receive = SSP_GetRxData();
            if (cntRx < MAX_BUFSIZE) {
                Rx_Buf[cntRx] = receive;
                cntRx++;
            } else {
                /* Place a break point here to check if receive data is right.                */
                /* Success Criteria:                                                          */
                /*               Every data transmited from Tx_Buf is received in Rx_Buf.     */
                /* When the line "#define BITRATE_MIN" is commented, the SSP is run in maxium */
                /*  bit rate, so we can find there is enough time to transmit date from 1 to  */
                /*  MAX_BUFSIZE one by one. but if we uncomment that line, SSP is run in      */
                /*  minimum bit rate, we will find that receive data can't catch "datTx++",   */
                /*  in this so slow bit rate, when the Tx FIFO is available, the cntTx has    */
                /*  been increased so much.                                                   */
                __NOP();
            }

        } else {
            /* do nothing */
        }
        sprintf(message, "Received data is %d\n\r" + (uint8_t)(receive / 8000));
        UART_Print(UART, message);
    }
}
Example #16
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
      
  }
}
Example #17
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;
}
Example #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 */
  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
      
  }
}
Example #19
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;

    /* 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_On(LED1);
	LED_Off(LED2);

	BOOT_Pin_Init();

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

	/* Check MAC Address */
	check_mac_address();

	Timer0_Configuration();

#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 TFTP App 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

#if 0
    /* Network Configuration */
    setSHAR(mac_addr);
    setSIPR(src_addr);
    setGAR(gw_addr);
    setSUBR(sub_addr);

    getSHAR(tmp);
    printf("MAC ADDRESS : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\r\n",tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5]);
    getSIPR(tmp);
    printf("IP ADDRESS : %.3d.%.3d.%.3d.%.3d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 
    getGAR(tmp);
    printf("GW ADDRESS : %.3d.%.3d.%.3d.%.3d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 
    getSUBR(tmp);
    printf("SN MASK: %.3d.%.3d.%.3d.%.3d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 

    /* Set Network Configuration */
    //wizchip_init(tx_size, rx_size);
#else
	Net_Conf();
#endif

	//TFTP_init(SOCK_TFTP, socket_buf);

	while (1) {
		if(g_op_mode == NORMAL_MODE) {
			do_udp_config(SOCK_CONFIG);
		} else {
			if(TFTP_run() != TFTP_PROGRESS)
				g_op_mode = NORMAL_MODE;
		}
	}

    return 0;
}
Example #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
      
  }
}
Example #21
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
//	int c;
   /*!< 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
     */     
    SystemInit();
	RCC_GetClocksFreq(&RCC_Clocks);
    SysTick_Config(SystemCoreClock / SYSTICK_FREQUENCY_HZ);

#ifdef TRACEUART
    TRACEUART_Configuration();
#endif //TRACEUART
	UART_Configuration();

	LED_Init();

	/* Output a message on Hyperterminal using printf function */
	printf("\n\r\n\r");
	printf("*** LATTICE FW LOADER V1.00 Build by phalt on ("__DATE__ "-" __TIME__ ")\n\r");
	printf("*** LATTICE FW LOADER V1.00 Rebooting ...\n\r");

	/*
     * wait for a keystroke (or a button press if you want.)
	*/
//    printf("\n\rPress Return to start, any other key To Enter the Console ...\n\r");
//	c = awaitkey(DEFAULT_BOOT_DELAY);
	if(1) 			//(((c != '\r') && (c != '\n') && (c != '\0')))
    {
		Delay(500);
		GPIO_ResetBits(BLINK_PORT, (0xF << LED1));
//		traceprintf("\rtrace start OK\n\r");
//		Codec_GPIO_Init();
//		Delay(1);
//		/* Reset the Codec Registers */
//		Codec_Reset();
//		Delay(1);
//		/* Initialize the Control interface of the Audio Codec */
//		Codec_CtrlInterface_Init();
//		Delay(1);
		if(1)
		{
	        GPIO_SetBits(BLINK_PORT, (0xF << LED1));
//	        WavePlayBack(AUDIOFREQ, 1);
	        WavePlayerInit(AUDIOFREQ);
	        GPIO_ResetBits(BLINK_PORT, (0xF << LED1));
		}
		while(1)						//eugene loop
		{
//			Codec_CtrlInterface_Init();
			GPIO_SetBits(BLINK_PORT, (0x1 << LED1));
//			Codec_Write();
			Codec_ReadRegister(0x00); //test read of codec
			GPIO_ResetBits(BLINK_PORT, (0x1 << LED1));
			Delay(1000);
		}

		if(1)									//test
		{
			init_builtin_cmds();
			serial_term();
		}


    }
	printf("*** JUMP to Application now ...\n\r");
    run_app(0x08000000);



    /* Infinite loop */
	while (1);
}
Example #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
     */
  
  /* 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
      
  }
Example #23
0
/**
  * @brief  wifi_init
  *         User API for wifi init
  * @param  None
  * @retval None
  */
WiFi_Status_t wifi_init(wifi_config* config)
{
#ifndef WIFI_USE_VCOM
  uint8_t tx_level;
#endif
  
  WiFi_Status_t status = WiFi_MODULE_SUCCESS;
  
#if DEBUG_PRINT
  printf("\r\nInitializing SPWF01SA1 Interface..\r\n");
#endif  
    
  WiFi_Module_Init();
    
#ifndef WIFI_USE_VCOM  
  wifi_wakeup(WIFI_TRUE);//Prevent from going to sleep during configuration    
  
  /* Soft reset the module */
  wifi_reset();
  
  /* Set localecho1 to 0*/  
  status = SET_Configuration_Value(LOCALECHO1, 0);
  if(status != WiFi_MODULE_SUCCESS) return status;
  
  /* Restore default setting*/    
  Reset_AT_CMD_Buffer();  
  sprintf((char*)(char*)WiFi_AT_Cmd_Buff,AT_RESTORE_DEFAULT_SETTING);  
  status = USART_Transmit_AT_Cmd(strlen((char*)WiFi_AT_Cmd_Buff));
  if(status == WiFi_MODULE_SUCCESS)
  {
    status = USART_Receive_AT_Resp(Receive_AT_Cmd_Response);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }
  
  /* Switch on HW Flow Control*/  
  status = SET_Configuration_Value(CONSOLE1_HWFC, 1);
  if(status != WiFi_MODULE_SUCCESS) return status; 
  
  if(config->wifi_baud_rate)
  {
    /* Set USART Speed*/  
    status = SET_Configuration_Value(CONSOLE1_SPEED, config->wifi_baud_rate);
    if(status != WiFi_MODULE_SUCCESS) return status; 
  }
  
  /* Set wifi_mode to idle*/  
  status = SET_Configuration_Value(WIFI_MODE, WiFi_IDLE_MODE);
  if(status != WiFi_MODULE_SUCCESS) return status;   
  
  switch(config->ht_mode)
  {
  case WIFI_FALSE:
    status = SET_Configuration_Value(WIFI_HT_MODE, 0);
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Addr(WIFI_OPR_RATE_MASK, "0x00003FCF");
    if(status != WiFi_MODULE_SUCCESS) return status;
    break;
  case WIFI_TRUE:
    status = SET_Configuration_Value(WIFI_HT_MODE, 1);
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Addr(WIFI_OPR_RATE_MASK, "0x003FFFCF");
    if(status != WiFi_MODULE_SUCCESS) return status;
    break;
  default:
    break;
  }
  
  switch(config->power)
  {
  case active:
    status = SET_Configuration_Value(WIFI_POWERSAVE, 0);
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Value(WIFI_SLEEP_ENABLED, 0);  
    if(status != WiFi_MODULE_SUCCESS) return status;
    break;
  case reactive:
    status = SET_Configuration_Value(WIFI_POWERSAVE, 1);
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Value(WIFI_OPERATIONAL_MODE, 11);  
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Value(WIFI_BEACON_WAKEUP, 0);
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Value(WIFI_LISTEN_INTERVAL, 0);
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Value(WIFI_SLEEP_ENABLED, 0);  
    if(status != WiFi_MODULE_SUCCESS) return status;
    break;
  case sleep:
    status = SET_Configuration_Value(WIFI_POWERSAVE, 1);
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Value(WIFI_OPERATIONAL_MODE, 12);  
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Value(WIFI_BEACON_WAKEUP, 10);
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Value(WIFI_LISTEN_INTERVAL, 1);
    if(status != WiFi_MODULE_SUCCESS) return status;
    status = SET_Configuration_Value(WIFI_SLEEP_ENABLED, 1);  
    if(status != WiFi_MODULE_SUCCESS) return status;
    break;
  default:
    break;
  }
  
  switch(config->power_level)
  {
  case low:
  case medium:
  case high:
  case max:
    tx_level=config->power_level*6;
    status = SET_Configuration_Value(WIFI_TX_POWER, tx_level);
    if(status != WiFi_MODULE_SUCCESS) return status;
    break;
  default:
    break;
  }
  
  switch(config->dhcp)
  {
  case off:
  case on:
  case custom:
    status = SET_Configuration_Value(IP_USE_DHCP_SERVER, config->dhcp);
    if(status != WiFi_MODULE_SUCCESS) return status;
    break;
  default:
    break;
  }
  
  /* Set IP address */
  if(config->ip_addr)
  {
    status = SET_Configuration_Addr(WIFI_IP_ADDRESS, config->ip_addr);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }
  /* Set netmask address */
  if(config->netmask_addr)
  {
    status = SET_Configuration_Addr(WIFI_IP_NETMASK, config->netmask_addr);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }
  /* Set default gateway address */
  if(config->gateway_addr)
  {
    status = SET_Configuration_Addr(WIFI_IP_DEFAULT_GATEWAY, config->gateway_addr);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }
  /* Set dns address */
  if(config->dns_addr)
  {
    status = SET_Configuration_Addr(WIFI_IP_DNS, config->dns_addr);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }
  /* Set hostname */
  if(config->host_name)
  {
    status = SET_Configuration_Addr(WIFI_IP_HOSTNAME, config->host_name);  
    if(status != WiFi_MODULE_SUCCESS) return status;
  }
  
  if(config->ap_domain_name)
  {
    status = SET_Configuration_Addr(WIFI_IP_APDOMAINNAME, config->ap_domain_name);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }
  
  if(config->ap_config_page_name)
  {
    status = SET_Configuration_Addr(WIFI_IP_APREDIRECT, config->ap_config_page_name);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }
  
  if(config->http_timeout)
  {
    status = SET_Configuration_Value(WIFI_IP_HTTP_TIMEOUT, config->http_timeout*1000);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }
  if(config->dhcp_timeout)
  {
    status = SET_Configuration_Value(WIFI_IP_DHCP_TIMEOUT, config->dhcp_timeout);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }   

#ifdef MODULE_VERSION_SPWF01Sx_1y
  Reset_AT_CMD_Buffer();  
  sprintf((char*)(char*)WiFi_AT_Cmd_Buff,AT_HTTPD, config->web_server);  
  status = USART_Transmit_AT_Cmd(strlen((char*)WiFi_AT_Cmd_Buff));
  if(status == WiFi_MODULE_SUCCESS)
  {
    status = USART_Receive_AT_Resp(Receive_AT_Cmd_Response);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }  
#endif  
  
  /*AT+S.TLSCERT2=clean,all */
  Reset_AT_CMD_Buffer();  
  sprintf((char*)(char*)WiFi_AT_Cmd_Buff,"AT+S.TLSCERT2=clean,all\r");        
  status = USART_Transmit_AT_Cmd(strlen((char*)WiFi_AT_Cmd_Buff));
  if(status == WiFi_MODULE_SUCCESS)
  {
    status = USART_Receive_AT_Resp(Receive_AT_Cmd_Response);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }  
  
  /* save current setting in flash */
  Reset_AT_CMD_Buffer();  
  sprintf((char*)(char*)WiFi_AT_Cmd_Buff,AT_SAVE_CURRENT_SETTING);  
  status = USART_Transmit_AT_Cmd(strlen((char*)WiFi_AT_Cmd_Buff));
  if(status == WiFi_MODULE_SUCCESS)
  {
    status = USART_Receive_AT_Resp(Receive_AT_Cmd_Response);
    if(status != WiFi_MODULE_SUCCESS) return status;
  }   
  
  if(config->wifi_baud_rate)
  {
    UART_Configuration(config->wifi_baud_rate); 
    Receive_Data();//Restart data reception
  }
  
  /* Soft reset the module, Do the second reset after setting all parameters and saving in flash */
  wifi_reset();

  wifi_wakeup(WIFI_FALSE);//De-assert wakeup signal (PC13) to allow sleep if enabled
#endif  //WIFI_USE_VCOM
  
#if DEBUG_PRINT
  printf("\r\nEnd of Initialization..\r\n");
#endif
  
  return status;
}