Beispiel #1
0
static  void  AppTaskStart (void *p_arg)
{
    OS_ERR   err;
#if (APP_CFG_TCPIP_MODULE_EN > 0u)
    NET_ERR  net_err;
#endif


   (void)&p_arg;

    BSP_Init();                                                 /* Initialize BSP functions                             */
    CPU_Init();                                                 /* Initialize the uC/CPU services                       */
    OS_CPU_TickInit();                                          /* Init uC/OS periodic time src (SysTick).              */

#if (OS_CFG_STAT_TASK_EN > 0u)
    OSStatTaskCPUUsageInit(&err);                               /* Compute CPU capacity with no task running            */
#endif

    Mem_Init();                                                 /* Initialize mem mgmt module, required for TCP-IP.     */

#if (APP_CFG_PROBE_COM_MODULE_EN > 0u)
    AppProbe_Init();                                            /* Initialize uC/Probe modules                          */
#endif

    OSTaskCreate((OS_TCB     *)&AppAccelTaskTCB,                /* Create the accelerometer task                        */
                 (CPU_CHAR   *)"Accel Task",
                 (OS_TASK_PTR ) AppAccelTask,
                 (void       *) 0,
                 (OS_PRIO     ) ACCEL_TASK_PRIO,
                 (CPU_STK    *)&AppAccelTaskStk[0],
                 (CPU_STK_SIZE) ACCEL_TASK_STK_SIZE / 10u,
                 (CPU_STK_SIZE) ACCEL_TASK_STK_SIZE,
                 (OS_MSG_QTY  ) 0u,
                 (OS_TICK     ) 0u,
                 (void       *) 0,
                 (OS_OPT      )(OS_OPT_TASK_STK_CHK | OS_OPT_TASK_STK_CLR),
                 (OS_ERR     *)&err);

    OSTaskCreate((OS_TCB     *)&AppTempTaskTCB,                 /* Create the temperature task                          */
                 (CPU_CHAR   *)"Temp Task",
                 (OS_TASK_PTR ) AppTempTask,
                 (void       *) 0,
                 (OS_PRIO     ) TEMPERATURE_TASK_PRIO,
                 (CPU_STK    *)&AppTempTaskStk[0],
                 (CPU_STK_SIZE) TEMPERATURE_TASK_STK_SIZE / 10u,
                 (CPU_STK_SIZE) TEMPERATURE_TASK_STK_SIZE,
                 (OS_MSG_QTY  ) 0u,
                 (OS_TICK     ) 0u,
                 (void       *) 0,
                 (OS_OPT      )(OS_OPT_TASK_STK_CHK | OS_OPT_TASK_STK_CLR),
                 (OS_ERR     *)&err);

    BSP_GraphLCD_Init();
    AppGraphLCD_Hdr();

#if (APP_CFG_TCPIP_MODULE_EN > 0u)
    AppTCPIP_Init(&net_err);                                    /* Initialize uC/TCP-IP & associated applications.      */
    AppCloud_Init(0);
#endif

#ifdef CPU_CFG_INT_DIS_MEAS_EN
    CPU_IntDisMeasMaxCurReset();
#endif

    AppTCPIP_Cfg = DEF_TRUE;

    while (DEF_ON) {
        OSTimeDlyHMSM(0u, 0u, 0u, 100u,
                      OS_OPT_TIME_HMSM_STRICT,
                      &err);
    }
}
Beispiel #2
0
static	void	App_TaskStart(void *p_arg)
{
	volatile  uint32_t status;
	int8u bufp[7] = {0xc4,0x01,0x01,0x00,0x00,0x00,0x55};
	uint8_t *ptr;
	uint8_t err;
	
	(void) p_arg;

	
	//系统滴答安装
	OS_CPU_SysTickInit();   

	//初始化信号量
	app_eventcreate();

	//初始化其他任务
	app_taskcreate();
	


	//初始化基础硬件
	BSP_Init();
	
	dw1000_init();

{
	dwtconf temp;
	temp.config.chan = 3;
	temp.config.prf = DWT_PRF_16M;
	
	temp.config.txPreambLength = DWT_PLEN_256;
	temp.config.rxPAC = DWT_PAC16;
	
	temp.config.rxCode = 5;
	temp.config.txCode = 5;
	temp.config.nsSFD = 1;
	
	temp.config.dataRate = DWT_BR_850K;
	temp.config.smartPowerEn = 0;
	
	temp.config.phrMode = 0;
	
	temp.mode = LOCA_LISTENER;
	dw1000_config(&temp);

}
dwt_rxenable(0);

	  USBD_Init(&USB_OTG_dev,
            USB_OTG_FS_CORE_ID, 
            &USR_desc, 
            &USBD_CDC_cb, 
            &USR_cb);
//dw1000_intenable();
	//发送log
	//Shell_SendDatas(strlen(logstr), logstr);

	//改变自己优先级 变为工作指示灯
	//OSTaskDel(OS_PRIO_SELF);
	OSTaskChangePrio(OS_PRIO_SELF, OS_LOWEST_PRIO - 4);
	
	while(TURE)
	{
	//	OSTimeDlyHMSM(0, 0, 0, 10);
		//dwt_writetxdata(127,msg,0);
		//dwt_writetxfctrl(127,0);
		//dwt_starttx(DWT_START_TX_IMMEDIATE);
	//	bufp[1] ++;
		//status = dwt_read32bitreg(SYS_STATUS_ID);


		ptr = OSQPend(qmsg, 0, &err);
		if (err == OS_ERR_NONE)
		{
		VCP_fops.pIf_DataTx(ptr+1, ptr[0]);

		free(ptr);
		}
	}
}
void main (void)
{
  bspIState_t intState;

#ifdef FREQUENCY_AGILITY
  memset(sSample, 0x0, sizeof(sSample));
#endif

  BSP_Init();

  /* If an on-the-fly device address is generated it must be done before the
   * call to SMPL_Init(). If the address is set here the ROM value will not
   * be used. If SMPL_Init() runs before this IOCTL is used the IOCTL call
   * will not take effect. One shot only. The IOCTL call below is conformal.
   */
#ifdef I_WANT_TO_CHANGE_DEFAULT_ROM_DEVICE_ADDRESS_PSEUDO_CODE
  {
    addr_t lAddr;

    createRandomAddress(&lAddr);
    SMPL_Ioctl(IOCTL_OBJ_ADDR, IOCTL_ACT_SET, &lAddr);
  }
#endif /* I_WANT_TO_CHANGE_DEFAULT_ROM_DEVICE_ADDRESS_PSEUDO_CODE */

  SMPL_Init(sCB);

  /* green and red LEDs on solid to indicate waiting for a Join. */
  if (!BSP_LED2_IS_ON())
  {
    toggleLED(2);
  }
  if (!BSP_LED1_IS_ON())
  {
    toggleLED(1);
  }

  /* main work loop */
  while (1)
  {
    /* manage FHSS schedule if FHSS is active */
    FHSS_ACTIVE( nwk_pllBackgrounder( false ) );
    
    /* Wait for the Join semaphore to be set by the receipt of a Join frame from a
     * device that supports an End Device.
     *
     * An external method could be used as well. A button press could be connected
     * to an ISR and the ISR could set a semaphore that is checked by a function
     * call here, or a command shell running in support of a serial connection
     * could set a semaphore that is checked by a function call.
     */
    if (sJoinSem && (sNumCurrentPeers < NUM_CONNECTIONS))
    {
      /* listen for a new connection */
      while (1)
      { /* SMPL_LinkListen will call nwk_PllBackgrounder for us if FHSS active */
        if (SMPL_SUCCESS == SMPL_LinkListen(&sLID[sNumCurrentPeers]))
        {
          break;
        }
        /* Implement fail-to-link policy here. otherwise, listen again. */
      }

      sNumCurrentPeers++;

      BSP_ENTER_CRITICAL_SECTION(intState);
      sJoinSem--;
      BSP_EXIT_CRITICAL_SECTION(intState);
    }

    /* Have we received a frame on one of the ED connections?
     * No critical section -- it doesn't really matter much if we miss a poll
     */
    if (sPeerFrameSem)
    {
      uint8_t     msg[MAX_APP_PAYLOAD], len, i;

      /* process all frames waiting */
      for (i=0; i<sNumCurrentPeers; ++i)
      {
        if (SMPL_SUCCESS == SMPL_Receive(sLID[i], msg, &len))
        {
          processMessage(sLID[i], msg, len);

          BSP_ENTER_CRITICAL_SECTION(intState);
          sPeerFrameSem--;
          BSP_EXIT_CRITICAL_SECTION(intState);
        }
      }
    }
    if (BSP_BUTTON1())
    {
      SPIN_ABOUT_A_QUARTER_SECOND;  /* debounce */
      changeChannel();
    }
    else
    {
      checkChangeChannel();
    }
    BSP_ENTER_CRITICAL_SECTION(intState);
    if (sBlinky)
    {
      if (++sBlinky >= 0xF)
      {
        sBlinky = 1;
        toggleLED(1);
        toggleLED(2);
      }
    }
    BSP_EXIT_CRITICAL_SECTION(intState);
  }

}
/** This function will initial STM32 board**/
void rt_hw_board_init()
{
	BSP_Init();
}
//*****************************************************************************
//
// Main application entry function.
//
//*****************************************************************************
int
main(void)
{
    tBoolean bRetcode;
    smplStatus_t eRetcode;
    ioctlScanChan_t sScan;
    freqEntry_t pFreq[NWK_FREQ_TBL_SIZE];
    tBoolean bFirstTimeThrough;
    unsigned long ulLoop;
    uint8_t ucLast;

    //
    // Set the system clock to run at 50MHz from the PLL
    //
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // NB: We don't call PinoutSet() in this testcase since the EM header
    // expansion board doesn't currently have an I2C ID EEPROM.  If we did
    // call PinoutSet() this would configure all the EPI pins for SDRAM and
    // we don't want to do this.
    //
    g_eDaughterType = DAUGHTER_NONE;

    //
    // Enable peripherals required to drive the LCD.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOH);

    //
    // Configure SysTick for a 10Hz interrupt.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / TICKS_PER_SECOND);
    ROM_SysTickEnable();
    ROM_SysTickIntEnable();

    //
    // Initialize the display driver.
    //
    Kitronix320x240x16_SSD2119Init();

    //
    // Initialize the touch screen driver.
    //
    TouchScreenInit();

    //
    // Set the touch screen event handler.
    //
    TouchScreenCallbackSet(WidgetPointerMessage);

    //
    // Add the compile-time defined widgets to the widget tree.
    //
    WidgetAdd(WIDGET_ROOT, (tWidget *)&g_sHeading);

    //
    // Initialize the status string.
    //
    UpdateStatus("Initializing...");

    //
    // Paint the widget tree to make sure they all appear on the display.
    //
    WidgetPaint(WIDGET_ROOT);

    //
    // Initialize the SimpliciTI BSP.
    //
    BSP_Init();

    //
    // Set the SimpliciTI device address using the current Ethernet MAC address
    // to ensure something like uniqueness.
    //
    bRetcode = SetSimpliciTIAddress();

    //
    // Did we have a problem with the address?
    //
    if(!bRetcode)
    {
        //
        // Yes - make sure the display is updated then hang the app.
        //
        WidgetMessageQueueProcess();
        while(1)
        {
            //
            // MAC address is not set so hang the app.
            //
        }
    }

    //
    // Turn on both our LEDs
    //
    SetLED(1, true);
    SetLED(2, true);

    UpdateStatus("Joining network...");

    //
    // Initialize the SimpliciTI stack but don't set any receive callback.
    //
    while(1)
    {
        eRetcode = SMPL_Init((uint8_t (*)(linkID_t))0);

        if(eRetcode == SMPL_SUCCESS)
        {
            break;
        }

        ToggleLED(1);
        ToggleLED(2);
        SPIN_ABOUT_A_SECOND;
    }

    //
    // Tell the user what's up.
    //
    UpdateStatus("Sniffing...");

    //
    // Set up for our first sniff.
    //
    sScan.freq = pFreq;
    bFirstTimeThrough = true;
    ucLast = 0xFF;

    //
    // Keep sniffing forever.
    //
    while (1)
    {
        //
        // Wait a while.
        //
        SPIN_ABOUT_A_QUARTER_SECOND;

        //
        // Scan for the active channel.
        //
        SMPL_Ioctl(IOCTL_OBJ_FREQ, IOCTL_ACT_SCAN, &sScan);

        //
        // Did we find a signal?
        //
        if (1 == sScan.numChan)
        {
            if (bFirstTimeThrough)
            {
                //
                // Set the initial LED state.
                //
                SetLED(1, false);
                SetLED(2, true);

                //
                // Wait a while.
                //
                for(ulLoop = 0; ulLoop < 15; ulLoop--)
                {
                    //
                    // Toggle both LEDs and wait a bit.
                    //
                    ToggleLED(1);
                    ToggleLED(2);
                    SPIN_ABOUT_A_QUARTER_SECOND;
                }
                bFirstTimeThrough = false;
            }

            //
            // Has the channel changed since the last time we updated the
            // display?
            //
            if(pFreq[0].logicalChan != ucLast)
            {
                //
                // Remember the channel we just detected.
                //
                ucLast = pFreq[0].logicalChan;

                //
                // Tell the user which channel we found to be active.
                //
                UpdateStatus("Active channel is %d.", pFreq[0].logicalChan);

                //
                // Set the "LEDs" to mimic the behavior of the MSP430 versions
                // of this application.
                //
                switch(pFreq[0].logicalChan)
                {
                    case 0:
                    {
                        /* GREEN OFF */
                        /* RED   OFF */
                        SetLED(1, false);
                        SetLED(2, false);
                        break;
                    }

                    case 1:
                    {
                        /* GREEN OFF */
                        /* RED   ON */
                        SetLED(1, false);
                        SetLED(2, true);
                        break;
                    }

                    case 2:
                    {
                        /* GREEN ON */
                        /* RED   OFF */
                        SetLED(1, true);
                        SetLED(2, false);
                        break;
                    }

                    case 3:
                    {
                        /* GREEN ON */
                        /* RED   ON */
                        SetLED(1, true);
                        SetLED(2, true);
                        break;
                    }

                    case 4:
                    {
                        /* blink them both... */
                        SetLED(1, false);
                        SetLED(2, false);
                        SPIN_ABOUT_A_QUARTER_SECOND;
                        SetLED(1, true);
                        SetLED(2, true);
                        SPIN_ABOUT_A_QUARTER_SECOND;
                        SetLED(1, false);
                        SetLED(2, false);
                    }
                }
            }
        }
    }
}
//*****************************************************************************
//
// Main application entry function.
//
//*****************************************************************************
int
main(void)
{
    tBoolean bRetcode;
    smplStatus_t eRetcode;
    ioctlToken_t eToken;

    //
    // Set the system clock to run at 50MHz from the PLL
    //
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // NB: We don't call PinoutSet() in this testcase since the EM header
    // expansion board doesn't currently have an I2C ID EEPROM.  If we did
    // call PinoutSet() this would configure all the EPI pins for SDRAM and
    // we don't want to do this.
    //
    g_eDaughterType = DAUGHTER_NONE;

    //
    // Enable peripherals required to drive the LCD.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOH);

    //
    // Configure SysTick for a 10Hz interrupt.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / TICKS_PER_SECOND);
    ROM_SysTickEnable();
    ROM_SysTickIntEnable();

    //
    // Initialize the display driver.
    //
    Kitronix320x240x16_SSD2119Init();

    //
    // Initialize the touch screen driver.
    //
    TouchScreenInit();

    //
    // Set the touch screen event handler.
    //
    TouchScreenCallbackSet(WidgetPointerMessage);

    //
    // Add the compile-time defined widgets to the widget tree.
    //
    WidgetAdd(WIDGET_ROOT, (tWidget *)&g_sHeading);

    //
    // Initialize the status string.
    //
    UpdateStatus("Initializing...");

    //
    // Paint the widget tree to make sure they all appear on the display.
    //
    WidgetPaint(WIDGET_ROOT);

    //
    // Initialize the SimpliciTI BSP.
    //
    BSP_Init();

    //
    // Set the SimpliciTI device address using the current Ethernet MAC address
    // to ensure something like uniqueness.
    //
    bRetcode = SetSimpliciTIAddress();

    //
    // Did we have a problem with the address?
    //
    if(!bRetcode)
    {
        //
        // Yes - make sure the display is updated then hang the app.
        //
        WidgetMessageQueueProcess();
        while(1)
        {
            //
            // MAC address is not set so hang the app.
            //
        }
    }

    //
    // Turn on both our LEDs
    //
    SetLED(1, true);
    SetLED(2, true);

    UpdateStatus("Waiting...");

    //
    // Initialize the SimpliciTI stack but don't set any receive callback.
    //
    while(1)
    {
        eRetcode = SMPL_Init((uint8_t (*)(linkID_t))0);

        if(eRetcode == SMPL_SUCCESS)
        {
            break;
        }

        ToggleLED(1);
        ToggleLED(2);
        SPIN_ABOUT_A_SECOND;
    }

    // This code example changes the Link token to be distributed to those who
    // Join. For the example here this should be done before anyone joins so
    // the Join context is defaulted to OFF for this scenario. See the
    // smpl_config.dat file. After the link token is set the Join context must
    // be enabled.
    //
    // NOTE that this is done after initialization. For APs the init sequence
    // consists of a step in which a link token is generated. The sequence here
    // overrides that setting. It can be used to distribute different link
    // tokens to different devices. The sequence here is a simple example of
    // how to use the IOCTL interface to set the Link token for subsequent
    // Joiners.
    //
    // You might want to be careful about following this particular example if
    // you are restoring from NV unless you are setting a fixed value as is
    // done here.  Unconditionally setting a random value will make it
    // essentially impossible for newly joining devices to link to devices that
    // joined before the AP was reset since they will have different link
    // tokens.
    //
    eToken.tokenType       = TT_LINK;
    eToken.token.linkToken = 0x78563412;

    SMPL_Ioctl(IOCTL_OBJ_TOKEN, IOCTL_ACT_SET, &eToken);

    //
    // Enable join context.
    //
    SMPL_Ioctl(IOCTL_OBJ_AP_JOIN, IOCTL_ACT_ON, 0);

    //
    // Tell the user what's up.
    //
    UpdateStatus("Access point active.");

    //
    // Do nothing after this - the SimpliciTI stack code handles all the
    // access point function required.
    //
    while(1)
    {
        //
        // Process the widget message queue.
        //
        WidgetMessageQueueProcess();
    }
}
int main(void)
{
  CHIP_Init();

  // Enable clocks
  CMU_ClockEnable(cmuClock_EBI, true);
  CMU_ClockEnable(cmuClock_GPIO, true);

  CMU_HFRCOBandSet(cmuHFRCOBand_28MHz);

  /* Setup SysTick Timer for 1 msec interrupts  */
  if (SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 1000)) while (1) ;

  /* Configure board. Select either EBI or SPI mode. */
  BSP_Init(BSP_INIT_DK_SPI);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  // EBI config
  EBI_Init_TypeDef ebiConfig = EBI_INIT_DEFAULT;



  // Set EBI address pins PE[15:8]
  GPIO_PinModeSet(gpioPortE, 15, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortE, 14, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortE, 13, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortE, 12, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortE, 11, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortE, 10, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortE, 9, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortE, 8, gpioModePushPull, 0);

  // Set EBI data pins PA15 + PA[6:0]
  GPIO_PinModeSet(gpioPortA, 15, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortA, 6, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortA, 5, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortA, 4, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortA, 3, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortA, 2, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortA, 1, gpioModePushPull, 0);
  GPIO_PinModeSet(gpioPortA, 0, gpioModePushPull, 0);

  /* EBI ARDY/WEN/REN/ALE */
  GPIO_PinModeSet( gpioPortF,  2, gpioModeInput,    0 );
  GPIO_PinModeSet( gpioPortF,  8, gpioModePushPull, 0 );
  GPIO_PinModeSet( gpioPortF,  9, gpioModePushPull, 0 );
  GPIO_PinModeSet( gpioPortC, 11, gpioModePushPull, 0 );

  /* --------------------------------------------------------- */
  /* Second bank needs a name, Bank 0, Base Address 0x80000000 */
  /* --------------------------------------------------------- */
      ebiConfig.banks       = EBI_BANK0;
      ebiConfig.csLines     = EBI_CS1;
      ebiConfig.mode        = ebiModeD8A8;
      ebiConfig.alePolarity = ebiActiveHigh;
      ebiConfig.location    = ebiLocation1;
      /* keep blEnable */
      ebiConfig.blEnable     = false;
      ebiConfig.addrHalfALE  = false;
      ebiConfig.readPrefetch = false;
      ebiConfig.noIdle       = true;

      /* keep alow/ahigh configuration */
      ebiConfig.aLow = ebiALowA0;
      ebiConfig.aHigh = ebiAHighA18;

      /* Address Setup and hold time */
      ebiConfig.addrHoldCycles  = 3;
      ebiConfig.addrSetupCycles = 3;

      /* Read cycle times */
      ebiConfig.readStrobeCycles = 7;
      ebiConfig.readHoldCycles   = 3;
      ebiConfig.readSetupCycles  = 3;

      /* Write cycle times */
      ebiConfig.writeStrobeCycles = 7;
      ebiConfig.writeHoldCycles   = 3;
      ebiConfig.writeSetupCycles  = 3;

      /* Configure EBI bank 1 */
      EBI_Init(&ebiConfig);


  uint16_t *BANK0_BASE_ADDR = 0x80000000;
  uint16_t DATA = 0xF000;
  uint32_t cnt = 0;
		  *BANK0_BASE_ADDR = 0x1;
		  BSP_LedsSet(0xff00);
  while (1) {
	  //if(cnt > 500000){
		  *BANK0_BASE_ADDR = DATA;
		  BSP_LedsSet(DATA);
		  Delay(500);
	  //}else{
		  *BANK0_BASE_ADDR = 0x0000;
		  BSP_LedsSet(0x0000);
	  //}
		  Delay(500);
	  //if(cnt>1000000)
	//	  cnt=0;
	  //cnt++;

  }
}
Beispiel #8
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  bool     redraw = false;
  bool     prevRedraw = false;
  EMSTATUS status;
  volatile int i;

  /* Chip revision alignment and errata fixes */
  CHIP_Init();

  /* Initialize DVK board register access */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Initialize DVK interrupt enable */
  DVK_IRQInit();

  /* Initialize GPIO interrupt */
  GPIO_IRQInit();

  /* Clear LEDs */
  BSP_LedsSet(0x0000);

  setupSWO();

  /* Wait until we have control over display */
  while(!redraw)
  {
    redraw = TFT_AddressMappedInit();
  }

  /* Init graphics context - abort on failure */
  status = GLIB_contextInit(&gc);
  if (status != GLIB_OK) while (1) ;

  /* Update TFT display forever */
  while (1)
  {
    /* Check if we should control TFT display instead of AEM/board controller */
    redraw = TFT_AddressMappedInit();
    if(redraw)
    {
      /* This indicated a BC -> EFM control transfer */
      if(prevRedraw != redraw)
      {
        /* Update information message */
        gc.foregroundColor = GLIB_rgbColor(200, 200, 200);
        gc.backgroundColor = GLIB_rgbColor(0, 0, 0);
        GLIB_drawString(&gc, description[0], strlen(description[0]), 0, 0, 1);
        GLIB_drawString(&gc, description[1], strlen(description[1]), 0, 8, 1);
        GLIB_drawString(&gc, description[2], strlen(description[2]), 0, 24, 1);
        GLIB_drawString(&gc, description[3], strlen(description[3]), 0, 40, 1);
        GLIB_drawString(&gc, description[4], strlen(description[4]), 0, 48, 1);
        GLIB_drawString(&gc, description[5], strlen(description[5]), 0, 64, 1);
        GLIB_drawString(&gc, description[6], strlen(description[6]), 0, 72, 1);
        gc.foregroundColor = GLIB_rgbColor(200, 200, 100);
        GLIB_drawString(&gc, description[7], strlen(description[7]), 0, 88, 1);
        GLIB_drawString(&gc, description[8], strlen(description[8]), 0, 104, 1);
      }
      /* Update selected demo  */
      gc.foregroundColor = GLIB_rgbColor(100, 200, 100);
      gc.backgroundColor = GLIB_rgbColor(50, 50, 50);
      GLIB_drawString(&gc, eModeDesc[eModeDemo], strlen(eModeDesc[eModeDemo]), 40, 150, 1);
    }
    else
    {
      /* No need to refresh display when BC is active */
    }
    prevRedraw = redraw;
    if(runDemo)
    {
      gc.foregroundColor = GLIB_rgbColor(50, 50, 50);
      gc.backgroundColor = GLIB_rgbColor(100, 200, 100);
      GLIB_drawString(&gc, eModeDesc[eModeDemo], strlen(eModeDesc[eModeDemo]), 40, 150, 1);
      for(i=0; i<14000; i++) ;
      break;
    }
  }

  /* Run demo */
  switch(eModeDemo)
  {
  case 0:
    Demo_Primes(cmuSelect_HFXO, (CMU_HFRCOBand_TypeDef) 0);
    break;
  case 1:
    Demo_EM1(cmuSelect_HFXO, (CMU_HFRCOBand_TypeDef) 0);
    break;
  case 2:
    Demo_Primes(cmuSelect_HFRCO, cmuHFRCOBand_14MHz);
    break;
  case 3:
    Demo_EM1(cmuSelect_HFRCO, cmuHFRCOBand_14MHz);
    break;
  case 4:
    Demo_EM2();
    break;
  case 5:
    Demo_EM2_RTC();
    break;
  case 6:
    Demo_EM3();
    break;
  case 7:
    Demo_EM3_GPIO();
    break;
  case 8:
    Demo_EM4();
    break;
  default:
    while(1);
  }
  return 0;
}
Beispiel #9
0
/*------------------------------------------------------------------------------------------------*/
int main(void)
{
	Bool_e NouveauMode;
	Horodatage_s Time = {
			.Heure = 0,
			.Minute = 0,
			.Seconde = 0,
	};


	// ------------------------------------------------------------------------
	// --- INIT DU SYSTEME
	// --- Initialisations uC, Peripheriques, Fonctions et Interfaces
	BSP_Init();									// Init carte
	SysTick_Config(SystemCoreClock / 1000);		// Init Tick 1ms
	HAL_Console_Init(115200);
	RTC_StartInit(TRUE);						// Start Init RTC
	I2C1_Init(100 * 1000);						// 100kHz
	ADC1_Init();

	_CONSOLE(0, "\n");
	_CONSOLE(LogId, "--- START - ALJ%s ---\n", VERSION_SW);

	//AM23xx_Test();

	REGLAGE_RTC();

	//----------------------------------
	// FONCTIONNALITES
	MemoireFAT_Init((Diskio_drvTypeDef*) &SdCard_SPI_Driver);
	#if USE_TEMP_HYGRO
		TempHygro_Init(TEMPERATURE_PERIODE_ACQUISITION_ms);
	#endif
	Delay_ms(50);

//	Hygrometre_Init();
	ConfIni_Init();
	Arrosage_Init(USE_CONF_INI_FILE);
	Chauffage_Init(USE_CONF_INI_FILE);
	Ventilation_Init(USE_CONF_INI_FILE);
	Logs_Init();

	PC_Init();
	Terminal_Init();
	Terminal_Cmd_Init();

	//_CONSOLE(LogId, "MODE_FCT_SERVEUR\n");
	ModeFct = MODE_FCT_SERVEUR;
	//MemoireFAT_PrintFileList("httpserver");
	Ethernet_Init(USE_CONF_INI_FILE);

	if (RTC_BkpRegister_Read(0) != 0)
	{
		_CONSOLE(LogId, "MODE_FCT_USB\n");
		ModeFct = MODE_FCT_USB;
		//USB_Init((Diskio_drvTypeDef*) &SdCard_SPI_Driver);
		RTC_BkpRegister_Write(0, 0);
	}

	// Lancement des timers
	TSW_Start(&TmrAffichTempHygro, 3000);


	//Mode_Test();

	WDG_InitWWDG(10000);

	while (RTC_Main() != RTC_ETAPE_READY);
	TSW_Start(&Tmr_RTC, 10000);
	RTC_Lire(&StartTime);
	RTC_Lire(&Time);


	//--------------------------------------------------------------------------------
	_CONSOLE(LogId, "--------------------------\n");
	_CONSOLE(LogId, "StartupTime=%dms\n", TSW_GetTimestamp_ms());
	_CONSOLE(LogId, "--------------------------\n\n");
		while(1)
	{
		WDG_Refresh();

//		if (PC_Read((uint8_t*) BufferIn, NULL) == TRUE)
//		{
//			Terminal_Parser(BufferIn, BufferOut, 1024);
//			if (strlen(BufferOut) > 0)
//				PC_Write(BufferOut, strlen(BufferOut));
//		}

		// Choix du mode de fonctionnement
		// WKUP = ACTIF -> USB  -  WKUP = INACTIF -> WebServer
		//if (GPIO_Get(PORT_WKUP) == Etat_ACTIF)
		//{
		//	RTC_BkpRegister_Write(0, 1);
		//	while (GPIO_Get(PORT_WKUP) == Etat_ACTIF)
		//		TSW_Delay(100);
		//	GOTO(0);
		//}

		//----------------------------------
		// PROCESSUS
		LifeBit_Main();
		MemoireFAT_Main();
		#if USE_TEMP_HYGRO
			TempHygro_Thread();
		#endif

		if (Mode != MODE_DEMARRAGE)
		{
			Arrosage_Management();
			Chauffage_Management();
			Ventilation_Management();
			Hygrometrie_Management();
		}

		if (ModeFct == MODE_FCT_SERVEUR)
		{
			Ethernet_Management();
		}

		Logs_Management();


		//----------------------------------
		// LECTURE TEMPERATURE
		if ((TempHygro_IsValide() == FALSE)
		&&	(Mode != MODE_DEMARRAGE))
		{
			Mode = MODE_DEFAUT;
		}
		else
		{
			Temperature = TempHygro_GetTemperature();
			Hygrometrie = TempHygro_GetHygrometrie();
		}

		//----------------------------------
		// RTC
		if (TSW_IsFinished(&Tmr_RTC))
		{
			RTC_Lire(&Time);
			TSW_ReStart(&Tmr_RTC);

			//_CONSOLE(LogId, "RTC = %d-%02d-%02d %02d:%02d:%02d;%08d;",
			//				Time.Annee, Time.Mois, Time.Jour,
			//				Time.Heure, Time.Minute, Time.Seconde,
			//				TSW_GetTimestamp_ms());
		}


		//----------------------------------
		// AFFICHAGE TEMPERATURE
/*		if (TSW_IsRunning(&TmrAffichTempHygro) == FALSE)
		{
			_CONSOLE(LogId, "TempHygro = ");
			if (TempHygro_IsValide() == FALSE)
				_CONSOLE(LogId, "Non valide\n");
			else
			{
				_CONSOLE(LogId, "%.01f %c\t%.01f %c\n",
						Temperature, '°',
						Hygrometrie, '%');
			}

			TSW_Start(&TmrAffichTempHygro, 2500);
		}
*/


		//----------------------------------
		// GESTION DES MODES
		NouveauMode = FALSE;
		if (LastMode != Mode)
		{
			LastMode = Mode;
			NouveauMode = TRUE;
		}

		switch (Mode)
		{
			//--------------------------------------------------------------
			case MODE_DEMARRAGE :

				if (NouveauMode)
				{
					_CONSOLE(LogId, "----- MODE_DEMARRAGE -----\n");
					Logs_Data();
				}

				if (Mode_Demarrage() == Status_Fini)
				{
					Mode = MODE_SURVEILLANCE;
				}

				break;


			//--------------------------------------------------------------
			case MODE_SURVEILLANCE :

				if (NouveauMode)
				{
					_CONSOLE(LogId, "----- MODE_SURVEILLANCE -----\n");
					Logs_Data();

					GPIO_Set(PORT_IHM_LED1, Etat_ACTIF);
					GPIO_Set(PORT_IHM_LED2, Etat_INACTIF);
					GPIO_Set(PORT_IHM_LED3, Etat_INACTIF);

					EtatVentillation	= Etat_INACTIF;
					EtatChauffage		= Etat_INACTIF;

					TSW_Start(&Tmr_ATTENTE, 1000 * 30); // On reste au moins 30sec en mode attente
				}

				if (TSW_IsRunning(&Tmr_ATTENTE) == TRUE)
				{
					break;
				}

				// Pas de chauffage dessuite après l'extraction
				if ((TSW_IsRunning(&Tmr_EXT) == FALSE)
				&&	(Temperature < Chauffage_Get()->Cfg_SeuilStart_DegC))
				{
					Mode = MODE_CHAUFFAGE;
				}

				// Pas d'extraction dessuite après le chauffage
				if ((TSW_IsRunning(&Tmr_CH) == FALSE)
				&&	(Temperature >= Ventilation_Get()->Cfg_SeuilStart_DegC))
				{
					Mode = MODE_VENTILLATION;
				}

				break;


			//--------------------------------------------------------------
			case MODE_CHAUFFAGE :

				if (NouveauMode)
				{
					_CONSOLE(LogId, "----- MODE_CHAUFFAGE -----\n");
					Logs_Data();

					GPIO_Set(PORT_IHM_LED1, Etat_INACTIF);
					GPIO_Set(PORT_IHM_LED2, Etat_ACTIF);
					GPIO_Set(PORT_IHM_LED3, Etat_INACTIF);

					if (Ventilation_Get()->Cfg_ActiverPendantChauffage)
						EtatVentillation = Etat_ACTIF;
					else
						EtatVentillation = Etat_INACTIF;
					EtatChauffage = Etat_ACTIF;
				}

				// Attente franchissement seuil
			if (Temperature >= Chauffage_Get()->Cfg_SeuilStop_DegC)
				{
					EtatChauffage = Etat_INACTIF;

					TSW_Start(&Tmr_CH, 1000 * Chauffage_Get()->Cfg_TempoApresCh_s);
					Mode = MODE_SURVEILLANCE;
				}

				break;

			//--------------------------------------------------------------
			case MODE_VENTILLATION :

				if (NouveauMode)
				{
					_CONSOLE(LogId, "----- MODE_VENTILLATION -----\n");
					Logs_Data();

					GPIO_Set(PORT_IHM_LED1, Etat_ACTIF);
					GPIO_Set(PORT_IHM_LED2, Etat_ACTIF);
					GPIO_Set(PORT_IHM_LED3, Etat_INACTIF);

					EtatChauffage = Etat_INACTIF;
					EtatVentillation = Etat_ACTIF;
				}

				if (Temperature < Ventilation_Get()->Cfg_SeuilStop_DegC)
				{
					EtatVentillation = Etat_INACTIF;

					TSW_Start(&Tmr_EXT, 1000 * Ventilation_Get()->Cfg_TempoApresEXT_s);
					Mode = MODE_SURVEILLANCE;
				}

				break;

			//--------------------------------------------------------------
			case MODE_DEFAUT :

				if (NouveauMode)
				{
					_CONSOLE(LogId, "----- MODE_DEFAUT -----\n");
					Logs_Data();

					GPIO_Set(PORT_IHM_LED1, Etat_INACTIF);
					GPIO_Set(PORT_IHM_LED2, Etat_INACTIF);
					GPIO_Set(PORT_IHM_LED3, Etat_ACTIF);

					EtatVentillation 	= Etat_INACTIF;
					EtatChauffage		= Etat_INACTIF;
					//Arrosage_Stop();

					TSW_Start(&Tmr_DEFAULT, 60 * 1000);
					TSW_Start(&Tmr_DEFAULT_Max, 600 * 1000);
				}

				if (TempHygro_IsValide() == TRUE)
				{
					Mode = MODE_VENTILLATION;
					break;
				}

				if ((TSW_IsRunning(&Tmr_DEFAULT) == FALSE)
				&&	(REBOOT_ON_DEFAULT_MODE == TRUE)
				&&	(Arrosage_IsActive() == FALSE))
				{
					if ((Telnet_GetNbActiveConnection() == 0)
					||	(TSW_IsRunning(&Tmr_DEFAULT_Max) == FALSE))
					{
						_CONSOLE(LogId, "REBOOT...\n");
						MemoireFAT_DeInit();
						TSW_Delay(5000);
						GOTO(0);
						Mode = MODE_DEMARRAGE;
					}
				}
				break;

		}

		//----------------------------------
		// MAJ DES SORTIES
		if (GPIO_Get(PORT_RELAIS_V_EXT) != EtatVentillation)
		{
			_CONSOLE(LogId, "Ventillation = %d\n", EtatVentillation);
			GPIO_Set(PORT_RELAIS_V_EXT, EtatVentillation);
			Logs_Data();
		}
		if (GPIO_Get(PORT_RELAIS_CH) != EtatChauffage)
		{
			_CONSOLE(LogId, "Chauffage = %d\n", EtatChauffage);
			GPIO_Set(PORT_RELAIS_CH, EtatChauffage);
			Logs_Data();
		}
	}

	return 0;

}


