Exemple #1
0
static void InitializeSystem(void)
{
	char result = 0;
	
	// initialize not used pins to inputs
	DDRD &= ~((1<<0) | (1<<1));
	DDRB &= ~((1<<4) | (1<<5) | (1<<6) | (1<<7));
	
	InitLED();
	
	result |= DINs_Initialize();
	result |= AINs_Initialize();
	result |= DOUTs_Initialize();
	result |= I2C_Address_Initialize();
	result |= I2C_FSM_Initialize();
	
	// check for error
	if(result) {
		uint32_t delay;
		
		while(1)
		{
			delay = 10000;
			while(delay--);
		
			ToggleLED();
		}		
	}
	
	sei(); /* enable interrupts */
}
int FuncionTeclas0(void){
	tecla = EscanearTeclas();
	if (comp == tecla) return 0;
	comp = tecla;
	ToggleLED(getVerde());
	switch (tecla){
	case 1:
		if (Voutmax - 3.0 != 0 ) Voutmax+=0.1;
		EnviarMensaje(1);
		break;
	case 2:
		if (Voutmax != 0) Voutmax-=0.1;
//		EnviarMensaje(2);
		break;
	case 3:
		Voutmax = 0;
//		EnviarMensaje(3);
		break;
	case 4:
		togglefuncion = 1;
		break;
	default: break;
	}
	return 1;
}
void Timer_ISR(void){
	ReiniciarTimer();
	ToggleLED(LED);

	valor_adc = LeerADC();
	valor_dac = (uint16_t) valor_adc * Voutmax;
	setDAC(valor_dac);
}
Exemple #4
0
void LED_InitGPIO(void)
{
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
    
    GPIO_InitTypeDef gpioInit = {
        .GPIO_Pin = 0,
        .GPIO_Mode = GPIO_Mode_OUT,
        .GPIO_OType = GPIO_OType_PP,
        .GPIO_PuPd = GPIO_PuPd_UP,
        .GPIO_Speed = GPIO_Speed_50MHz
    };
    for(int j = 0; j < 4; ++j) {
        gpioInit.GPIO_Pin = LED_PIN[j];
        GPIO_Init(LED_PORT[j], &gpioInit);
    }
}

void SetLED(int led, bool state) {
    if(state)
        LED_PORT[led]->BSRRL = LED_PIN[led];
    else
        LED_PORT[led]->BSRRH = LED_PIN[led];
}

void ToggleLED(int led) {
    LED_PORT[led]->ODR ^= LED_PIN[led];
}

static void InitClocks(void);
// static void TIM4_Config(void);