/*------------------------------------------------------------------------------------------------*/
extern void SdCard_SPI_timerproc (void);

void ApplicationTickHook (void) {

	static uint8_t ucTick_10ms=0;
	static uint8_t ucTick_100ms=0;


	/* Gestion du Tick Timer Software */
	TSW_Refresh();

	/* Tick 10ms */
	ucTick_10ms++;
	if (ucTick_10ms >= 10){
		ucTick_10ms = 0;
		ADC1_Tick();
		SdCard_SPI_timerproc();
	}

	/* Tick 100ms */
	ucTick_100ms++;
	if (ucTick_100ms >= 10){
		ucTick_100ms = 0;

	}
}


/*------------------------------------------------------------------------------------------------*/
void Delay(uint32_t nCount)
{
  /* Capture the current local time */
  uint32_t timingdelay = TSW_GetTimestamp_ms() + nCount;

  /* wait until the desired delay finish */
  while(timingdelay > TSW_GetTimestamp_ms())
  {
  }
}
Beispiel #10
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  int value, delayCount = 0, hfrcoband = 0;
  float current, voltage;
  bool vboost;
  char buffer[8];

  /* Chip errata */
  CHIP_Init();

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Initialize board support package */
  BSP_Init(BSP_INIT_BCC);

  /* Setup SysTick Timer for 1 msec interrupts  */
  if (SysTick_Config(SystemCoreClockGet() / 1000)) while (1) ;

  /* Initialize voltage comparator, to check supply voltage */
  VDDCHECK_Init();

  /* Check if voltage is below 3V, if so use voltage boost */
  if (VDDCHECK_LowVoltage(2.9))
  {
    vboost = true;
  }
  else
  {
    vboost = false;
  }

  /* Disable Voltage Comparator */
  VDDCHECK_Disable();

  /* Initialize segment LCD */
  SegmentLCD_Init(vboost);
  SegmentLCD_Symbol(LCD_SYMBOL_MICROAMP, 1);

  /* Infinite loop */
  while (1)
  {
    /* Read and display current */
    current = BSP_CurrentGet();
    value = (int) (1000 * current);

    /* Check that we fall within displayable value */
    if ( (value>0) && (value<10000) )
    {
      SegmentLCD_Number(value);
    }
    else
    {
      SegmentLCD_Number(-1);
    }

    /* Alternate between voltage and clock frequency */
    if ( ((delayCount / 10) & 1) == 0 )
    {
      voltage = BSP_VoltageGet();
      value = (int) (voltage * 100);
      SegmentLCD_Symbol(LCD_SYMBOL_DP6, 1);
      sprintf(buffer, "Volt%3d", value);
      SegmentLCD_Write(buffer);
    } else {
      SegmentLCD_Symbol(LCD_SYMBOL_DP6, 0);
      sprintf(buffer, "%3u MHz", (int) (SystemCoreClockGet()/1000000));
      SegmentLCD_Write(buffer);
    }

    /* After 5 seconds, use another HFRCO band */
    if ( delayCount % 50 == 0 )
    {
      switch( hfrcoband )
      {
      case 0:
        CMU_HFRCOBandSet(cmuHFRCOBand_11MHz);
        break;
      case 1:
        CMU_HFRCOBandSet(cmuHFRCOBand_14MHz);
        break;
      case 2:
        CMU_HFRCOBandSet(cmuHFRCOBand_21MHz);
        break;
      default:
        CMU_HFRCOBandSet(cmuHFRCOBand_28MHz);
        /* Restart iteartion */
        hfrcoband = -1;
        break;
      }
      hfrcoband++;
      /* Recalculate delay tick count and baudrate generation */
      if (SysTick_Config(SystemCoreClockGet() / 1000)) while (1) ;
      BSP_Init(BSP_INIT_BCC);
    }
    Delay(100);
    delayCount++;
  }
}
void main (void)
{
  ioctlScanChan_t scan;
  freqEntry_t     freq[NWK_FREQ_TBL_SIZE];
  uint8_t         firstTimeThru = 1;

  BSP_Init();

  /* Keep trying to join (a side effect of successful initialization) until
   * successful. Toggle LEDS to indicate that joining has not occurred.
   */
  while (SMPL_SUCCESS != SMPL_Init(0))
  {
    toggleLED(1);
    toggleLED(2);
    SPIN_ABOUT_A_SECOND;
  }

  scan.freq = freq;
  while (1)
  {
    SPIN_ABOUT_A_QUARTER_SECOND;

    SMPL_Ioctl(IOCTL_OBJ_FREQ, IOCTL_ACT_SCAN, &scan);
    if (1 == scan.numChan)
    {
      if (firstTimeThru)
      {
        BSP_TURN_OFF_LED1();
        BSP_TURN_ON_LED2();
        {
          uint8_t i=15;

          while (i--)
          {
            toggleLED(1);
            toggleLED(2);
            SPIN_ABOUT_A_QUARTER_SECOND;
          }
        }
        firstTimeThru = 0;
      }
      switch(freq[0].logicalChan)
      {
        case 0:
          /* GREEN OFF */
          /* RED   OFF */
          BSP_TURN_OFF_LED1();
          BSP_TURN_OFF_LED2();
          break;

        case 1:
          /* GREEN OFF */
          /* RED   ON */
          BSP_TURN_OFF_LED1();
          BSP_TURN_ON_LED2();
          break;

        case 2:
          /* GREEN ON */
          /* RED   OFF */
          BSP_TURN_ON_LED1();
          BSP_TURN_OFF_LED2();
          break;

        case 3:
          /* GREEN ON */
          /* RED   ON */
          BSP_TURN_ON_LED1();
          BSP_TURN_ON_LED2();
          break;

        case 4:
          /* blink them both... */
          BSP_TURN_OFF_LED1();
          BSP_TURN_OFF_LED2();
          SPIN_ABOUT_A_QUARTER_SECOND;
          BSP_TURN_ON_LED1();
          BSP_TURN_ON_LED2();
          SPIN_ABOUT_A_QUARTER_SECOND;
          BSP_TURN_OFF_LED1();
          BSP_TURN_OFF_LED2();
      }
    }
  }
}
void main (void)
{
  addr_t lAddr;
  bspIState_t intState;
  char *Flash_Addr;                         // Initialize radio address location
  Flash_Addr = (char *)0x10F0;

  WDTCTL = WDTPW + WDTHOLD;                 // Stop WDT
  // delay loop to ensure proper startup before SimpliciTI increases DCO
  // This is typically tailored to the power supply used, and in this case
  // is overkill for safety due to wide distribution.
  __delay_cycles(65000);

  if( CALBC1_8MHZ == 0xFF && CALDCO_8MHZ == 0xFF )// Do not run if cal values
  {
    P1DIR |= 0x03;
    BSP_TURN_ON_LED1();
    BSP_TURN_OFF_LED2();
    while(1)
    {
      __delay_cycles(65000);
      BSP_TOGGLE_LED2();
      BSP_TOGGLE_LED1();
    }
  }

  BSP_Init();

  if( Flash_Addr[0] == 0xFF &&
      Flash_Addr[1] == 0xFF &&
      Flash_Addr[2] == 0xFF &&
      Flash_Addr[3] == 0xFF )
    {
      createRandomAddress();                // Create Random device address at
    }                                       // initial startup if missing
  lAddr.addr[0]=Flash_Addr[0];
  lAddr.addr[1]=Flash_Addr[1];
  lAddr.addr[2]=Flash_Addr[2];
  lAddr.addr[3]=Flash_Addr[3];

  //SMPL_Init();
  SMPL_Ioctl(IOCTL_OBJ_ADDR, IOCTL_ACT_SET, &lAddr);

  MCU_Init();
  //Transmit splash screen and network init notification
  TXString( (char*)splash, sizeof splash);
  TXString( "\r\nInitializing Network....", 26 );

  SMPL_Init(sCB);

  // network initialized
  TXString( "Done\r\n", 6);

  // main work loop
  while(1)
  {
    // Wait for the Join semaphore to be set by the receipt of a Join frame from a
    // device that supports and End Device.

    if (sJoinSem && (sNumCurrentPeers < NUM_CONNECTIONS))
    {
      // listen for a new connection
      SMPL_LinkListen(&sLID[sNumCurrentPeers]);
      sNumCurrentPeers++;
      BSP_ENTER_CRITICAL_SECTION(intState);
      if (sJoinSem)
      {
        sJoinSem--;
      }
      BSP_EXIT_CRITICAL_SECTION(intState);
    }

    // if it is time to measure our own temperature...
    if(sSelfMeasureSem)
    {
//    	TXString("\r\n...", 5);
      BSP_TOGGLE_LED1();
      sSelfMeasureSem = 0;
    }

    // Have we received a frame on one of the ED connections?
    // No critical section -- it doesn't really matter much if we miss a poll
    if (sPeerFrameSem)
    {
    	  uint8_t  msg[MESSAGE_LENGTH], len, i;

      // process all frames waiting
      for (i=0; i<sNumCurrentPeers; ++i)
      {
        if (SMPL_Receive(sLID[i], msg, &len) == SMPL_SUCCESS)
        {
          ioctlRadioSiginfo_t sigInfo;
          sigInfo.lid = sLID[i];
          SMPL_Ioctl(IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_SIGINFO, (void *)&sigInfo);
          transmitData( i, (signed char)sigInfo.sigInfo.rssi, (char*)msg );
          BSP_TURN_ON_LED2();               // Toggle LED2 when received packet
          BSP_ENTER_CRITICAL_SECTION(intState);
          sPeerFrameSem--;
          BSP_EXIT_CRITICAL_SECTION(intState);
          __delay_cycles(10000);
          BSP_TURN_OFF_LED2();
        }
      }
    }
  }
}
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
#ifdef GG_STK
  uint32_t mode = 0;
#else
  /* Initialize DK board register access, necessary if run on DK */
  BSP_Init(BSP_INIT_DEFAULT);
  BSP_PeripheralAccess(BSP_AUDIO_OUT, true);
#endif
  
  /* Initialize peripherals */
  initClock();
  initDma();
  initDac();
  initDacDma();
  initTimer();
#ifdef GG_STK
  initGpio();
#endif

  while(1)
  {
/*** Operation for EFM32GG-DK3750 ***/    
#ifndef GG_STK
    /* Wait key press */
    while(!BSP_PushButtonsGet())
      ;
    if (BSP_PushButtonsGet() == BC_UIF_PB1)
    {
      BSP_LedsSet(0x0001);
      /* Wait key release */
      while(BSP_PushButtonsGet()!=0);
      /* Start play files */      
      playList[0].frameStart = (char *)voice8k;
      playList[1].frameStart = NULL;
      playList[0].frameNum = sizeof(voice8k)/FRAME_SIZE_8K;
      speexPlayBack(0, NARROWBAND, FRAME_SIZE_8K, &playList[0]);
      BSP_LedsSet(0x0000);
    }
    if (BSP_PushButtonsGet() == BC_UIF_PB2)
    {    
      BSP_LedsSet(0x0002);
      /* Wait key release */
      while(BSP_PushButtonsGet()!=0);
      /* Start play files */      
      playList[0].frameStart = (char *)voice11k;
      playList[1].frameStart = NULL;
      playList[0].frameNum = sizeof(voice11k)/FRAME_SIZE_11K;
      speexPlayBack(0, NARROWBAND, FRAME_SIZE_11K, &playList[0]);
      BSP_LedsSet(0x0000);
    }
    if (BSP_PushButtonsGet() == BC_UIF_PB3)
    {
      BSP_LedsSet(0x0004);
      /* Wait key release */
      while(BSP_PushButtonsGet()!=0);
      /* Start play files */      
      playList[0].frameStart = (char *)voice15k;
      playList[1].frameStart = NULL;
      playList[0].frameNum = sizeof(voice15k)/FRAME_SIZE_15K;
      speexPlayBack(0, NARROWBAND, FRAME_SIZE_15K, &playList[0]);
      BSP_LedsSet(0x0000);
    }
    if (BSP_PushButtonsGet() == BC_UIF_PB4)
    {    
      BSP_LedsSet(0x0008);
      /* Wait key release */
      while(BSP_PushButtonsGet()!=0);
      /* Start play files */      
      playList[0].frameStart = (char *)voice18k2;
      playList[1].frameStart = NULL;
      playList[0].frameNum = sizeof(voice18k2)/FRAME_SIZE_18K2;
      speexPlayBack(0, NARROWBAND, FRAME_SIZE_18K2, &playList[0]);
      BSP_LedsSet(0x0000);
    }

/*** Operation for EFM32GG-STK3750 ***/        
#else
    /* Wait key press */
    EMU_EnterEM1();

    switch (keyCheck())
    {
    case 1:
      mode++;
      if (mode == 4)
      {
        mode = 0;
      }
      GPIO_PortOutSetVal(gpioPortE, (mode << 2), 0x000c);
      break;
      
    case 2:
      if (mode == 0x00)
      {
        /* Start play files */      
        playList[0].frameStart = (char *)voice8k;
        playList[1].frameStart = NULL;
        playList[0].frameNum = sizeof(voice8k)/FRAME_SIZE_8K;
        speexPlayBack(0, NARROWBAND, FRAME_SIZE_8K, &playList[0]);
      }
      else if (mode == 0x01)
      {
        /* Start play files */      
        playList[0].frameStart = (char *)voice11k;
        playList[1].frameStart = NULL;
        playList[0].frameNum = sizeof(voice11k)/FRAME_SIZE_11K;
        speexPlayBack(0, NARROWBAND, FRAME_SIZE_11K, &playList[0]);
      }
      else if (mode == 0x02)
      {
        /* Start play files */      
        playList[0].frameStart = (char *)voice15k;
        playList[1].frameStart = NULL;
        playList[0].frameNum = sizeof(voice15k)/FRAME_SIZE_15K;
        speexPlayBack(0, NARROWBAND, FRAME_SIZE_15K, &playList[0]);
      }
      else
      {
        /* Start play files */      
        playList[0].frameStart = (char *)voice18k2;
        playList[1].frameStart = NULL;
        playList[0].frameNum = sizeof(voice18k2)/FRAME_SIZE_18K2;
        speexPlayBack(0, NARROWBAND, FRAME_SIZE_18K2, &playList[0]);
      }
      break;
      
    default:
      break;
    }    
#endif
  }
}
Beispiel #14
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  int c;
  MPU_RegionInit_TypeDef flashInit       = MPU_INIT_FLASH_DEFAULT;
  MPU_RegionInit_TypeDef sramInit        = MPU_INIT_SRAM_DEFAULT;
  MPU_RegionInit_TypeDef peripheralInit  = MPU_INIT_PERIPHERAL_DEFAULT;

  /* Chip revision alignment and errata fixes */
  CHIP_Init();

  /* Initialize DVK board register access */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Enable printf on RS232 port - this example only supports LEUART */
  RETARGET_SerialInit();
  RETARGET_SerialCrLf(1);

  printf("\nEFM32 MPU access violation example.\n"
           "Hit lowercase 'x' to force access violations.\n");

  MPU_Disable();

  /* Flash memory */
  MPU_ConfigureRegion( &flashInit );

  /* SRAM */
  MPU_ConfigureRegion( &sramInit );

  /* SRAM, a 4k part with priviledged only access, this regions settings  */
  /* will override those of the previous region                           */
  sramInit.regionNo         = 2;
  sramInit.baseAddress      = RAM_MEM_BASE + 0x2000;
  sramInit.size             = mpuRegionSize4Kb;
  sramInit.accessPermission = mpuRegionApPRw;
  MPU_ConfigureRegion( &sramInit );

  /* LEUART, priviledged only access */
  peripheralInit.regionNo         = 3;
  peripheralInit.baseAddress      = LEUART1_BASE;
  peripheralInit.size             = mpuRegionSize128b;
  peripheralInit.accessPermission = mpuRegionApPRw;
  MPU_ConfigureRegion( &peripheralInit );

  MPU_Enable( MPU_CTRL_PRIVDEFENA ); /* Full access to default memory map */
                                     /* in priviledged state              */

  while (1)
  {
    EMU_EnterEM2(true);

    /* Retrieve new character */
    c = getchar();
    if (c > 0)
    {
      if ( c == 'x' )
      {
        /* Generate an access violation in LEUART1 peripheral     */
        __set_CONTROL( 1 );   /* Enter User (unpriviledged) state */
        putchar( c );

        /* MemManage_Handler() will set back to priviledged state */

        /* Generate an access violation in internal SRAM          */
        __set_CONTROL( 1 );   /* Enter User (unpriviledged) state */
        *(volatile uint32_t *)(RAM_MEM_BASE + 0x2000) = 1;

        /* MemManage_Handler() will set back to priviledged state */
      }
    else
      {
      /* Echo character */
      putchar(c);
      }
    }

    /* Most terminals issue CR when pressing enter, add LF */
    if (c == '\r')
    {
      putchar('\n');
    }
  }
}
Beispiel #15
0
/*
*********************************************************************************************************
*                                          AppTaskStart()
*
* Description : The startup task. The uC/OS-III ticker should only be initialize once multitasking starts.
*
* Argument(s) : p_arg       Argument passed to 'AppTaskStart()' by 'OSTaskCreate()'.
*
* Return(s)   : none.
*
* Note(s)     : (1) The first line of code is used to prevent a compiler warning because 'p_arg' is not
*                   used.  The compiler should not generate any code for this statement.
*
*               (2) Interrupts are enabled once the task starts because the I-bit of the CCR register was
*                   set to 0 by 'OSTaskCreate()'.
*********************************************************************************************************
*/
static void App_TaskStart(void *p_arg)
{
  uint16_t osVersion1, osVersion2, osVersion3;

  OS_ERR err = OS_ERR_NONE;

  (void)p_arg; /* Note(1) */

  /* Use 48MHZ HFXO as core clock frequency */
  CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);

  /* Initialize DK board register access */
  /* This demo currently only works in EBI mode */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Initialize the uC/OS-III ticker                       */
  OS_CPU_SysTickInit(CMU_ClockFreqGet(cmuClock_CORE) / OS_CFG_TICK_RATE_HZ);