int main(void)
{
    InitClocks();
    
    // Configure for millisecond system ticks
    if(SysTick_Config(SystemCoreClock/1000))
        while(1) {;}
    
    LED_InitGPIO();
    
    SetLED(0, true);
    SetLED(1, true);
    
    int led = 0;
    while(1)
    {
        delay_ms(1);
        ToggleLED(led);
        led = (led + 3)%4;
    }
} // main()
Exemple #5
0
int main(void)
{
	uint32_t delay;
	
	InitializeSystem();

	// check for button pressed at startup to reset slave address to default
	if(BtnPressed()) {
		delay = 30000;
		while(--delay) {
			// button released before timeout occurred
			if(!BtnPressed())
				break;

			// indicate activity
			if(!(delay % 1000))
				ToggleLED();
		}

		// button pressed long enough, reset to default
		if(!delay) {
			I2C_Address_SetDefault();
			I2C_FSM_Initialize(); // load the new address
		}
	}

	delay = 20000;
		
    while(1)
    {
		I2C_FSM_Refresh();

		// toggle LED to indicate activity
		if( (delay--) == 0 ) {
			delay = 200000;
			ToggleLED();
		}			
    }
}
//*****************************************************************************
//
// The main loop calls this function to process received SimpliciTI messages.
// In this case, we are using a trivial protocol which merely passes a LED
// number and transaction ID.  We toggle the LED that is indicated in the
// message.
//
//*****************************************************************************
static void
ProcessMessage(linkID_t sLID, uint8_t *pucMsg, uint8_t ucLen)
{
    //
    // Were we passed a real message (non-zero length)?
    //
    if (ucLen)
    {
        //
        // Yes - the first byte of the message indicates an LED that we should
        // toggle so go ahead and do this.
        //
        ToggleLED(*pucMsg);
    }
    return;
}
//*****************************************************************************
//
// This function is called whenever an alert is received from another device.
// It retransmits the alert every 100mS and toggles an LED to indicate that
// the alarm has been sounded.
//
// This function does not return.
//
//*****************************************************************************
void
Start2Babble()
{
    uint8_t pucMsg[1];

    //
    // Tell the user what we are doing.
    //
    UpdateStatus(false, "Retransmitting alert");

    /* wake up radio. */
    SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_AWAKE, 0);

    //
    // Send the bad news message. In a real application, to prevent confusion
    // with different "networks" such as neighboring smoke alarm arrays send a
    // token controlled by a DIP switch, for example, and filter in this token.
    //
    pucMsg[0] = BAD_NEWS;

    //
    // Keep sending the alert forever.  In "real life" you would provide a method
    // to stop sending the alert when the sensor was reset or the alert condition
    // cleared.
    //
    while (1)
    {
        //
        // Wait 100mS or so.
        //
        ApplicationDelay(100);

        //
        // Babble...
        //
        SMPL_Send(SMPL_LINKID_USER_UUD, pucMsg, sizeof(pucMsg));
        ToggleLED(2);
    }
}
//*****************************************************************************
//
// Main application entry function.
//
//*****************************************************************************
int
main(void)
{
    tBoolean bSuccess, bRetcode, bInitialized;

    //
    // Set the system clock to run at 50MHz from the PLL
    //
    MAP_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);

    //
    // 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();
    if(!bRetcode)
    {
        //
        // The Ethernet MAC address can't have been set so hang here since we
        // don't have an address to use for SimpliciTI.
        //
        WidgetMessageQueueProcess();
        while(1)
        {
            //
            // MAC address is not set so hang the app.
            //
        }
    }

    //
    // First time through, we need to initialize the SimpliciTI stack.
    //
    bInitialized = false;

    //
    // The main loop starts here now that we have joined the network.
    //
    while(1)
    {
        //
        // Tell the user what to do.
        //
        UpdateStatus(true, "Please choose the operating mode.");

        //
        // Now wait until the user selects whether we should run as the sender
        // or the receiver.
        //
        while(g_ulMode == MODE_UNDEFINED)
        {
            //
            // Just spin, processing UI messages and waiting for someone to
            // press one of the mode buttons.
            //
            WidgetMessageQueueProcess();
        }

        //
        // At this point, the mode is set so remove the buttons from the
        // display and replace them with the LEDs.
        //
        WidgetRemove((tWidget *)&g_sBtnContainer);
        WidgetAdd((tWidget *)&g_sBackground,
                  (tWidget *)&g_sLEDContainer);
        WidgetPaint((tWidget *)&g_sBackground);

        //
        // Tell the user what we're doing now.
        //
        UpdateStatus(false, "Joining network...");

        if(!bInitialized)
        {
            //
            // Initialize the SimpliciTI stack  We keep trying to initialize until
            // we get a success return code.  This indicates that we have also
            // successfully joined the network.
            //
            while(SMPL_SUCCESS != SMPL_Init((uint8_t (*)(linkID_t))0))
            {
                ToggleLED(1);
                ToggleLED(2);
                SPIN_ABOUT_A_SECOND;
            }

            //
            // Now that we are initialized, remember not to call this again.
            //
            bInitialized = true;
        }

        //
        // Once we have joined, turn both LEDs on and tell the user what we want
        // them to do.
        //
        SetLED(1, true);
        SetLED(2, true);

        //
        // Now call the function that initiates communication in
        // the desired mode.  Note that these functions will not return
        // until communication is established or an error occurs.
        //
        if(g_ulMode == MODE_SENDER)
        {
            bSuccess = LinkTo();
        }
        else
        {
            bSuccess = LinkFrom();
        }

        //
        // If we were unsuccessfull, go back to the mode selection
        // display.
        //
        if(!bSuccess)
        {
            //
            // Remove the LEDs and show the buttons again.
            //
            WidgetRemove((tWidget *)&g_sLEDContainer);
            WidgetAdd((tWidget *)&g_sBackground, (tWidget *)&g_sBtnContainer);
            WidgetPaint((tWidget *)&g_sBackground);

            //
            // Tell the user what happened.
            //
            UpdateStatus(false, "Error establishing communication!");

            //
            // Remember that we don't have an operating mode chosen.
            //
            g_ulMode = MODE_UNDEFINED;
        }
    }
}
//*****************************************************************************
//
// Link to the access point and continue processing local button requests
// forever.  This function is called following initialization in main() and
// does not return.
//
//*****************************************************************************
static void
LinkTo(void)
{
    uint8_t     pucMsg[2];
    uint8_t     ucMisses, ucDone;
    uint8_t     ucNoAck;
    smplStatus_t eRetcode;
    unsigned long ulButton;

    UpdateStatus(false, "Linking to Access Point");

    //
    // Keep trying to link.  Flash our "LEDs" while these attempts continue.
    //
    while (SMPL_SUCCESS != SMPL_Link(&g_sLinkID))
    {
        ToggleLED(1);
        ToggleLED(2);
        SPIN_ABOUT_A_SECOND;
    }

    //
    // Turn off both LEDs now that we are linked.
    //
    SetLED(1, false);
    SetLED(2, false);

    //
    // Tell the user all is well.
    //
    UpdateStatus(false, "Link successful");

    //
    // Put the radio to sleep until a button is pressed.
    //
    SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_SLEEP, 0);

    //
    // Start of the main button processing loop.
    //
    while (1)
    {

        //
        // Grab the button press flag and clear it.  We do this since the flag
        // could be changed during the loop whenever function
        // WidgetMessageQueueProcess() is called and we don't want to miss any
        // button presses.
        //
        ulButton = g_ulButtonPressed;

        //
        // Has either button been pressed?
        //
        if (ulButton)
        {
            //
            // Clear the main button press flag.
            //
            g_ulButtonPressed = 0;

            //
            // Wake the radio up since we are about to need it.
            //
            SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_AWAKE, 0);

            /* Set TID and designate which LED to toggle */
            pucMsg[1] = ++g_ucTid;
            pucMsg[0] = (ulButton == 1) ? 1 : 2;
            ucDone = 0;
            while (!ucDone)
            {

                //
                // Remember that we have yet to receive an ack from the AP.
                //
                ucNoAck = 0;

                //
                // Try sending the message MISSES_IN_A_ROW times looking for an
                // ack after each transmission.
                //
                for (ucMisses = 0; ucMisses < MISSES_IN_A_ROW; ucMisses++)
                {
                    //
                    // Send the message and request acknowledgement.
                    //
                    eRetcode=SMPL_SendOpt(g_sLinkID, pucMsg, sizeof(pucMsg),
                                          SMPL_TXOPTION_ACKREQ);

                    //
                    // Did we get the ack?
                    //
                    if (eRetcode == SMPL_SUCCESS)
                    {
                        //
                        // Yes - Message acked.  We're done.  Toggle LED 1 to
                        // indicate ack received. */
                        ToggleLED(1);
                        break;
                    }

                    //
                    // Did we send the message but fail to get an ack back?
                    //
                    if (SMPL_NO_ACK == eRetcode)
                    {
                        //
                        // Count ack failures.  Could also fail because of CCA
                        // and we don't want to scan in this case.
                        //
                        ucNoAck++;
                    }
                }

                //
                // Did we fail to get an ack after every transmission?
                //
                if (MISSES_IN_A_ROW == ucNoAck)
                {
                    //
                    // Tell the user what happened.
                    //
                    UpdateStatus(false, "Channel changed?");

                    //
                    // Message not acked.  Toggle LED 2.
                    //
                    ToggleLED(2);

#ifdef FREQUENCY_AGILITY
                    //
                    // At this point, we assume we're on the wrong channel so
                    // look for the correct channel by using Ping to initiate a
                    // scan when it gets no reply.  With a successful ping try
                    // sending the message again.  Otherwise, for any error we
                    // get we will wait until the next button press to try
                    // again.
                    //
                    if (SMPL_SUCCESS != SMPL_Ping(g_sLinkID))
                    {
                        ucDone = 1;
                    }
#else
                    ucDone = 1;
#endif  /* FREQUENCY_AGILITY */
                }
                else
                {
                    //
                    // We got the ack so drop out of the transmit loop.
                    //
                    ucDone = 1;

                    UpdateStatus(false, "Toggled AP LED %d", ulButton);
                }
            }

            //
            // Now that we are finished with it, put the radio back to sleep.
            //
            SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_SLEEP, 0);
        }

        //
        // Process the widget message queue.
        //
        WidgetMessageQueueProcess();
    }
}
Exemple #10
0
int main(void)
{
	char interruptFlag=0 , answerReceivedFlag = 0 ;
	char i ;
	uint16_t ret , rssivalue;
	
	int dataLength ;
	unsigned char baseStationNumber;
	uint8_t temp =0;
	//_delay_ms(5000);
	micro_Initialize();
	resetGlobalIntrrupt();
	ResetSearchArray();
	//while(1)
	//{
		//DDRB = 0xFF;
		//PORTB =0xFF;
	//}
	
	transceiver.setMode(TRANSCEIVER_MODE_RECEIVER);
	for (i=0;i<3 ;i++)
	{
		setLED(i);
		_delay_ms(50);
		resetLED(i);
		_delay_ms(50);
	}
	
	_delay_ms(100);
	if( (PIND & 0x04) >> 2)
	setLED(0);

	_delay_ms(100);
	setLED(0);
	setGlobalIntrrupt();
	
	baseStationNumber =0;
	//eeprom_write_byte(&test_index2 , test_index2);
	//
	//temp = eeprom_is_ready();
	////eeprom_write_byte(0x5,(uint8_t)0xA4);
	////eeprom_write_byte(&test_index2 , 0x9E);
	////test_index2	= 0x4D;
	//temp = eeprom_read_byte(&test_index2);
	////temp = eeprom_read_byte(&test_index2);
	//while(1)
	//{
	////serial.putChar(0x5A);
	//if (serialRxDataBuffer.getFifoFullLength() > 0)
	//{
	//ret = serialRxDataBuffer.readByte() ;
	//if (temp == ret)
	//{
	//;
	//}
	//else
	//eeprom_update_byte(&test_index2 , ret);
	//}
	//
	////temp = 0;
	////if ( temp == test_index2)
	////;
	////else
	//////test_index2 = temp;
	//serial.putChar(temp);
	////serial.putChar(test_index2);
	//}
	 minimumSearchBaseStationIndex =-1; 
	 maximumSearchBaseStationIndex =-1;
	 automaticSearchModeFlag = 0;	 
	while (1)
	{

		processSerialReceivedBytes();
		
		if ((serialTxDataBuffer.getFifoFullLength() > 0 ) )
			if (serial.isSerialTxEmpty())
				serial.putChar(serialTxDataBuffer.readByte());
				
		if(commandRecievedFlag)
			ToggleLED(0);
		if (transceiver.isReceiver())
		{
			
			if (transceiver.isPreambleDetected())
			{
				rssivalue = transceiver.adfReadback(RSSI_READBACK);
				//rssivalue = 0x34E5;
			}
			
			if (transceiver.getFifoFullLength() > PACKET_LENGTH - 1  )
			{
				
				transceiver.readReceivedPacket(receivedPacket);
				resetLED(2);
				
				if (packetProcessor.extractData(receivedPacket , dataLength))
				{			
					ToggleLED(1);
					StationInfoStructure* structPtr = (StationInfoStructure*) receivedPacket;
					structPtr->rssiCenterStation = rssivalue ;
					receivedDataProcess(receivedPacket , dataLength);
					answerReceivedFlag = 1;
				}
				
			}
			else if ((timeoutCounter > 2500) || answerReceivedFlag )   //timeout counter must be bigger than 1889 for baudrate 9600;
			{
				if(!commandRecievedFlag)
				{
					if (automaticSearchModeFlag)
					{
						if ( !answerReceivedFlag)
						{
							;//serialTxDataBuffer.writeString("$CMD" , sizeof("$CMD"));
							//serialTxDataBuffer.writeByte(0);
						}
						
						sendAlliveSerialData();

						if (searchdelaycounterL <= 0 && searchdelaycounterH <= 0)
						{
							ToggleLED(1);
							int nextindex = -1;
							for (int i = searchindex+1; i <= searchpointer; i++)
							{
								//serial.getChar(searchingarray[i]);
								if (searchingarray[i] != -1)
								{
									nextindex = i;
									break;
								}
							}
							if (nextindex != -1)
							{
								searchindex = nextindex;
								//serial.putChar('X');
								//serial.putChar(searchindex);
								//serial.putChar(searchingarray[searchindex]);
								madeGetStatusCommandBaseOnMACAddress(searchingarray[searchindex]);
							}
							else
							{
								searchindex = -1;
								searchdelaycounterH = searchdelaymaxH;
								searchdelaycounterL = searchdelaymaxL;
							}
														
							commandRecievedFlag = 1;
						}
						else
						{
							//if (searchdelaycounter > -1)
								//searchdelaycounter--;
							//else
								//searchdelaycounter = searchdelaymax;
							//if (searchdelaycounterH == 0)
							ToggleLED(2);
						}
						
					}
					 
				}
				else
				{
					if ( !answerReceivedFlag)
					{
						;//serialTxDataBuffer.writeString("$CMD" , sizeof("$CMD"));
						//serialTxDataBuffer.writeByte(0);
					}
					
				}

				answerReceivedFlag = 0;
				timeoutCounter =0;
				
				if (commandRecievedFlag)
				{
					interruptFlag = resetAndStoreIntrruptFlag();
					transceiver.changeMode();
					
					packetProcessor.createPacket(commandArray , commandArray[MAXIMUM_NUMBER_OF_DATA] , commandPacket);
					transceiver.writePacket(commandPacket);
					commandRecievedFlag	= 0;
					restoreIntrrupt(interruptFlag);
				}
				else
					sendAlliveSerialData();
			}
			else
			{
				;//_delay_us(10);
				
				
			}
		}
		else
		{
			setLED(2);
			if (transceiver.getFifoFullLength() == 0 )
				transceiver.changeMode();	
				//{
					//packetProcessor.createPacket((char *)commandRecievedFlag , 1 , commandPacket);
					//transceiver.writePacket(commandPacket);	
				//}//

		}
		
	}
}
//*****************************************************************************
//
// This function attempts to link to another SimpliciTI device by sending a
// link request.
//
//*****************************************************************************
tBoolean
LinkTo(void)
{
    smplStatus_t eRetcode;
    unsigned long ulCount;

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

    //
    // Tell SimpliciTI to try to link to an access point.
    //
    for(ulCount = 1; ulCount <= 10; ulCount++)
    {
        //
        // Update the displayed count.  Note that we must process the widget
        // message queue here to ensure that the change makes it onto the
        // display.
        //
        UpdateStatus(false, "Link request %d (%s)", ulCount,
                     (ulCount > 1) ? MapSMPLStatus(eRetcode) : "Waiting");
        WidgetMessageQueueProcess();

        //
        // Try to link to the access point.
        //
        eRetcode = SMPL_Link(&sLinkID);
        if(eRetcode == SMPL_SUCCESS)
        {
            break;
        }

        //
        // Wait a bit before trying again.
        //
        NWK_DELAY(1000);

        //
        // Toggle both the LEDs
        //
        ToggleLED(1);
        ToggleLED(2);
    }

    //
    // Did we manage to link to the access point?
    //
    if(eRetcode == SMPL_SUCCESS)
    {
        //
        // Tell the user how we got on.
        //
        UpdateStatus(false, "Link successful.");
        SetLED(2, false);

        //
        // Turn on RX. Default is off.
        //
        SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_RXON, 0);

        //
        // Set the time at which we have to send the next packet to our peer to
        // one second in the future.
        //
        g_ulNextPacketTick = g_ulSysTickCount + TICKS_PER_SECOND;

        //
        // Tell the main loop that we established communication successfully.
        //
        return(true);
    }
    else
    {
        UpdateStatus(false, "Failed to link.");

        //
        // Tell the main loop that we failed to establish communication.
        //
        return(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();
    }
}
Exemple #13
0
void main(void)
{
	WDT_A_hold(WDT_A_BASE);
	memset(psaData,0,8);

	while (1) {
		switch (nextState) {
		case InituProc:
			curState=InituProc;

			uProcConfig();
			PSAConfig();
			CSaAFConfig();

			nextState=InitHW;
			break;
		case InitHW:
			curState=InitHW;

			simType=SimNone;
			PSAInit();
			CSaAFInit();
			PSASetMode(PSANormal);
			PSAEnableTransfer(true);
			//IRQ handler will set this to true
			goodTransfer=false;
			totalTestLEDLoops=SIMNONE_LEDTEST_LOOPS;
			totalTXLEDLoops=SIMNONE_LEDTX_LOOPS;

			nextState=Ready;
			break;
		case Ready:
			curState=Ready;

			if (startLEDcycle) {
				if (simType==SimNone) {
					SetLED(TEST_LED_PORT, TEST_LED_PIN,false);
					SetLED(TRANSFER_LED_PORT,TRANSFER_LED_PIN,true);
				} else {
					SetLED(TEST_LED_PORT, TEST_LED_PIN,true);
				}
				curTestLEDLoops=0;
				curTXLEDLoops=0;
				ledTestToggle=false;
				startLEDcycle=false;
			}
			if (ledTXToggle) {
				ToggleLED(TRANSFER_LED_PORT, TRANSFER_LED_PIN);
				ledTXToggle=false;
			}


			if (ledTestToggle) {
				ToggleLED(TEST_LED_PORT, TEST_LED_PIN);
				ledTestToggle=false;
			}

			if (!goodTransfer && simType==SimNone) {
				nextState=UpdateBadTXData;
				readyForBadTXData=true;

			} else if (resetBtn) {
				nextState=InitHW;
				resetBtn=false;
			} else if (testBtn) {
				if (simType==SimNone) {
					//next sim type is ADS1198 test signal
					nextState=InitPSATest;
				} else if (simType==SimHW) {
					//next sim type is Launchpad generated signal
					nextState=StartSimIRQ;
				} else {
					nextState=InitHW;
				}
				testBtn=false;
			} else if (readyForSimUpdate) {
				nextState=UpdateSimData;
				readyForSimUpdate=false;
			} else if (readyForPSAData) {
				nextState=ReadFromPSA;
				readyForPSAData=false;
			} else if (readyForBadTXData) {
				nextState=UpdateBadTXData;
				readyForBadTXData=false;
			}

			break;
		case ReadFromPSA:
			curState=ReadFromPSA;

			PSARead(psaData);

			nextState=WriteToCSaAF;
			break;
		case WriteToCSaAF:
			curState=WriteToCSaAF;

			CSaAFWrite(psaData);

			nextState=Ready;
			break;
		case StartSimIRQ:
			curState=StartSimIRQ;

			//1ms "master" clock is resused for simulation
			PSAEnableTransfer(false);
			totalTestLEDLoops=SIMSW_LEDTEST_LOOPS;
			goodTransfer=false;
			simType=SimSW;
			nextState=Ready;
			break;
		case UpdateSimData:
			curState=UpdateSimData;

			static uint32_t last_val_change=0;
			if (timer_ms-last_val_change>=SIM_HALFPERIOD) {
				GenPulseData(SIM_AMP);
				last_val_change=timer_ms;
			}

			nextState=WriteToCSaAF;
			break;
		case UpdateBadTXData:
			curState=UpdateBadTXData;
			static uint32_t last_pulse_change=0;
			static uint32_t last_txval_change=0;
			static bool STAGE_PULSE=true;


			if (timer_ms-last_txval_change>=BADTX_HALFPERIOD) {
				if (STAGE_PULSE) {
					GenPulseData(BADTX_AMP);
				} else{
					//memset only copies uint8
					memset(psaData,0,16);
				}

				last_txval_change=timer_ms;
			}
			if (timer_ms-last_pulse_change>=BADTX_HALFPERIOD*BADTX_PULSES*2) {
				STAGE_PULSE=!STAGE_PULSE;
				last_pulse_change=timer_ms;
			}

			nextState=WriteToCSaAF;
			break;
		case InitPSATest:
			curState=InitPSATest;

			PSASetMode(PSATest);
			PSAEnableTransfer(true);
			simType=SimHW;
			totalTestLEDLoops=SIMHW_LEDTEST_LOOPS;

			nextState=Ready;
			break;
		default:
			break;
		}
	}
}
//*****************************************************************************
//
// 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();
}
//*****************************************************************************
//
// Main application entry function.
//
//*****************************************************************************
int
main(void)
{
    tBoolean bRetcode;
    bspIState_t intState;
    uint8_t ucLastChannel;

    //
    // 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, "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(true, "Waiting for a device...");

    //
    // Initialize the SimpliciTI stack and register our receive callback.
    //
    SMPL_Init(ReceiveCallback);

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

    //
    // Do nothing after this - the SimpliciTI stack code handles all the
    // access point function required.
    //
    while(1)
    {
        //
        // 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 (g_ucJoinSem && (g_ucNumCurrentPeers < NUM_CONNECTIONS))
        {
            //
            // Listen for a new incoming connection.
            //
            while (1)
            {
                if (SMPL_SUCCESS == SMPL_LinkListen(&g_sLID[g_ucNumCurrentPeers]))
                {
                    //
                    // The connection attempt succeeded so break out of the
                    // loop.
                    //
                    break;
                }

                //
                // Process our widget message queue.
                //
                WidgetMessageQueueProcess();

                //
                // A "real" application would implement its fail-to-link
                // policy here.  We go back and listen again.
                //
            }

            //
            // Increment our peer counter.
            //
            g_ucNumCurrentPeers++;

            //
            // Decrement the join semaphore.
            //
            BSP_ENTER_CRITICAL_SECTION(intState);
            g_ucJoinSem--;
            BSP_EXIT_CRITICAL_SECTION(intState);

            //
            // Tell the user how many devices we are now connected to.
            //
            UpdateStatus(false, "%d devices connected.", g_ucNumCurrentPeers);
        }

        //
        // Have we received a frame on one of the ED connections? We don't use
        // a critical section here since it doesn't really matter much if we
        // miss a poll.
        //
        if (g_ucPeerFrameSem)
        {
            uint8_t     pucMsg[MAX_APP_PAYLOAD], ucLen, ucLoop;

            /* process all frames waiting */
            for (ucLoop = 0; ucLoop < g_ucNumCurrentPeers; ucLoop++)
            {
                //
                // Receive the message.
                //
                if (SMPL_SUCCESS == SMPL_Receive(g_sLID[ucLoop], pucMsg,
                                                 &ucLen))
                {
                    //
                    // ...and pass it to the function that processes it.
                    //
                    ProcessMessage(g_sLID[ucLoop], pucMsg, ucLen);

                    //
                    // Decrement our frame semaphore.
                    //
                    BSP_ENTER_CRITICAL_SECTION(intState);
                    g_ucPeerFrameSem--;
                    BSP_EXIT_CRITICAL_SECTION(intState);
                }
            }
        }

        //
        // Have we been asked to change channel?
        //
        ucLastChannel = g_ucChannel;
        if (g_bChangeChannel)
        {
            //
            // Yes - go ahead and change to the next radio channel.
            //
            g_bChangeChannel = false;
            ChangeChannel();
        }
        else
        {
            //
            // No - check to see if we need to automatically change channel
            // due to interference on the current one.
            //
            CheckChangeChannel();
        }

        //
        // If the channel changed, update the display.
        //
        if(g_ucChannel != ucLastChannel)
        {
            UpdateStatus(false, "Changed to channel %d.", g_ucChannel);
        }

        //
        // If required, blink the "LEDs" to indicate we are waiting for a
        // message following a channel change.
        //
        BSP_ENTER_CRITICAL_SECTION(intState);
        if (g_ulBlinky)
        {
            if (++g_ulBlinky >= 0xF)
            {
                g_ulBlinky = 1;
                ToggleLED(1);
                ToggleLED(2);
            }
        }
        BSP_EXIT_CRITICAL_SECTION(intState);

        //
        // Process our widget message queue.
        //
        WidgetMessageQueueProcess();
    }
}
//*****************************************************************************
//
// This is the main loop for the application.
//
//*****************************************************************************
int
main(void)
{
    //
    // If running on Rev A2 silicon, turn the LDO voltage up to 2.75V.  This is
    // a workaround to allow the PLL to operate reliably.
    //
    if(REVISION_IS_A2)
    {
        SysCtlLDOSet(SYSCTL_LDO_2_75V);
    }

    //
    // Set the clocking to run directly from the PLL at 50MHz.
    //
    SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                   SYSCTL_XTAL_8MHZ);

    //
    // Configure CAN 0 Pins.
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    GPIOPinTypeCAN(GPIO_PORTD_BASE, GPIO_PIN_0 | GPIO_PIN_1);

    //
    // Configure LED pin.
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);

    //
    // Configure GPIO Pin used for the LED.
    //
    GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_2);

    //
    // Turn off the LED.
    //
    GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, 0);

    //
    // Enable the CAN controller.
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_CAN0);

    //
    // Reset the state of all the message object and the state of the CAN
    // module to a known state.
    //
    CANInit(CAN0_BASE);

    //
    // Configure the bit rate for the CAN device, the clock rate to the CAN
    // controller is fixed at 8MHz for this class of device and the bit rate is
    // set to CAN_BITRATE.
    //
    CANBitRateSet(CAN0_BASE, 8000000, CAN_BITRATE);

    //
    // Take the CAN0 device out of INIT state.
    //
    CANEnable(CAN0_BASE);

    //
    // Enable interrupts from CAN controller.
    //
    CANIntEnable(CAN0_BASE, CAN_INT_MASTER | CAN_INT_ERROR);

    //
    // Enable interrupts for the CAN in the NVIC.
    //
    IntEnable(INT_CAN0);

    //
    // Enable processor interrupts.
    //
    IntMasterEnable();

    //
    // Set the initial state to wait for data.
    //
    g_sCAN.eState = CAN_WAIT_RX;

    //
    // Reset the buffer pointer.
    //
    g_sCAN.MsgObjectRx.pucMsgData = g_sCAN.pucBuffer;

    //
    // Set the total number of bytes expected.
    //
    g_sCAN.ulBytesRemaining = CAN_FIFO_SIZE;

    //
    // Configure the receive message FIFO.
    //
    CANReceiveFIFO(g_sCAN.pucBuffer, CAN_FIFO_SIZE);

    //
    // Initialized the LED toggle count.
    //
    g_ulLEDCount = 0;

    //
    // Loop forever.
    //
    while(1)
    {
        switch(g_sCAN.eState)
        {
            case CAN_IDLE:
            {
                //
                // Switch to sending state.
                //
                g_sCAN.eState = CAN_SENDING;

                //
                // Initialize the transmit count to zero.
                //
                g_sCAN.ulBytesTransmitted = 0;

                //
                // Schedule all of the CAN transmissions.
                //
                CANTransmitFIFO(g_sCAN.pucBuffer, CAN_FIFO_SIZE);

                break;
            }
            case CAN_SENDING:
            {
                //
                // Wait for all bytes to go out.
                //
                if(g_sCAN.ulBytesTransmitted == CAN_FIFO_SIZE)
                {
                    //
                    // Switch to wait for RX state.
                    //
                    g_sCAN.eState = CAN_WAIT_RX;
                }

                break;
            }
            case CAN_WAIT_RX:
            {
                //
                // Wait for all new data to be received.
                //
                if(g_sCAN.ulBytesRemaining == 0)
                {
                    //
                    // Switch to wait for Process data state.
                    //
                    g_sCAN.eState = CAN_PROCESS;

                    //
                    // Reset the buffer pointer.
                    //
                    g_sCAN.MsgObjectRx.pucMsgData = g_sCAN.pucBuffer;

                    //
                    // Reset the number of bytes expected.
                    //
                    g_sCAN.ulBytesRemaining = CAN_FIFO_SIZE;
                }
                break;
            }
            case CAN_PROCESS:
            {
                //
                // Handle the LED toggle.
                //
                ToggleLED();

                //
                // Return to the idle state.
                //
                g_sCAN.eState = CAN_IDLE;

                break;
            }
            default:
            {
                break;
            }
        }
    }
}
//*****************************************************************************
//
// Main application entry function.
//
//*****************************************************************************
int
main(void)
{
    tBoolean bRetcode;
    smplStatus_t eRetcode;

    //
    // Set the system clock to run at 50MHz from the PLL
    //
    MAP_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;
    }

    //
    // Tell the user what's up.
    //
    UpdateStatus("Range Extender active.");

    //
    // Do nothing after this - the SimpliciTI stack code handles all the
    // access point function required.
    //
    while(1)
    {
        //
        // Process the widget message queue.
        //
        WidgetMessageQueueProcess();
    }
}
//*****************************************************************************
//
// Main application entry function.
//
//*****************************************************************************
int
main(void)
{
    tBoolean bSuccess, bRetcode;
    unsigned char pucMsg[2];
    unsigned char ucTid;
    unsigned char ucDelay;
    unsigned long ulLastRxCount, ulLastTxCount;
    smplStatus_t eRetcode;

    //
    // 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, "Please choose the operating mode.");

    //
    // 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();
    if(!bRetcode)
    {
        //
        // The board does not have a MAC address configured so we can't set
        // the SimpliciTI device address (which we derive from the MAC address).
        //
        while(1);
    }

    //
    // Initialize the SimpliciTI stack and supply our receive callback
    // function pointer.
    //
    SMPL_Init(RxCallback);

    //
    // Initialize our message ID, initial inter-message delay and packet
    // counters.
    //
    ucTid = 0;
    ucDelay = 0;
    ulLastRxCount = 0;
    ulLastTxCount = 0;

    //
    // Fall into the command line processing loop.
    //
    while (1)
    {
        //
        // Process any messages from or for the widgets.
        //
        WidgetMessageQueueProcess();

        //
        // Check to see if we've been told to do anything.
        //
        if(g_ulCommandFlags)
        {
            //
            // Has the mode been set?  If so, set up the display to show the
            // "LEDs" and then start communication.
            //
            if(HWREGBITW(&g_ulCommandFlags, COMMAND_MODE_SET))
            {
                //
                // Clear the bit now that we have seen it.
                //
                HWREGBITW(&g_ulCommandFlags, COMMAND_MODE_SET) = 0;

                //
                // Remove the buttons and replace them with the LEDs then
                // repaint the display.
                //
                WidgetRemove((tWidget *)&g_sBtnContainer);
                WidgetAdd((tWidget *)&g_sBackground,
                          (tWidget *)&g_sLEDContainer);
                WidgetPaint((tWidget *)&g_sBackground);

                //
                // Now call the function that initiates communication in
                // the desired mode.  Note that these functions will not return
                // until communication is established or an error occurs.
                //
                if(g_ulMode == MODE_TALKER)
                {
                    bSuccess = LinkTo();
                }
                else
                {
                    bSuccess = LinkFrom();
                }

                //
                // If we were unsuccessfull, go back to the mode selection
                // display.
                //
                if(!bSuccess)
                {
                    //
                    // Remove the LEDs and show the buttons again.
                    //
                    WidgetRemove((tWidget *)&g_sLEDContainer);
                    WidgetAdd((tWidget *)&g_sBackground,
                              (tWidget *)&g_sBtnContainer);
                    WidgetPaint((tWidget *)&g_sBackground);

                    //
                    // Tell the user what happened.
                    //
                    UpdateStatus(false, "Error establishing communication!");
                    UpdateStatus(true, "Please choose the operating mode.");

                    //
                    // Remember that we don't have an operating mode chosen.
                    //
                    g_ulMode = MODE_UNDEFINED;
                }
            }

            //
            // Have we been asked to toggle the first "LED"?
            //
            if(HWREGBITW(&g_ulCommandFlags, COMMAND_LED1_TOGGLE))
            {
                //
                // Clear the bit now that we have seen it.
                //
                HWREGBITW(&g_ulCommandFlags, COMMAND_LED1_TOGGLE) = 0;

                //
                // Toggle the LED.
                //
                ToggleLED(1);
            }

            //
            // Have we been asked to toggle the second "LED"?
            //
            if(HWREGBITW(&g_ulCommandFlags, COMMAND_LED2_TOGGLE))
            {
                //
                // Clear the bit now that we have seen it.
                //
                HWREGBITW(&g_ulCommandFlags, COMMAND_LED2_TOGGLE) = 0;

                //
                // Toggle the LED.
                //
                ToggleLED(2);
            }

            //
            // Have we been asked to send a packet back to our peer?  This
            // command is only ever sent to the main loop when we are running
            // in listener mode (LinkListen).
            //
            if(HWREGBITW(&g_ulCommandFlags, COMMAND_SEND_REPLY))
            {
                //
                // Clear the bit now that we have seen it.
                //
                HWREGBITW(&g_ulCommandFlags, COMMAND_SEND_REPLY) = 0;

                //
                // Create the message.  The first byte tells the receiver to
                // toggle LED1 and the second is a sequence counter.
                //
                pucMsg[0] = 1;
                pucMsg[1] = ++ucTid;
                eRetcode = SMPL_Send(sLinkID, pucMsg, 2);

                //
                // Update our transmit counter if we transmitted the packet
                // successfully.
                //
                if(eRetcode == SMPL_SUCCESS)
                {
                    g_ulTxCount++;
                }
                else
                {
                    UpdateStatus(false, "TX error %s (%d)", MapSMPLStatus(eRetcode),
                                 eRetcode);
                }
            }
        }

        //
        // If we are the talker (LinkTo mode), check to see if it's time to
        // send another packet to our peer.
        //
        if((g_ulMode == MODE_TALKER) &&
           (g_ulSysTickCount >= g_ulNextPacketTick))
        {
            //
            // Create the message.  The first byte tells the receiver to
            // toggle LED1 and the second is a sequence counter.
            //
            pucMsg[0] = 1;
            pucMsg[1] = ++ucTid;
            eRetcode = SMPL_Send(sLinkID, pucMsg, 2);

            //
            // Update our transmit counter if we transmitted the packet
            // correctly.
            //
            if(eRetcode == SMPL_SUCCESS)
            {
                g_ulTxCount++;
            }
            else
            {
                UpdateStatus(false, "TX error %s (%d)", MapSMPLStatus(eRetcode),
                             eRetcode);
            }

            //
            // Set the delay before the next message.
            //
#ifndef USE_2_SECOND_DELAY
            //
            // Set the delay before the next message.  We increase this from 1
            // second to 4 seconds then cycle back to 1.
            //
            ucDelay = (ucDelay == 4) ? 1 : (ucDelay + 1);
#else
            //
            // Wait 2 seconds before sending the next message.
            //
            ucDelay = 2;
#endif

            //
            // Calculate the system tick count when our delay has completed.
            // This algorithm will generate a spurious packet every 13.7 years
            // since I don't handle the rollover case in the comparison above
            // but I'm pretty sure you will forgive me for this oversight.
            //
            g_ulNextPacketTick = g_ulSysTickCount +
                                 (TICKS_PER_SECOND * ucDelay);
        }

        //
        // If either the transmit or receive packet count changed, update
        // the status on the display.
        //
        if((g_ulRxCount != ulLastRxCount) || (g_ulTxCount != ulLastTxCount))
        {
            ulLastTxCount = g_ulTxCount;
            ulLastRxCount = g_ulRxCount;
            UpdateStatus(false, "Received %d pkts, sent %d (%d)",
                         ulLastRxCount, ulLastTxCount);
        }
    }
}
//*****************************************************************************
//
// This function listens for a link request from another SimpliciTI device.
//
//*****************************************************************************
tBoolean
LinkFrom(void)
{
    linkID_t linkID1;
    uint8_t  pucMsg[MAX_APP_PAYLOAD], ucLen, ucLtid;
    unsigned long ulCount;
    smplStatus_t eRetcode;

    //
    // Tell the user what we're doing.
    //
    UpdateStatus(false, "Listening for link...");

    //
    // Keep the compiler happy.
    //
    eRetcode = SMPL_TIMEOUT;

    //
    // Turn on LED 1 to indicate that we are listening.
    //
    SetLED(1, true);

    //
    // Listen for link for 10 seconds or so.  This logic may fail if you
    // happen to have sat around for about 13.6 years between starting the
    // example and pressing the mode selection button.  I suspect I will be
    // forgiven for this.
    //
    ulCount = g_ulSysTickCount + (LINK_TIMEOUT_SECONDS * TICKS_PER_SECOND);
    while (ulCount > g_ulSysTickCount)
    {
        //
        // Process our message queue to keep the widget library happy.
        //
        WidgetMessageQueueProcess();

        //
        // Listen for a link.  This call takes quite some time to return.
        //
        eRetcode = SMPL_LinkListen(&linkID1);

        //
        // Was the link successful?
        //
        if (SMPL_SUCCESS == eRetcode)
        {
            //
            // Yes - drop out of the loop.
            //
            break;
        }
    }

    //
    // Did we link successfully?
    //
    if(eRetcode != SMPL_SUCCESS)
    {
        //
        // No - Tell the user what happened and return an error.
        //
        UpdateStatus(false, "Failed to link!");
        return(false);
    }

    //
    // Turn off LED 1 to indicate that our listen succeeded.
    //
    UpdateStatus(false, "Link succeeded.");
    SetLED(1, false);

    //
    // Clear our message counter.
    //
    ulCount = 0;

    //
    // Enter an infinite loop polling for messages.
    //
    while (1)
    {
        //
        // Turn the radio off and pretend to sleep for a second or so.
        //
        SMPL_Ioctl(IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_SLEEP, 0);
        SPIN_ABOUT_A_SECOND;  /* emulate MCU sleeping */

        //
        // Turn the radio back on again.
        //
        SMPL_Ioctl(IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_AWAKE, 0);

        //
        // Were any messages "received"?
        //
        // The receive call results in polling the Access Point.  The success
        // case occurs when a payload is actually returned.  When there is no
        // frame waiting for the device a frame with no payload is returned by
        // the Access Point.  Note that this loop will retrieve any and all
        // frames that are waiting for this device on the specified link ID.
        // This call will also return frames that were received directly.  It
        // is possible to get frames that were repeated either from the initial
        // transmission from the peer or via a Range Extender.  This is why we
        // implement the TID check.
        //
        do
        {
            //
            // Receive whatever the AP has for us.
            //
            eRetcode = SMPL_Receive(linkID1, pucMsg, &ucLen);

            //
            // Did we get a real frame?
            //
            if((eRetcode == SMPL_SUCCESS) && ucLen)
            {
                //
                // Tell the user what's going on.
                //
                UpdateStatus(false, "Received msg %d", ++ulCount);

                //
                // Process our message queue to keep the widget library happy.
                //
                WidgetMessageQueueProcess();

                //
                // Check the application sequence number to detect late or missing
                // frames.
                //
                ucLtid = *(pucMsg+1);
                if (ucLtid)
                {
                    //
                    // If the current TID is non-zero and the last one we saw was
                    // less than this one assume we've received the 'next' one.
                    //
                    if (g_ucTid < ucLtid)
                    {
                        //
                        // 'Next' frame.  We may have missed some but we don't
                        // care.
                        //
                        if ((*pucMsg == 1) || (*pucMsg == 2))
                        {
                            //
                            // We're good. Toggle the requested LED.
                            //
                            ToggleLED(*pucMsg);
                        }

                        //
                        // Remember the last TID.
                        //
                        g_ucTid = ucLtid;
                    }

                    //
                    // If current TID is non-zero and less than or equal to the last
                    // one we saw assume we received a duplicate.  Just ignore it.
                    //
                }
                else
                {
                    //
                    // Current TID is zero so the count wrapped or we just started.
                    // Let's just accept it and start over.
                    //
                    if ((*pucMsg == 1) || (*pucMsg == 2))
                    {
                        //
                        // We're good. Toggle the requested LED.
                        //
                        ToggleLED(*pucMsg);
                    }

                    //
                    // Remember the last TID.
                    //
                    g_ucTid = ucLtid;
                }
            }
        } while ((eRetcode == SMPL_SUCCESS) & ucLen);
    }
}
//*****************************************************************************
//
// 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);
                    }
                }
            }
        }
    }
}
//*****************************************************************************
//
// This function attempts to link to another SimpliciTI device by sending a
// link request.
//
//*****************************************************************************
tBoolean
LinkTo(void)
{
    linkID_t linkID1;
    uint8_t  pucMsg[2], ucWrap;
    unsigned long ulCount;
    smplStatus_t eRetcode;

    //
    // Our message counter hasn't wrapped.
    //
    ucWrap = 0;

    //
    // Turn on LED 2
    //
    SetLED(2, true);

    //
    // Tell the user what we're doing.
    //
    UpdateStatus(false, "Attempting to link...");

    //
    // Try to link for about 10 seconds.
    //
    for(ulCount = 0; ulCount < LINK_TIMEOUT_SECONDS; ulCount++)
    {
        //
        // Try to link.
        //
        eRetcode = SMPL_Link(&linkID1);

        //
        // Did we succeed?
        //
        if(eRetcode == SMPL_SUCCESS)
        {
            //
            // Yes - drop out of the loop.
            //
            break;
        }

        //
        // We didn't link so toggle the LEDs, wait a bit then try again.
        //
        ToggleLED(1);
        ToggleLED(2);
        SPIN_ABOUT_A_SECOND;
    }

    //
    // Did the link succeed?
    //
    if(eRetcode != SMPL_SUCCESS)
    {
        //
        // No - return an error code.
        //
        UpdateStatus(false, "Failed to link!");
        return(false);
    }
    else
    {
        UpdateStatus(false, "Link succeeded.");
    }

    //
    // Turn off the second LED now that we have linked.
    //
    SetLED(2, false);

#ifdef FREQUENCY_AGILITY
    //
    // The radio comes up with Rx off. If Frequency Agility is enabled we need
    // it to be on so we don't miss a channel change broadcast.  We need to
    // hear this since this application has no ack.  The broadcast from the AP
    // is, therefore, the only way to find out about a channel change.
    //
    SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_RXON, 0);
#endif

    //
    // Set up the initial message and message counter.
    //
    pucMsg[0] = 2;
    pucMsg[1] = ++g_ucTid;
    ulCount = 0;

    //
    // We've linked successfully so drop into an infinite loop during which
    // we send messages to the receiver every 5 seconds or so.
    //
    while (1)
    {
        //
        // Send a message every 5 seconds. This could be emulating a sleep.
        //
#ifndef FREQUENCY_AGILITY
        //
        // If Frequency Agility is disabled we don't need to listen for the
        // broadcast channel change command.
        //
        SMPL_Ioctl(IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_SLEEP, 0);
#endif

        //
        // Kill about 5 seconds.
        //
        SPIN_ABOUT_A_SECOND;
        SPIN_ABOUT_A_SECOND;
        SPIN_ABOUT_A_SECOND;
        SPIN_ABOUT_A_SECOND;
        SPIN_ABOUT_A_SECOND;

#ifndef FREQUENCY_AGILITY
        //
        // See comment above...If Frequency Agility is not enabled we never
        // listen so it is OK if we just awaken leaving Rx off.
        //
        SMPL_Ioctl(IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_AWAKE, 0);
#endif

        //
        // Send a message.
        //
        eRetcode = SMPL_Send(linkID1, pucMsg, sizeof(pucMsg));
        if (SMPL_SUCCESS == eRetcode)
        {
            //
            // Toggle LED 1 to indicate that we sent something.
            //
            ToggleLED(1);

            //
            // Set up the next message.  Every 8th message toggle LED 1 instead
            // of LED 2 on the receiver.
            //
            pucMsg[0] = (++ucWrap & 0x7) ? 2 : 1;
            pucMsg[1] = ++g_ucTid;
        }

        //
        // Tell the user what we did.
        //
        UpdateStatus(false, "Sent msg %d (%s).", ++ulCount,
                     MapSMPLStatus(eRetcode));
    }
}
//*****************************************************************************
//
// This is the main monitoring function for the applicaiton. It "sleeps" for
// 5 seconds or so then checks to see if there are any alerts being broadcast.
// If not, it toggles a LED and goes back to "sleep".  If an alert is received
// it switches into "babbling" mode where it retransmits the alert every 100mS
// to propagate the alert through the network.
//
// This function does not return.
//
//*****************************************************************************
void
MonitorForBadNews(void)
{
    uint8_t pucMsg[1], ucLen;
    unsigned long ulLoop;

    //
    // Turn off LEDs. Check for bad news will toggle one LED.  The other LED will
    // toggle when bad news message is sent.
    //
    SetLED(2, false);
    SetLED(1, false);

    //
    // Start with radio sleeping.
    //
    SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_SLEEP, 0);

    while (1)
    {
        //
        // Spoof MCU sleeping...
        //
        for (ulLoop = 0; ulLoop < CHECK_RATE; ulLoop++)
        {
            SPIN_ABOUT_A_SECOND;
        }

        ToggleLED(1);

        //
        // Check the "sensor" to see if we need to send an alert.
        //
        if (g_bAlarmRaised)
        {
            //
            // The sensor has been activated. Start babbling.  This function
            // will not return.
            //
            Start2Babble();
        }

        //
        // Wake up the radio and receiver so that we can listen for others
        // babbling.
        //
        SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_AWAKE, 0);
        SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_RXON, 0);

        //
        // Stay on "long enough" to see if someone else is babbling
        //
        SPIN_ABOUT_A_QUARTER_SECOND;

        //
        // We're done with the radio so shut it down.
        //
        SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_SLEEP, 0);

        //
        // Did we receive a message while the radio was on?
        //
        if (SMPL_SUCCESS == SMPL_Receive(SMPL_LINKID_USER_UUD, pucMsg, &ucLen))
        {
            //
            // Did we receive something and, if so, is it bad news?
            //
            if (ucLen && (pucMsg[0] == BAD_NEWS))
            {
                //
                // Bad news has been received so start babbling to pass the
                // alert on to the other devices in the network.
                //
                UpdateStatus(true, "Alarm received!");
                Start2Babble();
            }
        }
    }
}
//*****************************************************************************
//
// The following is the Main Application Thread.  It will Initialize the
// Bluetooth Stack and all used profiles.
//
//*****************************************************************************
static void
MainApp(void *pThreadParameter)
{
    int iPressCount;
    int iTick;
    int iVolume;
    int iRetVal;
    tDeviceInfo sDeviceInfo;
    BTPS_Initialization_t sBTPSInitialization;

    //
    // Set the callback function the stack can use for printing to the
    // console.
    //
#ifdef DEBUG_ENABLED
    sBTPSInitialization.MessageOutputCallback = MessageOutputCallback;
#else
    sBTPSInitialization.MessageOutputCallback = NULL;
#endif

    //
    // Initialize the Bluetooth stack, using no callback parameters (NULL).
    //
    iRetVal = InitializeBluetooth(BluetoothCallbackFunction, NULL,
                                  &sBTPSInitialization);

    //
    // Initialize the Graphics Module.
    //
    InitializeGraphics(ButtonPressCallback);

    //
    // Proceed with application if there was no Bluetooth init error.
    //
    if(!iRetVal)
    {
        //
        // Make the device Connectable and Discoverable and enabled Secured
        // Simple Pairing.
        //
        SetLocalDeviceMode(CONNECTABLE_MODE  | DISCOVERABLE_MODE |
                           PAIRABLE_SSP_MODE);

        //
        // Get information about our local device.
        //
        iRetVal = GetLocalDeviceInformation(&sDeviceInfo);
        if(!iRetVal)
        {
            //
            // Format the board address into a string, and display it on
            // the console.
            //
            BD_ADDRToStr(sDeviceInfo.ucBDAddr, g_cBoardAddress);
            Display(("Local BD_ADDR: %s\r\n", g_cBoardAddress));

            //
            // Display additional info about the device to the console
            //
            Display(("HCI Version  : %s\r\n",
                      g_pcHCIVersionStrings[sDeviceInfo.ucHCIVersion]));
            Display(("Connectable  : %s\r\n",
                    ((sDeviceInfo.sMode & CONNECTABLE_MODE) ? "Yes" : "No")));
            Display(("Discoverable : %s\r\n",
                    ((sDeviceInfo.sMode & DISCOVERABLE_MODE) ? "Yes" : "No")));
            if(sDeviceInfo.sMode & (PAIRABLE_NON_SSP_MODE | PAIRABLE_SSP_MODE))
            {
                Display(("Pairable     : Yes\r\n"));
                Display(("SSP Enabled  : %s\r\n",
                       ((sDeviceInfo.sMode & PAIRABLE_SSP_MODE) ?
                        "Yes" : "No")));
            }
            else
            {
                Display(("Pairable     : No\r\n"));
            }

            //
            // Show message to user on the screen
            //
            UpdateStatusBox("Waiting for Connection...");

            //
            // Bluetooth should be running now.  Enter a forever loop to run
            // the user interface on the board screen display and process
            // button presses.
            //
            iTick = ONE_SEC_COUNT;
            iVolume = DEFAULT_POWERUP_VOLUME;
            iPressCount = 0;
            while(1)
            {
                //
                // Update the screen.
                //
                ProcessGraphics();

                //
                // Wait 1/10 second.
                //
                BTPS_Delay(TENTH_SEC_COUNT);

                //
                // If one second has elapsed, toggle the LED
                //
                if(!(--iTick))
                {
                   iTick = ONE_SEC_COUNT;
                   ToggleLED(LED_PIN);
                }

                //
                // Check to see if the User Switch was pressed.
                //
                if(UserSwitchPressed())
                {
                   //
                   // Count the amount of time that the button has been
                   // pressed.
                   //
                   iPressCount++;
                }

                //
                // Else the user switch is not pressed
                //
                else
                {
                    //
                    // If the button was just released, then adjust the volume.
                    // Decrease the volume by 10% for each button press.  At
                    // zero, then reset it to 100%.
                    //
                    if(iPressCount)
                    {
                        iVolume = (iVolume == 0) ? 100 : iVolume - 10;

                        //
                        // Set the new volume, and display a message on the
                        // console
                        //
                        SoundVolumeSet(iVolume);
                        Display(("Press Count %d Volume %d\r\n", iPressCount,
                                iVolume));
                        iPressCount = 0;
                   }
                }
            }
        }
    }

    //
    // There was an error initializing Bluetooth
    //
    else
    {
        //
        // Print an error message to the console and show a message on
        // the screen
        //
        Display(("Bluetooth Failed to initialize:  Error %d\r\n", iRetVal));
        UpdateStatusBox("Failed to Initialize Bluetooth.");

        //
        // Enter a forever loop.  Continue to update the screen, and rapidly
        // blink the LED as an indication of the error state.
        //
        while(1)
        {
            ProcessGraphics();
            BTPS_Delay(500);
            ToggleLED(LED_PIN);
        }
    }
}