#if (OS_TASK_STAT_EN > 0U)
  /* Determine CPU capacity                               */
  OSStatInit();
#endif

  /* Create application tasks                             */
  App_TaskCreate();

  /* Create application mailboxes                         */
  App_MailboxCreate();

  UART1_SerialInit();
  UART1_SerialCrLf(1);

  /* Initialize tft serial                                */
  RETARGET_SerialInit();

  osVersion3 = OSVersion( &err );
  osVersion1 = osVersion3 / 10000;
  osVersion3 -= osVersion1 * 10000;
  osVersion2 = osVersion3 / 100;
  osVersion3 -= osVersion2 * 100;
  osVersion3 %= 100;

  printf("\n*************************************");
  printf("\n    uC/OS-III v%d.%02d.%02d on EFM32 DK   ",
         osVersion1, osVersion2, osVersion3 );
  printf("\n           Demo Application   \n");
  printf("\n              uC/OS-III        ");
  printf("\n      \"The real time kernel\" ");
  printf("\n           www.micrium.com      ");
  printf("\n            is running on      ");
  printf("\n          Energy Micro EFM32   ");
  printf("\n         www.energymicro.com   \n");
  printf("\nDescription:");
  printf("\n\nTask1: LED blink task");
  printf("\n\nTask2: Receives characters from serial and posts message to Task3");
  printf("\n\nTask3: Receives message from Task2 and writes it on screen");
  printf("\n\n**************************************\n");
  printf("\nStart typing...\n");

  /* Suspend this task as it is only used once in one Reset cycle */
  OSTaskSuspend(&AppTaskStartTCB, &err);

  /* Error had occured if code execution reached this point as suspend calls the scheduler
   * that performs a context switch */
  while (1U) ;
}
Beispiel #16
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  int c;
  int index;

  /* Initialize DK board register access */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Initialize USART and map LF to CRLF */
  RETARGET_SerialInit();
  RETARGET_SerialCrLf(1);

#ifdef RETARGET_LEUART1
  printf("\nEFM32WG_DK3850 LEUART1 example\n");
#else
  printf("\nEFM32WG_DK3850 UART1 example\n");
#endif
  for (index = 0; index < ECHOBUFSIZE; index++)
  {
    echoBuffer[index] = (char) 'a' + index;
  }

  /* Retrieve characters, print local echo and full line back */
  index = 0;
  while (1)
  {
    /* Retrieve new character */
    c = getchar();
    if (c > 0)
    {
      /* Output character - most terminals use CRLF */
      if (c == '\r')
      {
        echoBuffer[index] = '\0';
        /* Output entire line */
        printf("\n%s\n", echoBuffer);
        index = 0;
      }
      else
      {
        /* Filter non-printable characters */
        if ((c < ' ') || (c > '~'))
          continue;

        /* Enter into buffer */
        echoBuffer[index] = c;
        index++;
        if (index == ECHOBUFSIZE)
        {
          /* Flush buffer */
          index = 0;
        }
        /* Local echo */
        putchar(c);
      }
    }
    else
    {
      #ifdef RETARGET_LEUART1
        /* Enter EM2 when idle */
        EMU_EnterEM2(true);
      #else
        /* Enter EM1 when idle */
        EMU_EnterEM1();
      #endif
    }
  }
}
Beispiel #17
0
void  *Thread_Startup (void *p_arg)
{
	int i;
	unsigned int uival;
	uint8_t userInput = 0;
    struct termios2 opt;
    struct timespec timeout;
    struct mac_mrf24j40_open_param	rf_mac_init;
    struct mac_mrf24j40	rf_mac;

    BSP_Init();                                                 /* Initialize BSP functions                             */
    CPU_Init();                                                 /* Initialize the uC/CPU services                       */

    driver_probe();
    board_register_devices();

    g_fd_led[0] = open_dev("led-green", 0);
    g_fd_led[1] = open_dev("led-red", 	0);
    g_fd_led[2] = open_dev("led-blue", 0);
    g_fd_led[3] = open_dev("led-orange", 0);

    g_fd_button = open_dev("button", 	0);
    // open usart
    g_fd_debug = open_dev("usart-1", O_RDWR);
    if(g_fd_debug >= 0){
        // configure
        ioctl(g_fd_debug, TCGETS2, (unsigned int)&opt);
        opt.c_cc[VMIN]  = 1;
        opt.c_cc[VTIME] = 100;
        opt.c_ispeed = 115200;
        opt.c_ospeed = 115200;
        opt.c_cflag &= ~CBAUD;
        opt.c_cflag |= BOTHER;
        /*     no parity
            1 stop bit
            8 bit data
         */
        opt.c_cflag &= ~CSIZE;
        opt.c_cflag |= CS8;
        opt.c_cflag &= ~CSTOPB;
        opt.c_cflag &= ~PARENB;
        opt.c_iflag &= ~INPCK;

        //opt.c_cflag &= ~CRTSCTS;             // disable hardware flow control CTS/ RTS*/
        opt.c_cflag |= (CLOCAL | CREAD);    // ignore modem controls, enable reading
        opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // raw input
        opt.c_oflag &= ~(OPOST|ONLCR|OCRNL);  // raw output
        opt.c_iflag &= ~(IXON | IXOFF | IXANY | IGNBRK| INLCR| IGNCR| ICRNL); /* disable sofware flow */
        ioctl(g_fd_debug, TCSETS2, (unsigned int)&opt);
        LREP("\r\n____________________________");
        LREP("\r\n|-------- startup ---------|\r\n");
    }else{
    	timeout.tv_sec = 0;
    	timeout.tv_nsec = 1000000*100;
        while(1){
            LED_TOGGLE(RED);
            nanosleep(&timeout, 0);
        };
    }
    if(g_fd_button < 0){
    	LREP("g_fd_button failed\r\n");
    }

    g_p_rf_mac_init = &rf_mac_init;
    g_p_rf_mac = &rf_mac;

    rf_mac_init.fd_spi = open_dev("spi-1", O_RDWR);
    if(rf_mac_init.fd_spi < 0){
        LREP("open spi device failed\r\n");
    }
    else{
        uival = SPI_MODE_0;
        if(ioctl(rf_mac_init.fd_spi, SPI_IOC_WR_MODE, (unsigned int)&uival) != 0) LREP("ioctl spi mode failed\r\n");
        uival = 5000000;
        if(ioctl(rf_mac_init.fd_spi, SPI_IOC_WR_MAX_SPEED_HZ, (unsigned int)&uival) != 0) LREP("ioctl spi speed failed\r\n");
        else{
            uival = 0;
            if(ioctl(rf_mac_init.fd_spi, SPI_IOC_RD_MAX_SPEED_HZ, (unsigned int)&uival) == 0) LREP("ioctl spi speed = %u\r\n", uival);
        }
    }
    rf_mac_init.fd_cs = open_dev("spi-1-cs", 0);
    if(rf_mac_init.fd_cs < 0) LREP("open spi cs device failed\r\n");
    rf_mac_init.fd_reset = open_dev("rf-reset", 0);
    if(rf_mac_init.fd_reset < 0) LREP("open rf-reset device failed\r\n");
    rf_mac_init.fd_intr = open_dev("rf-intr", 0);
    if(rf_mac_init.fd_intr < 0) LREP("open rf-intr device failed\r\n");

    for(i = 0; i < APP_THREAD_COUNT-1; i++)
        sem_post(&g_thread_startup[i]);

    sleep(1);

    LREP("1. MAC test\r\n");
    LREP("2. Normal mode\r\n");
    LREP("cmd? ");
    do{
    	userInput = kbhit(1000);
    }while(!userInput);
    LREP("\r\n");
    switch(userInput){
    	case '1':{
    		MAC_test();
    		break;
    	}
    	case '2':{
    		break;
    	}
    }

	timeout.tv_sec = 0;
	timeout.tv_nsec = 1000000*250;
    while (1) {                                          /* Task body, always written as an infinite loop.       */
        nanosleep(&timeout, 0);
    }
}
Beispiel #18
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  bool     redraw, firstRun;
  FRESULT  res;
  int      mountStatus;
  /* Used when iterating through directory */
  FILINFO Finfo;
  DIR     dir;
  FRESULT listDirStatus = FR_OK;
  /* Used for manifest operation */
  bool useManifest = false;
  char buffer[20];

  /* Use 32MHZ HFXO as core clock frequency */
  CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);

  /* Initialize DK board register access */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Setup SysTick Timer for 10 msec interrupts  */
  if (SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 100))
  {
    while (1) ;
  }

  /* Enable SPI access to MicroSD card */
  BSP_PeripheralAccess(BSP_MICROSD, true);

  /* Initialize filesystem */
  mountStatus = initFatFS();

  /* Open Manifest file. If a manifest file is not present, iterate through the
   * File system in filesystem order. */
  if (f_open(&manifest, "files.txt", FA_READ) == FR_OK)
    useManifest = true;

  firstRun = true;
  /* Update TFT display forever */
  while (1)
  {
    if (!useManifest)
    {
      /* Open root directory */
      strcpy(path, "");
      listDirStatus = f_opendir(&dir, path);
    }
    /* Iterate through files */
    while (1)
    {
      /* Check if we should control TFT display instead of
       * AEM/board control application. Read state of AEM pushbutton */
      redraw = TFT_AddressMappedInit();
      if (redraw)
      {
        if ( firstRun )
        {
          firstRun = false;
          SLIDES_init();
        }

        /* Check disk status */
        if (disk_status(0) != 0)
        {
          /* Filesystem not mounted, show fatal error. */
          SLIDES_showError(true, "Fatal:\n  Filesystem is not ready.\n  (%d)", disk_status(0));
        }

        /* Check if filesystem was successfully mounted. */
        if (mountStatus != 0)
        {
          /* Filesystem not mounted, show fatal error. */
          SLIDES_showError(true, "Fatal:\n  Filesystem could not be mounted.\n  (%d)", mountStatus);
        }

        /* Is there a manifest file present? */
        if (useManifest)
        {
          /* If we are at the end of the file, reset filepointer */
          if (f_eof(&manifest))
            f_lseek(&manifest, 0);
          /* Read next file from manifest file */
          f_gets(buffer, 20, &manifest);
          /* Display Bitmap */
          SLIDES_showBMP(buffer);
        }
        else
        {
          /* Check to see if the root directory was correctly opened. */
          if (listDirStatus != FR_OK)
          {
            SLIDES_showError(true, "Fatal:\n  Could not read root directory.\n  (%d)", listDirStatus);
          }

          /* Open the next entry in directory */
          res = f_readdir(&dir, &Finfo);
          if ((res != FR_OK) || !Finfo.fname[0])
          {
            /* End of directory listing. Break out of inner loop and reopen
             * directory entry */
            break;
          }
          /* Update display */
          SLIDES_showBMP(Finfo.fname);
        }

        /* Delay to allow the user to see the BMP file. */
        Delay(200);
      }
    }
  }
}
Beispiel #19
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  uint32_t buttons;
  POINT touchSample, P[ 3 ];
  ADC_Init_TypeDef init = ADC_INIT_DEFAULT;

  /* Configure for 48MHz HFXO operation of core clock */
  CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);

  /* Initialize DK board register access */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  CMU_ClockEnable(cmuClock_GPIO, true);

  CMU_ClockEnable( cmuClock_ADC0, true);
  /* Max ADC clock is 13MHz, use 14MHz/(1+1) or 48MHz/(5+1) */
  init.prescale = 5;
  ADC_Init(ADC0, &init);
  sInit.reference = adcRefVDD;

  /* Set frame buffer start address */
  frameBuffer = (uint16_t *) EBI_BankAddress(EBI_BANK2);

  /* Make sure CYCCNT is running, needed by delay functions. */
  DWT_CTRL |= 1;

  /* Indicate we are waiting for AEM button state enabling EFM */
  BSP_LedsSet(0x8001);
  while (BSP_RegisterRead(&BC_REGISTER->UIF_AEM) != BC_UIF_AEM_EFM)
  {
    /* Show a short "strobe light" on DK LEDs, indicating wait */
    BSP_LedsSet(0x8001);
    delayMs(200);
    BSP_LedsSet(0x4002);
    delayMs(50);
  }

  /* Initialize touch screen calibration factor matrix with approx. values  */
  setCalibrationMatrix( (POINT*)&lcdCalibPoints,   /* Display coordinates   */
                        (POINT*)&touchCalibPoints, /* Touch coordinates     */
                        &calibFactors );      /* Calibration factor matrix  */

  while (1)
  {
    if ( TFT_DirectInit(&tftInit) )
    {
      displayHelpScreen();
      BSP_LedsSet(0x0000);
      BSP_PeripheralAccess(BSP_TOUCH, true);
      GPIO_PinModeSet(LCD_TOUCH_X1, gpioModeInput, 0);
      GPIO_PinModeSet(LCD_TOUCH_X2, gpioModeInput, 0);
      GPIO_PinModeSet(LCD_TOUCH_Y1, gpioModeInput, 0);
      GPIO_PinModeSet(LCD_TOUCH_Y2, gpioModeInput, 0);

      do
      {
        buttons = readButtons();

        /* Draw on screen */
        if ( buttons & BC_UIF_PB1 )
        {
          memset( frameBuffer, BLACK, 2 * WIDTH * HEIGHT );   /* Clear screen */

          do
          {
            if ( touched() )
            {
              touchSample = getTouchSample();
              drawPixel( touchSample.x, touchSample.y, COLOR );
            }
            delayMs( 2 );

            buttons = readButtons() & ~BC_UIF_PB1;
          } while ( buttons == 0 );
        }

        /* Calibrate touch screen */
        else if ( buttons & BC_UIF_PB2 )
        {
          memset( frameBuffer, BLACK, 2 * WIDTH * HEIGHT );   /* Clear screen */
          drawCross( lcdCalibPoints[ 0 ].x, lcdCalibPoints[ 0 ].y, COLOR );
          TFT_DrawString(30, 35, "Tap green marker" );
          P[ 0 ] = getTouchTapSample10bit();

          memset( frameBuffer, BLACK, 2 * WIDTH * HEIGHT );   /* Clear screen */
          drawCross( lcdCalibPoints[ 1 ].x, lcdCalibPoints[ 1 ].y, COLOR );
          TFT_DrawString(40, 130, "Tap green marker" );
          P[ 1 ] = getTouchTapSample10bit();

          memset( frameBuffer, BLACK, 2 * WIDTH * HEIGHT );   /* Clear screen */
          drawCross( lcdCalibPoints[ 2 ].x, lcdCalibPoints[ 2 ].y, COLOR );
          TFT_DrawString(20, 180, "Tap green marker" );
          P[ 2 ] = getTouchTapSample10bit();

          setCalibrationMatrix( (POINT*)&lcdCalibPoints,/* Display coordinates*/
                                &P[0],                  /* Touch coordinates  */
                                &calibFactors );  /* Calibration factor matrix*/

          memset( frameBuffer, BLACK, 2 * WIDTH * HEIGHT );   /* Clear screen */
          TFT_DrawString(10, 100, "The touch screen is" );
          TFT_DrawString(30, 130, "now calibrated !" );
        }

        /* Display help screen */
        else if ( buttons & BC_UIF_PB3 )
        {
          displayHelpScreen();
          while ( readButtons() & BC_UIF_PB3 ) {}
        }

      } while ( ( buttons & EXIT_LOOP ) == 0 );
    }
    else
    {
      BSP_LedsSet(0x8001);
      delayMs(200);
    }
  }
}
Beispiel #20
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  uint8_t prod_rev;
  uint32_t temp;
  uint32_t temp_offset;
  float    temperature;

  /* Initialize DK board register access */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Initialize the TFT stdio retarget module. */
  RETARGET_TftInit();

  printf("\nEFM32 onchip temperature sensor example\n\n");

  CMU_ClockEnable(cmuClock_HFPER, true);
  CMU_ClockEnable(cmuClock_ADC0, true);
  CMU_ClockEnable(cmuClock_GPIO, true);

  /* Enable board control interrupts */
  BSP_InterruptDisable(0xffff);
  BSP_InterruptFlagsClear(0xffff);
  BSP_InterruptEnable(BC_INTEN_JOYSTICK);
  temperatureIRQInit();

  /* This is a work around for Chip Rev.D Errata, Revision 0.6. */
  /* Check for product revision 16 and 17 and set the offset */
  /* for ADC0_TEMP_0_READ_1V25. */
  prod_rev = (DEVINFO->PART & _DEVINFO_PART_PROD_REV_MASK) >> _DEVINFO_PART_PROD_REV_SHIFT;
  if( (prod_rev == 16) || (prod_rev == 17) )
  {
    temp_offset = 112;
  }
  else
  {
    temp_offset = 0;
  }

  /* Setup ADC for sampling internal temperature sensor. */
  setupSensor();

  /* Main loop - just read temperature and update LCD */
  while (1)
  {
    /* Start one ADC sample */
    ADC_Start(ADC0, adcStartSingle);

    /* Wait in EM1 for ADC to complete */
    EMU_EnterEM1();

    /* Read sensor value */
    /* According to rev. D errata ADC0_TEMP_0_READ_1V25 should be decreased */
    /* by the offset  but it is the same if ADC reading is increased - */
    /* reference manual 28.3.4.2. */
    temp = ADC_DataSingleGet(ADC0) + temp_offset;

    /* Convert ADC sample to Fahrenheit / Celsius and print string to display */
    if (showFahrenheit)
    {
      temperature = convertToFahrenheit(temp);
    }
    else
    {
      temperature = convertToCelsius(temp);
    }

    printf("%d.%d %c\n",
           (int) temperature, (int)(10*(temperature-(int)temperature)),
           showFahrenheit? 'F' : 'C');

    /* Sleep for 2 seconds in EM 2 */
    RTCDRV_Trigger(2000, NULL);
    EMU_EnterEM2(true);
  }
}
Beispiel #21
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  int toggleLED = 0;
  int cnt, x, y;
  bool movedown, moveright;

  /* Use 48MHZ HFXO as core clock frequency */
  CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);

  /* Initialize DK board register access */
  /* This demo currently only works in EBI mode */
  BSP_Init(BSP_INIT_DEFAULT);
  BSP_LedsInit();

  /* Setup SysTick Timer for 10 msec interrupts  */
  if (SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 1000))
  {
    while (1) ;
  }

  /* Initialize the display module. */
  DISPLAY_Init();

  /* Retarget stdio to a text display. */
  if (RETARGET_TextDisplayInit() != TEXTDISPLAY_EMSTATUS_OK)
  {
    while (1) ;
  }

  /* Output text on Memory LCD */
  printf("Hello, EFM32 Zero Gecko world!");
  Delay(2000);

  /* Clear screen */
  printf("\f");

  cnt = x = y = 0;
  movedown = moveright = true;

  /* Update Memory LCD display forever */
  while (1)
  {
    printf("%d", cnt );

    if (movedown)
    {
      y++;
      printf( TEXTDISPLAY_ESC_SEQ_CURSOR_DOWN_ONE_LINE );
    }
    else
    {
      y--;
      printf( TEXTDISPLAY_ESC_SEQ_CURSOR_UP_ONE_LINE );
    }

    if (y >= TEXTDISPLAY_DEVICE_0_LINES-1)
      movedown=false;
    if (y == 0)
      movedown=true;
    
    if (moveright)
    {
      x++;
      if (cnt >= 10)
        printf( TEXTDISPLAY_ESC_SEQ_CURSOR_LEFT_ONE_CHAR );
    } 
    else
    {
      x--;
      if (cnt > 10)
      {
        printf( TEXTDISPLAY_ESC_SEQ_CURSOR_LEFT_ONE_CHAR );
        printf( TEXTDISPLAY_ESC_SEQ_CURSOR_LEFT_ONE_CHAR );
        printf( TEXTDISPLAY_ESC_SEQ_CURSOR_LEFT_ONE_CHAR );
      }
      else
      {
        printf( TEXTDISPLAY_ESC_SEQ_CURSOR_LEFT_ONE_CHAR );
        printf( TEXTDISPLAY_ESC_SEQ_CURSOR_LEFT_ONE_CHAR );
      }
    }

    if (x >= TEXTDISPLAY_DEVICE_0_COLUMNS-2)
      moveright=false;
    if (x == 0)
      moveright=true;

    /* Clear screen and reset counter when 100 is reached. */
    if (++cnt == 100)
    {
      printf("\f");
      cnt = x = y = 0;
      movedown = moveright = true;
    }

    /* Toggle led after each Memory LCD_displayUpdate iteration */
    if (toggleLED)
    {
      BSP_LedsSet(0x0000);
      toggleLED = 0;
    }
    else
    {
      BSP_LedsSet(0x000f);
      toggleLED = 1;
    }
    Delay(100);
  }
}
Beispiel #22
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
    const int msDelay=100;
    char displayString[8];
    LCD_AnimInit_TypeDef anim = {
        true,
        0x00,
        lcdAnimShiftNone,
        0x03,
        lcdAnimShiftLeft,
        lcdAnimLogicOr
    };
    LCD_FrameCountInit_TypeDef fc = {
        true,
        2, /* Update each 2nd frame */
        lcdFCPrescDiv1,
    };

    /* Chip errata */
    CHIP_Init();

    /* Configure push button interrupts */
    BSP_Init(BSP_INIT_DK_SPI);

    /* If first word of user data page is non-zero, enable eA Profiler trace */
    BSP_TraceProfilerSetup();

    /* Initialize DK interrupt enable */
    DkIrqInit();

    /* Initialize GPIO interrupt */
    GpioIrqInit();

    /* Setup SysTick Timer for 1 msec interrupts  */
    if (SysTick_Config(SystemCoreClockGet() / 1000)) while (1) ;

    /* Initialize LCD controller */
    SegmentLCD_Init(false);

    /* Run countdown for user to select energy mode */
    msCountDown = 4000; /* milliseconds */
    eMode = 0;
    while(msCountDown > 0)
    {
        if ( eMode >=3 && eMode<=4) {
            sprintf(displayString, "EM%d", eMode);
            SegmentLCD_Write(displayString);
        }
        switch( eMode )
        {
        case 0:
            SegmentLCD_Write("EM0 32M");
            break;
        case 1:
            SegmentLCD_Write("EM1 32M");
            break;
        case 2:
            SegmentLCD_Write("EM2 32K");
            break;
        case 3:
            SegmentLCD_Write("EM3    ");
            break;
        case 4:
            SegmentLCD_Write("EM4    ");
            break;
        case 5:
            SegmentLCD_Write("EM2+RTC");
            break;
        case 6:
        default:
            SegmentLCD_Write("RTC+LCD");
            break;
        }
        SegmentLCD_Number(msCountDown);
        Delay(msDelay);
        msCountDown -= msDelay;
    }
    /* Disable components, reenable when needed */
    SegmentLCD_Disable();
    RTC_Enable(false);

    GPIO->IEN = 0x00000000;
    NVIC_DisableIRQ(GPIO_EVEN_IRQn);
    BSP_Disable();
    GpioDisablePins();

    /* Go to energy mode and wait for reset */
    switch(eMode)
    {
    case 0:
        /* Disable systick timer */
        SysTick->CTRL  = 0;

        /* 32Mhz primes demo - running off HFXO */
        CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);
        /* Disable HFRCO, LFRCO and all unwanted clocks */
        CMU->OSCENCMD = CMU_OSCENCMD_HFRCODIS;
        CMU->OSCENCMD = CMU_OSCENCMD_LFRCODIS;
        CMU->HFPERCLKEN0  = 0x00000000;
        CMU->HFCORECLKEN0 = 0x00000000;
        CMU->LFACLKEN0    = 0x00000000;
        CMU->LFBCLKEN0    = 0x00000000;
        /* Supress Conditional Branch Target Prefetch */
        MSC->READCTRL = MSC_READCTRL_MODE_WS1SCBTP;
        {
#define PRIM_NUMS 64
            uint32_t i, d, n;
            uint32_t primes[PRIM_NUMS];

            /* Find prime numbers forever */
            while (1)
            {
                primes[0] = 1;
                for (i = 1; i < PRIM_NUMS;)
                {
                    for (n = primes[i - 1] + 1; ; n++)
                    {
                        for (d = 2; d <= n; d++)
                        {
                            if (n == d)
                            {
                                primes[i] = n;
                                goto nexti;
                            }
                            if (n%d == 0) break;
                        }
                    }
nexti:
                    i++;
                }
            }
        }
    case 1:
        /* Disable systick timer */
        SysTick->CTRL  = 0;

        CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);
        /* Disable HFRCO, LFRCO and all unwanted clocks */
        CMU->OSCENCMD = CMU_OSCENCMD_HFRCODIS;
        CMU->OSCENCMD = CMU_OSCENCMD_LFRCODIS;
        CMU->HFPERCLKEN0  = 0x00000000;
        CMU->HFCORECLKEN0 = 0x00000000;
        CMU->LFACLKEN0    = 0x00000000;
        CMU->LFBCLKEN0    = 0x00000000;
        EMU_EnterEM1();
        break;
    case 2:
        /* Enable LFRCO */
        CMU->OSCENCMD = CMU_OSCENCMD_LFRCOEN;
        /* Disable everything else */
        CMU->OSCENCMD = CMU_OSCENCMD_LFXODIS;
        CMU->HFPERCLKEN0  = 0x00000000;
        CMU->HFCORECLKEN0 = 0x00000000;
        CMU->LFACLKEN0    = 0x00000000;
        CMU->LFBCLKEN0    = 0x00000000;
        EMU_EnterEM2(false);
        break;
    case 3:
        CMU->OSCENCMD = CMU_OSCENCMD_LFXODIS;
        CMU->OSCENCMD = CMU_OSCENCMD_LFRCODIS;
        CMU->HFPERCLKEN0  = 0x00000000;
        CMU->HFCORECLKEN0 = 0x00000000;
        CMU->LFACLKEN0    = 0x00000000;
        CMU->LFBCLKEN0    = 0x00000000;
        EMU_EnterEM3(false);
        break;
    case 4:
        EMU_EnterEM4();
        break;
    case 5:
        /* EM2 + RTC - only briefly wake up to reconfigure each second */
        while(1)
        {
            RTCDRV_Trigger(2000, NULL);
            EMU_EnterEM2(false);
        }
    case 6:
        /* EM2 + RTC + LCD */
        SegmentLCD_Init(false);
        /* Animate LCD */
        LCD_FrameCountInit(&fc);
        LCD_AnimInit(&anim);
        while(1)
        {
            SegmentLCD_Write("Energy");
            /* Sleep in EM2 */
            RTCDRV_Trigger(2000, NULL);
            EMU_EnterEM2(false);

            SegmentLCD_Write("Micro");
            /* Sleep in EM2 */
            RTCDRV_Trigger(2000, NULL);
            EMU_EnterEM2(false);
        }
    case 7:
        break;
    }

    return 0;
}
Beispiel #23
0
/*
=================
Qcommon_Init
=================
*/
void Qcommon_Init(int argc, char **argv)
{
    if (setjmp(com_abortframe))
        Sys_Error("Error during initialization: %s", com_errorMsg);

    com_argc = argc;
    com_argv = argv;

    Com_SetLastError(NULL);

    X86_SetFPCW();

    srand(time(NULL));

    // prepare enough of the subsystems to handle
    // cvar and command buffer management
    Z_Init();
    MSG_Init();
    Cbuf_Init();
    Cmd_Init();
    Cvar_Init();
    Key_Init();
    Prompt_Init();
    Con_Init();

    //
    // init commands and vars
    //
    z_perturb = Cvar_Get("z_perturb", "0", 0);
#if USE_CLIENT
    host_speeds = Cvar_Get("host_speeds", "0", 0);
#endif
#ifdef _DEBUG
    developer = Cvar_Get("developer", "0", 0);
#endif
    timescale = Cvar_Get("timescale", "1", CVAR_CHEAT);
    fixedtime = Cvar_Get("fixedtime", "0", CVAR_CHEAT);
    logfile_enable = Cvar_Get("logfile", "0", 0);
    logfile_flush = Cvar_Get("logfile_flush", "0", 0);
    logfile_name = Cvar_Get("logfile_name", "console", 0);
    logfile_prefix = Cvar_Get("logfile_prefix", "[%Y-%m-%d %H:%M] ", 0);
#if USE_CLIENT
    dedicated = Cvar_Get("dedicated", "0", CVAR_NOSET);
    cl_running = Cvar_Get("cl_running", "0", CVAR_ROM);
    cl_paused = Cvar_Get("cl_paused", "0", CVAR_ROM);
#else
    dedicated = Cvar_Get("dedicated", "1", CVAR_ROM);
#endif
    sv_running = Cvar_Get("sv_running", "0", CVAR_ROM);
    sv_paused = Cvar_Get("sv_paused", "0", CVAR_ROM);
    com_timedemo = Cvar_Get("timedemo", "0", CVAR_CHEAT);
    com_date_format = Cvar_Get("com_date_format", "%Y-%m-%d", 0);
#ifdef _WIN32
    com_time_format = Cvar_Get("com_time_format", "%H.%M", 0);
#else
    com_time_format = Cvar_Get("com_time_format", "%H:%M", 0);
#endif
#ifdef _DEBUG
    com_debug_break = Cvar_Get("com_debug_break", "0", 0);
#endif
    com_fatal_error = Cvar_Get("com_fatal_error", "0", 0);
    com_version = Cvar_Get("version", com_version_string, CVAR_SERVERINFO | CVAR_ROM);

    allow_download = Cvar_Get("allow_download", COM_DEDICATED ? "0" : "1", CVAR_ARCHIVE);
    allow_download_players = Cvar_Get("allow_download_players", "1", CVAR_ARCHIVE);
    allow_download_models = Cvar_Get("allow_download_models", "1", CVAR_ARCHIVE);
    allow_download_sounds = Cvar_Get("allow_download_sounds", "1", CVAR_ARCHIVE);
    allow_download_maps = Cvar_Get("allow_download_maps", "1", CVAR_ARCHIVE);
    allow_download_textures = Cvar_Get("allow_download_textures", "1", CVAR_ARCHIVE);
    allow_download_pics = Cvar_Get("allow_download_pics", "1", CVAR_ARCHIVE);
    allow_download_others = Cvar_Get("allow_download_others", "0", 0);

    rcon_password = Cvar_Get("rcon_password", "", CVAR_PRIVATE);

    Cmd_AddCommand("z_stats", Z_Stats_f);

    //Cmd_AddCommand("setenv", Com_Setenv_f);

    Cmd_AddMacro("com_date", Com_Date_m);
    Cmd_AddMacro("com_time", Com_Time_m);
    Cmd_AddMacro("com_uptime", Com_Uptime_m);
    Cmd_AddMacro("com_uptime_long", Com_UptimeLong_m);
    Cmd_AddMacro("random", Com_Random_m);
    Cmd_AddMacro("com_maplist", Com_MapList_m);

    // add any system-wide configuration files
    Sys_AddDefaultConfig();

    // we need to add the early commands twice, because
    // a basedir or cddir needs to be set before execing
    // config files, but we want other parms to override
    // the settings of the config files
    Com_AddEarlyCommands(qfalse);

    Sys_Init();

    Sys_RunConsole();

    FS_Init();

    Sys_RunConsole();

    // no longer allow CVAR_NOSET modifications
    com_initialized = qtrue;

    // after FS is initialized, open logfile
    logfile_enable->changed = logfile_enable_changed;
    logfile_flush->changed = logfile_param_changed;
    logfile_name->changed = logfile_param_changed;
    logfile_enable_changed(logfile_enable);

    // execute configs: default.cfg may come from the packfile, but config.cfg
    // and autoexec.cfg must be real files within the game directory
    Com_AddConfigFile(COM_DEFAULT_CFG, 0);
    Com_AddConfigFile(COM_CONFIG_CFG, FS_TYPE_REAL | FS_PATH_GAME);
    Com_AddConfigFile(COM_AUTOEXEC_CFG, FS_TYPE_REAL | FS_PATH_GAME);
    Com_AddConfigFile(COM_POSTEXEC_CFG, FS_TYPE_REAL);

    Com_AddEarlyCommands(qtrue);

    Cmd_AddCommand("lasterror", Com_LastError_f);

    Cmd_AddCommand("quit", Com_Quit_f);
#if !USE_CLIENT
    Cmd_AddCommand("recycle", Com_Recycle_f);
#endif

    Netchan_Init();
    NET_Init();
    BSP_Init();
    CM_Init();
    SV_Init();
    CL_Init();
    TST_Init();

    Sys_RunConsole();

    // add + commands from command line
    if (!Com_AddLateCommands()) {
        // if the user didn't give any commands, run default action
        char *cmd = COM_DEDICATED ? "dedicated_start" : "client_start";

        if ((cmd = Cmd_AliasCommand(cmd)) != NULL) {
            Cbuf_AddText(&cmd_buffer, cmd);
            Cbuf_Execute(&cmd_buffer);
        }
    } else {
        // the user asked for something explicit
        // so drop the loading plaque
        SCR_EndLoadingPlaque();
    }

    // even not given a starting map, dedicated server starts
    // listening for rcon commands (create socket after all configs
    // are executed to make sure port number is properly set)
    if (COM_DEDICATED) {
        NET_Config(NET_SERVER);
    }

    Com_AddConfigFile(COM_POSTINIT_CFG, FS_TYPE_REAL);

    Com_Printf("====== " PRODUCT " initialized ======\n\n");
    Com_LPrintf(PRINT_NOTICE, APPLICATION " " VERSION ", " __DATE__ "\n");
    Com_Printf("http://skuller.net/q2pro/\n\n");

    time(&com_startTime);

    com_eventTime = Sys_Milliseconds();
}
/***************************************************************************//**
* @brief
*   Main function. Setup ADC, FFT, clocks, PRS, DMA, Timer,
*   and process FFT forever.
*******************************************************************************/
int main(void)
{
  arm_status status;
  char buf[20];
  bool redraw = false;
  int glibStatus;
  
  DMA_Init_TypeDef   dmaInit;
  TIMER_Init_TypeDef timerInit = TIMER_INIT_DEFAULT;

  /* Initialize DVK board register access */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceEtmSetup();

  /* Connect audio in to ADC */
  BSP_PeripheralAccess(BSP_AUDIO_IN, true);

  /* Wait a while in order to let signal from audio-in stabilize after */
  /* enabling audio-in peripheral. */
  RTCDRV_Trigger(1000, NULL);
  EMU_EnterEM2(true);
  
  /* Initialize the CFFT/CIFFT module */
  status = arm_rfft_init_f32(&rfft_instance,
                             &cfft_instance,
                             GUITAR_AUDIO_BUFFER_SAMPLES,
                             0,  /* forward transform */
                             1); /* normal, not bitreversed, order */
  
  if (status != ARM_MATH_SUCCESS) {
    /* Error initializing RFFT module. */
    while (1) ;
  }
  
  dataReadyForFFT = false;
  processingFFT   = false;
  
  /* Use the HFXO. We still only manage to process about
   * a third the buffers through FFT
   */
  CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);
  
  /* Setup SysTick Timer for 1 msec interrupts  */
  if (SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 1000))
  {
    while (1) ;
  }

  /* Enable clocks required */
  CMU_ClockEnable(cmuClock_HFPER, true);
  CMU_ClockEnable(cmuClock_ADC0, true);
  CMU_ClockEnable(cmuClock_PRS, true);
  CMU_ClockEnable(cmuClock_DMA, true);
  CMU_ClockEnable(cmuClock_TIMER0, true);

  NVIC_SetPriority(DMA_IRQn, 0); /* Highest priority */

  /* Configure peripheral reflex system used by TIMER to trigger ADC/DAC */
  guitarPRSConfig(GUITAR_PRS_CHANNEL);

  /* Configure general DMA issues */
  dmaInit.hprot        = 0;
  dmaInit.controlBlock = dmaControlBlock;
  DMA_Init(&dmaInit);

  /* Configure ADC used for audio-in */
  guitarADCConfig();

  /* Trigger sampling according to configured sample rate */
  TIMER_TopSet(TIMER0, CMU_ClockFreqGet(cmuClock_HFPER) / GUITAR_AUDIO_SAMPLE_RATE);
  TIMER_Init(TIMER0, &timerInit);

  /* Wait until we have control over display */
  while(!redraw)
  {
    redraw = TFT_AddressMappedInit();
  }
  
  /* Init graphics context - abort on failure */
  glibStatus = GLIB_contextInit(&gc);
  if (glibStatus != GLIB_OK) while (1) ;
  
  /* Clear the screen */
  gc.backgroundColor = GLIB_rgbColor(0, 0, 0);
  GLIB_clear(&gc);
  
  while (1)
  {
    while (dataReadyForFFT)
    {
      float32_t freq;

      processingFFT = true;
      processFFT();
      dataReadyForFFT = false;
      processingFFT = false;
      
      /* Get frequency and make string with one decimal accuracy */
      freq = getFreq();
      sprintf(buf, "%6.1f", freq);
      
      /* Check if we should control TFT display instead of AEM/board controller */
      redraw = TFT_AddressMappedInit();
      if (redraw)
      {
        gc.foregroundColor = GLIB_rgbColor(220, 220, 220);
        gc.backgroundColor = GLIB_rgbColor(0, 0, 0);

        /* Print the frequency somewhere in the middle of the screen */
        GLIB_drawString(&gc,
                        buf,
                        strlen(buf),
                        100,
                        120,
                        1);
      }
    }
    EMU_EnterEM1();
  }
}
Beispiel #25
0
static  void  Task_Start (void *p_arg)
{
    CPU_INT32U  cpu_clk_freq;
    CPU_INT32U  cnts;
    OS_ERR    err_os;


   (void)&p_arg;

    BSP_Init();                                                 /* Initialize BSP functions                             */

    cpu_clk_freq = BSP_SysClkFreqGet();                         /* Determine SysTick reference freq.                    */
    cnts         = cpu_clk_freq                                 /* Determine nbr SysTick increments                     */
                 / (CPU_INT32U)OSCfg_TickRate_Hz;

    OS_CPU_SysTickInit(cnts);
    CPU_Init();                                                 /* Initialize the uC/CPU services                       */

#if (OS_CFG_STAT_TASK_EN > 0u)
    OSStatTaskCPUUsageInit(&err_os);                            /* Compute CPU capacity with no task running            */
#endif

    Mem_Init();

#ifdef CPU_CFG_INT_DIS_MEAS_EN
    CPU_IntDisMeasMaxCurReset();
#endif

//		AppTaskCreate();                                            /* Creates all the necessary application tasks.         */

//    while (DEF_ON) {
//        BSP_LED_Toggle(0);

//        OSTimeDlyHMSM(0, 0, 0, 500,
//                      OS_OPT_TIME_HMSM_STRICT,
//                     &err_os);
//    }

	// Set the pinout for the board, including required pins for Ethernet
	// operation.
	
	PinoutSet(0,1);
	
	g_ui32SysClock = SysCtlClockFreqSet((SYSCTL_XTAL_25MHZ |
																			 SYSCTL_OSC_MAIN |
																			 SYSCTL_USE_PLL |
																			 SYSCTL_CFG_VCO_480), 120000000);
		
	UARTStdioConfig(0, 115200, g_ui32SysClock); //cpu_clk_freq);
	
	UARTprintf("\033[2J\033[H");
	UARTprintf("Welcome to the Connected LaunchPad!!\n");
	UARTprintf("Internet of Things Demo\n");
	UARTprintf("Type \'help\' for help.\n\n");
	
	//create task LED1	
	OSTaskCreate((OS_TCB     *)&LED_TCB,					                      
               (CPU_CHAR   *)"LED",						            
               (OS_TASK_PTR )Task_LED,					            
               (void       *)0,							                
               (OS_PRIO     )TASK_LED_PRIO,				       
               (CPU_STK    *)&LED_Stk[0],				        
               (CPU_STK_SIZE)TASK_LED_STK_SIZE/10,		   
               (CPU_STK_SIZE)TASK_LED_STK_SIZE,			   
               (OS_MSG_QTY  )0,							             
               (OS_TICK     )0,							
               (void       *)0,							              
               (OS_OPT      )(OS_OPT_TASK_STK_CHK | 
                              OS_OPT_TASK_STK_CLR),	      
               (OS_ERR     *)&err_os);						            
			

	// createe test task
	OSTaskCreate((OS_TCB     *)&Tmr_TCB,					  
               (CPU_CHAR   *)"TS",						
               (OS_TASK_PTR )Task_Tmr,				
               (void       *)0,							
               (OS_PRIO     )TASK_DBG_PRIO,				
               (CPU_STK    *)&Tmr_Stk[0],				
               (CPU_STK_SIZE)TASK_TMR_STK_SIZE/10,		
               (CPU_STK_SIZE)TASK_TMR_STK_SIZE,			
               (OS_MSG_QTY  )0,						
               (OS_TICK     )0,							
               (void       *)0,							
               (OS_OPT      )(OS_OPT_TASK_STK_CHK | 
                              OS_OPT_TASK_STK_CLR),	 
               (OS_ERR     *)&err_os);	
               
  // remove the startup task.	
	OSTaskDel(&StartUp_TCB,&err_os);	
}
//*****************************************************************************
//
// Main application entry function.
//
//*****************************************************************************
int
main(void)
{
    tBoolean bRetcode;

    //
    // Set the system clock to run at 50MHz from the PLL
    //
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // NB: We don't call PinoutSet() in this testcase since the EM header
    // expansion board doesn't currently have an I2C ID EEPROM.  If we did
    // call PinoutSet() this would configure all the EPI pins for SDRAM and
    // we don't want to do this.
    //
    g_eDaughterType = DAUGHTER_NONE;

    //
    // Enable peripherals required to drive the LCD.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOH);

    //
    // Configure SysTick for a 10Hz interrupt.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / TICKS_PER_SECOND);
    ROM_SysTickEnable();
    ROM_SysTickIntEnable();

    //
    // Initialize the display driver.
    //
    Kitronix320x240x16_SSD2119Init();

    //
    // Initialize the touch screen driver.
    //
    TouchScreenInit();

    //
    // Set the touch screen event handler.
    //
    TouchScreenCallbackSet(WidgetPointerMessage);

    //
    // Add the compile-time defined widgets to the widget tree.
    //
    WidgetAdd(WIDGET_ROOT, (tWidget *)&g_sHeading);

    //
    // Initialize the status string.
    //
    UpdateStatus(true, "Joining network...");

    //
    // Paint the widget tree to make sure they all appear on the display.
    //
    WidgetPaint(WIDGET_ROOT);

    //
    // Initialize the SimpliciTI BSP.
    //
    BSP_Init();

    //
    // Set the SimpliciTI device address using the current Ethernet MAC address
    // to ensure something like uniqueness.
    //
    bRetcode = SetSimpliciTIAddress();

    //
    // Did we have a problem with the address?
    //
    if(!bRetcode)
    {
        //
        // Yes - make sure the display is updated then hang the app.
        //
        WidgetMessageQueueProcess();
        while(1)
        {
            //
            // MAC address is not set so hang the app.
            //
        }
    }

    //
    // Turn both "LEDs" off.
    //
    SetLED(1, false);
    SetLED(2, false);

    //
    // Keep trying to join (a side effect of successful initialization) until
    // successful.  Toggle LEDS to indicate that joining has not occurred.
    //
    while(SMPL_SUCCESS != SMPL_Init(0))
    {
      ToggleLED(1);
      ToggleLED(2);
      SPIN_ABOUT_A_SECOND;
    }

    //
    // We have joined the network so turn on both "LEDs" to indicate this.
    //
    SetLED(1, true);
    SetLED(2, true);
    UpdateStatus(true, "Joined network");

    //
    // Link to the access point which is now listening for us and continue
    // processing.  This function does not return.
    //
    LinkTo();
}
Beispiel #27
0
int main(void)
{
  DMA_Init_TypeDef dmaInit;
  TIMER_Init_TypeDef timerInit = TIMER_INIT_DEFAULT;
  SYSTEM_ChipRevision_TypeDef chipRev;
  uint32_t volSample;
  uint32_t vpot;
  uint32_t rpot;
  uint32_t leds;

  /* Chip revision alignment and errata fixes */
  CHIP_Init();

  /* ADC errata for rev B when using VDD as reference, need to multiply */
  /* result by 2 */
  SYSTEM_ChipRevisionGet(&chipRev);
  if ((chipRev.major == 1) && (chipRev.minor == 1))
  {
    preampErrataShift = 1;
  }

  /* Initialize DVK board register access */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Connect potentiometer to EFM32 (and ensure ambient light sensor */
  /* sharing same ADC channel is not enabled). */
  BSP_PeripheralAccess(BSP_AMBIENT, false);
  BSP_PeripheralAccess(BSP_POTMETER, true);

  /* Connect audio in/out to ADC/DAC */
  BSP_PeripheralAccess(BSP_AUDIO_IN, true);
  BSP_PeripheralAccess(BSP_AUDIO_OUT, true);

  /* Wait a while in order to let signal from audio-in stabilize after */
  /* enabling audio-in peripheral. */
  RTCDRV_Trigger(1000, NULL);
  EMU_EnterEM2(true);

  /* Current example gets by at 14MHz core clock (also with low level of compiler */
  /* optimization). That may however change if modified, consider changing to */
  /* higher HFRCO band or HFXO. */
  /*
    Use for instance one of below statements to increase core clock.
    CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);
    CMU_HFRCOBandSet(cmuHFRCOBand_28MHz);
  */

  /* Enable clocks required */
  CMU_ClockEnable(cmuClock_HFPER, true);
  CMU_ClockEnable(cmuClock_ADC0, true);
  CMU_ClockEnable(cmuClock_DAC0, true);
  CMU_ClockEnable(cmuClock_PRS, true);
  CMU_ClockEnable(cmuClock_DMA, true);
  CMU_ClockEnable(cmuClock_TIMER0, true);

  /* Ensure DMA interrupt at higher priority than PendSV. */
  /* (PendSV used to process sampled audio). */
  NVIC_SetPriority(DMA_IRQn, 0); /* Highest priority */
  NVIC_SetPriority(PendSV_IRQn, (1 << __NVIC_PRIO_BITS) - 1); /* Lowest priority */

  /* Configure peripheral reflex system used by TIMER to trigger ADC/DAC */
  preampPRSConfig(PREAMP_PRS_CHANNEL);

  /* Configure general DMA issues */
  dmaInit.hprot = 0;
  dmaInit.controlBlock = dmaControlBlock;
  DMA_Init(&dmaInit);

  /* Configure DAC used for audio-out */
  preampDACConfig();

  /* Configure ADC used for audio-in */
  preampADCConfig();

  /* Trigger sampling according to configured sample rate */
  TIMER_TopSet(TIMER0, CMU_ClockFreqGet(cmuClock_HFPER) / PREAMP_AUDIO_SAMPLE_RATE);
  TIMER_Init(TIMER0, &timerInit);

  /* Main loop, only responsible for checking volume */
  while (1)
  {
    /* Triggered to check volume setting? */
    if (preampCheckVolume)
    {
      preampCheckVolume = false;

      /* Trigger single conversion, and wait for it to complete */
      ADC_IntClear(ADC0, ADC_IF_SINGLE);
      ADC_Start(ADC0, adcStartSingle);
      while (!(ADC_IntGet(ADC0), ADC_IF_SINGLE))
      {
        /* Just wait for an interrupt to wake us up (DMA interrupts occur */
        /* regularly). Thus, we don't need to enable ADC interrupt. */
        EMU_EnterEM1();
      }
      volSample = ADC_DataSingleGet(ADC0) << preampErrataShift;

      /*
        DVK potentiometer design:

                 | Vdd = 3.3V
                +-+
                | | Rpullup = 10kOhm
                +-+
                 |
                 +------> Vpot (to ADC)
                 |
                +-+
                | | Rpot = 0-100kOhm
                +-+
                 | Gnd

         Vpot = Rpot * Vdd / (Rpullup + Rpot)

         This gives a non-linear voltage level measured by ADC with respect to
         pot meter position. In order to determine the actual Rpot setting, which
         is linear with respect to position, rewrite the above formula to:

         Rpot = Rpullup * Vpot / (Vdd - Vpot)
      */

      /* Vpot sampled with 8 bit, divide by max value */
      vpot = (POTENTIOMETER_VDD_mV * volSample) / 0xff;

      /* Calculate Rpot determining volume */
      rpot = (POTENTIOMETER_PULLUP_OHM * vpot) / (POTENTIOMETER_VDD_mV - vpot);
      /* The potentiometer may not be exact in upper range, make sure we don't use a higher */
      /* value than assumed by defines. */
      if (rpot > POTENTIOMETER_MAX_OHM)
      {
        rpot = POTENTIOMETER_MAX_OHM;
      }

      /* Precalculate adjustment factor to avoid repeated calculation when used. */
      /* Scale down Rpot a bit to use in integer calculation without overflowing 32 bit reg. */
      preampAdjustFactor = rpot / PREAMP_ADJUST_DIVISOR;

      /* Use 14 right leds for volume control indicating. Leftmost led is used to indicate */
      /* clipping of audio out signal (in order to limit volume out). Add half interval */
      /* for improving integer rounding effects. */
      leds = rpot + (POTENTIOMETER_MAX_OHM / (14 * 2));
      leds = (1 << ((14 * leds) / POTENTIOMETER_MAX_OHM)) - 1;

      /* Audio out clipped? */
      if (preampAudioOutClipped)
      {
        preampAudioOutClipped = false;
        leds |= 0x8000;
      }
      BSP_LedsSet((uint16_t)leds);
    }

    EMU_EnterEM1();
  }
}
Beispiel #28
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  int      toggleLED = 0;
  bool     redraw = false;
  EMSTATUS status;
  GLIB_Rectangle_t rect = {
    .xMin =   0,
    .yMin =   0,
    .xMax = 319,
    .yMax = 239,
  };

  /* Use 48MHZ HFXO as core clock frequency */
  CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);

  /* Initialize DK board register access */
  /* This demo currently only works in EBI mode */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Setup SysTick Timer for 1 msec interrupts  */
  if (SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 1000))
  {
    while (1) ;
  }

  /* Wait until we have control over display */
  while(!redraw)
  {
    redraw = TFT_AddressMappedInit();
  }

  /* Init graphics context - abort on failure */
  status = GLIB_contextInit(&gc);
  if (status != GLIB_OK) while (1) ;

  /* Clear framebuffer */
  gc.foregroundColor = GLIB_rgbColor(20, 40, 20);
  GLIB_drawRectFilled(&gc, &rect);

  /* Update TFT display forever */
  while (1)
  {
    /* Check if we should control TFT display instead of AEM/board controller */
    redraw = TFT_AddressMappedInit();
    if(redraw)
    {
      /* Update display */
      TFT_displayUpdate(&gc);
    }
    else
    {
      /* No need to refresh display when BC is active */
      Delay(200);
    }
    /* Toggle led after each TFT_displayUpdate iteration */
    if (toggleLED)
    {
      BSP_LedsSet(0x0000);
      toggleLED = 0;
    }
    else
    {
      BSP_LedsSet(0x000f);
      toggleLED = 1;
    }
  }
}