Exemplo n.º 1
0
void miwiProcess()
{
    // Basic counter
    // Connects rxIndex with ConnectionTable
    uint8_t rxIndex;

    if (MiApp_MessageAvailable())
    {
        // Gets Source address
        if ((rxMessage.flags.bits.srcPrsnt)&&(rxMessage.flags.bits.altSrcAddr))
        {
            // Find ConnectionTable index is linked with message Address
            for (rxIndex = 0; rxIndex < CONNECTION_SIZE; rxIndex++)
            {
                if ((rxMessage.SourceAddress[0] == ConnectionTable[rxIndex].AltAddress.v[0])&&
                    (rxMessage.SourceAddress[1] == ConnectionTable[rxIndex].AltAddress.v[1]))
                {
                    // rxIndex is the correct location
                    break;
                }
            }
            
            // Hasn't overflowed so it is in my connection table
            if (rxIndex < CONNECTION_SIZE)
            {
                pktIDX = rxIndex;
                pktCMD = rxMessage.Payload[0];
                pktMSG = rxMessage.Payload[1];  
            }
        } // End of sourceAddress present
        MiApp_DiscardMessage();        
    }
    else
    {
        if(pktIDX!=0xff) 
        {       
            uint8_t valid = 1;
            uint8_t buffer[2];
            buffer[0] = pktCMD;
            buffer[1] = pktMSG;
            
            // Send it to everyone I know
            for (rxIndex = 0; rxIndex < CONNECTION_SIZE; rxIndex++)
            {
                if ((ConnectionTable[rxIndex].status.bits.isValid)&&(rxIndex!=pktIDX))
                {
                    valid = miwiMsg(rxIndex,buffer,2);
                }
            }
            
            // if everyone got it send it to device who requested it
            if(valid)
            {
                miwiMsg(pktIDX,buffer,2);  
            }
            
            pktIDX = 0xff;
        }
    }
}
Exemplo n.º 2
0
int main(void)
{
	BYTE i; 
    GOL_MSG msg;                    // GOL message structure to interact with GOL
    
    InitializeBoard();
    
	TRISGbits.TRISG3 = 1;
	TRISGbits.TRISG2 = 0;
	Nop();
	PORTGbits.RG2 = 1;
	Nop();
	
	//RADIO SETUP
	// Function MiApp_ProtocolInit initialize the protocol stack.//
 	MiApp_ProtocolInit(FALSE);
	
	//setting the frequency at whick this wx will transmit over comes back as false if the set channel fails 
	if( MiApp_SetChannel(myChannel) == FALSE )
	{
            return 0;
    }

	//Enables all connection types
 	MiApp_ConnectionMode(ENABLE_ALL_CONN);

	//try to establish connection with peer device: p1=0xff=establish connection with any device, p2=direct connection
	//returns 0xFF if it false 
	i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT);

	if( i == 0xFF )
   	{
		//starting a connecton: direct connect, duration of scan, channel to start connection on	
		MiApp_StartConnection(START_CONN_DIRECT, 10, 24);
	}
	//END RADIO SETUP
	
    LED = 1;
//	i2cRec(2);
	
    while(1)
    {	//i2cSend(3,2);
        if(GOLDraw())               // Draw GOL object
        {
            TouchGetMsg(&msg);      // Get message from touch screen
            GOLMsg(&msg);           // Process message
        }
        
        /* MiApp_MessageAvailable returns a bool*/
		if( MiApp_MessageAvailable() )
        {
			Incoming=*rxMessage.Payload;
			/* Function MiApp_DiscardMessage is used to release the current received packet.*/
           	MiApp_DiscardMessage();
		}
	}//end while
}
Exemplo n.º 3
0
BOOL MyMIWI_RxMsg(char *theMsg) {

    int i;

    /*******************************************************************/
    // Function MiApp_MessageAvailable returns a boolean to indicate if
    //  a packet has been received by the transceiver. If a packet has
    //  been received, all information will be stored in the rxFrame,
    //  structure of RECEIVED_MESSAGE.
    /*******************************************************************/
    if( !MiApp_MessageAvailable() )
        return FALSE;

    /*******************************************************************/
    // If a packet has been received, following code prints out some of
    // the information available in rxMessage.
    /*******************************************************************/
    if( rxMessage.flags.bits.secEn )
        ConsolePutROMString((ROM char *)"Secured ");

    if( rxMessage.flags.bits.broadcast )
        ConsolePutROMString((ROM char *)"Broadcast Packet with RSSI ");
    else
        ConsolePutROMString((ROM char *)"Unicast Packet with RSSI ");

    PrintChar(rxMessage.PacketRSSI);

    if( rxMessage.flags.bits.srcPrsnt ) {
        ConsolePutROMString((ROM char *)" from ");
         if( rxMessage.flags.bits.altSrcAddr ) {
            PrintChar(rxMessage.SourceAddress[1]);
            PrintChar(rxMessage.SourceAddress[0]);
         } else {
            for(i = 0; i < MY_ADDRESS_LENGTH; i++)
                PrintChar(rxMessage.SourceAddress[MY_ADDRESS_LENGTH-1-i]);
         }
    }

    ConsolePutROMString((ROM char *)" : ");
    for(i = 0; i < rxMessage.PayloadSize; i++) {
        ConsolePut(rxMessage.Payload[i]);
        *theMsg++ = rxMessage.Payload[i];
    }
    ConsolePutROMString((ROM char *)"\n");
    *theMsg = '\0';

    /*******************************************************************/
    // Function MiApp_DiscardMessage is used to release the current
    //  received packet.
    // After calling this function, the stack can start to process the
    //  next received frame
    /*******************************************************************/
    MiApp_DiscardMessage();

    return TRUE;
}
Exemplo n.º 4
0
void Demo_Pan(void)
{
    TRISB = 0x0;
    UART_TX_TRIS = 0;
    int alarm_status = 1;
    
    while(true)
    {
        if(MiApp_MessageAvailable())
        {
            if (rxMessage.Payload[0] == DEMO_ALARM_ARMED)
            {alarm_status = 1;}
            
            if (rxMessage.Payload[0] == DEMO_ALARM_DISARMED)
            {alarm_status = 0;}
            
            if (alarm_status == 1)
            {
            if(rxMessage.Payload[0] == DEMO_ALARM_ON )
            {
                demo_gyro(1);
            }
            
            else if(rxMessage.Payload[0] == DEMO_ALARM_OFF )
            {
                
                demo_gyro(0);
                
            }
            }
        }
        MiApp_DiscardMessage();
    }
    
    
    
}
Exemplo n.º 5
0
int main(void)
#endif
{   
    BYTE i, j;
    BYTE TxSynCount = 0;
    BYTE TxNum = 0;
    BYTE RxNum = 0;
    BOOL bReceivedMessage = FALSE;
    
    /*******************************************************************/
    // Initialize the system
    /*******************************************************************/
    BoardInit();         
    ConsoleInit();    
    DemoOutput_Greeting();

    /*******************************************************************/
    // Function MiApp_ProtocolInit initialize the protocol stack. The
    // only input parameter indicates if previous network configuration
    // should be restored. In this example, if button 1 is pressed and
    // hold when powering up, we assume the user would like to enable
    // the Network Freezer and load previous network configuration
    // from NVM.
    /*******************************************************************/
    if( (PUSH_BUTTON_1 == 0) && ( MiApp_ProtocolInit(TRUE) == TRUE ) )
    {   
        DemoOutput_NetworkFreezer();
        LED_1 = 1;
        while(PUSH_BUTTON_1 == 0);
    }
    else
    {
        /*******************************************************************/
        // Function MiApp_ProtocolInit initialize the protocol stack. In 
        // this example, if button 1 is released when powering up, we assume 
        // that the user want the network to start from scratch.
        /*******************************************************************/
        MiApp_ProtocolInit(FALSE);   

        LED_1 = 0;
        LED_2 = 0;

        myChannel = 0xFF;
        DemoOutput_StartActiveScan();

        /*******************************************************************/
        // Function MiApp_SearchConnection will return the number of 
        // existing connections in all channels. It will help to decide 
        // which channel to operate on and which connection to add.
        // The return value is the number of connections. The connection 
        //     data are stored in global variable ActiveScanResults. 
        //     Maximum active scan result is defined as 
        //     ACTIVE_SCAN_RESULT_SIZE
        // The first parameter is the scan duration, which has the same 
        //     definition in Energy Scan. 10 is roughly 1 second. 9 is a 
        //     half second and 11 is 2 seconds. Maximum scan duration is 14, 
        //     or roughly 16 seconds.
        // The second parameter is the channel map. Bit 0 of the 
        //     double word parameter represents channel 0. For the 2.4GHz 
        //     frequency band, all possible channels are channel 11 to 
        //     channel 26. As the result, the bit map is 0x07FFF800. Stack 
        //     will filter out all invalid channels, so the application 
        //     only needs to pay attention to the channels that are not 
        //     preferred.
        /*******************************************************************/
        i = MiApp_SearchConnection(10, 0xFFFFFFFF);
        DemoOutput_ActiveScanResults(i);

        /*******************************************************************/
        // Function MiApp_ConnectionMode sets the connection mode for the 
        // protocol stack. Possible connection modes are:
        //  - ENABLE_ALL_CONN       accept all connection request
        //  - ENABLE_PREV_CONN      accept only known device to connect
        //  - ENABL_ACTIVE_SCAN_RSP do not accept connection request, but 
        //                          allow response to active scan
        //  - DISABLE_ALL_CONN      disable all connection request, including
        //                          active scan request
        /*******************************************************************/
        MiApp_ConnectionMode(ENABLE_ALL_CONN);
    
        if( i > 0 )
        {
            /*******************************************************************/
            // Function MiApp_EstablishConnection try to establish a new 
            // connection with peer device. 
            // The first parameter is the index to the active scan result, which 
            //      is acquired by discovery process (active scan). If the value
            //      of the index is 0xFF, try to establish a connection with any 
            //      peer.
            // The second parameter is the mode to establish connection, either 
            //      direct or indirect. Direct mode means connection within the 
            //      radio range; Indirect mode means connection may or may not 
            //      in the radio range. 
            /*******************************************************************/
            if( MiApp_EstablishConnection(0, CONN_MODE_DIRECT) == 0xFF )
            {
                DemoOutput_JoinFail();
            }
        }    
        else
        {         
            DemoOutput_EnergyScan();
            /*******************************************************************/
            // Function MiApp_StartConnection tries to start a new network
            //
            // The first parameter is the mode of start connection. There are 
            // two valid connection modes:
            //   - START_CONN_DIRECT        start the connection on current 
            //                              channel
            //   - START_CONN_ENERGY_SCN    perform an energy scan first, 
            //                              before starting the connection on 
            //                              the channel with least noise
            //   - START_CONN_CS_SCN        perform a carrier sense scan 
            //                              first, before starting the 
            //                              connection on the channel with 
            //                              least carrier sense noise. Not
            //                              supported for current radios
            //
            // The second parameter is the scan duration, which has the same 
            //     definition in Energy Scan. 10 is roughly 1 second. 9 is a 
            //     half second and 11 is 2 seconds. Maximum scan duration is 
            //     14, or roughly 16 seconds.
            //
            // The third parameter is the channel map. Bit 0 of the 
            //     double word parameter represents channel 0. For the 2.4GHz 
            //     frequency band, all possible channels are channel 11 to 
            //     channel 26. As the result, the bit map is 0x07FFF800. Stack 
            //     will filter out all invalid channels, so the application 
            //     only needs to pay attention to the channels that are not 
            //     preferred.
            /*******************************************************************/
            MiApp_StartConnection(START_CONN_ENERGY_SCN, 10, 0xFFFFFFFF);
        }
        
        // Turn on LED 1 to indicate ready to accept new connections
        LED_1 = 1;
    }
    
    DumpConnection(0xFF);
    DemoOutput_StartConnection();                    
    DemoOutput_Instruction();

    while(1)
    {
        /*******************************************************************/
        // Function MiApp_MessageAvailable will return a boolean to indicate 
        // if a message for application layer has been received by the 
        // transceiver. If a message has been received, all information will 
        // be stored in the rxMessage, structure of RECEIVED_MESSAGE.
        /*******************************************************************/
        if( MiApp_MessageAvailable() )
        {
            DemoOutput_HandleMessage();
            
            /*******************************************************************/
            // Function MiApp_DiscardMessage is used to release the current 
            // received message. After calling this function, the stack can 
            // start to process the next received message.
            /*******************************************************************/          
            MiApp_DiscardMessage();
            
            // Toggle LED2 to indicate receiving a packet.
            LED_2 ^= 1;
            bReceivedMessage = TRUE;
            
            DemoOutput_UpdateTxRx(TxNum, ++RxNum);
        }
        else
        {
            /*******************************************************************/
            // If no packet received, now we can check if we want to send out
            // any information.
            // Function ButtonPressed will return if any of the two buttons
            // has been pushed.
            /*******************************************************************/
            BYTE PressedButton = ButtonPressed();
            switch( PressedButton )
            {
                case 1: 
                    {
                        DWORD ChannelMap = ~((DWORD)0x00000001 << currentChannel);
                        DemoOutput_InitFreqHop();

                        /*******************************************************************/
                        // Function MiApp_InitChannelHopping will start the process of 
                        // channel hopping. This function can be only called by Frquency 
                        // Agility starter and the device must have the energy detection 
                        // feature turned on. This function will do an energy detection 
                        // scan of all input channels and start the process of jumping to 
                        // the channel with least noise
                        //
                        // The only parameter of this function is the bit map of the 
                        // allowed channels. Bit 0 of the double word parameter represents 
                        // channel 0. For the 2.4GHz frequency band, the possible channels 
                        // are channel 11 to channel 26. As the result, the bit map is 
                        // 0x07FFF800. 
                        //
                        // Microchip proprietary stack does not limit the application when to
                        // do channel hopping. The typical triggers for channel hopping are:
                        //  1.  Continuous data transmission failures
                        //  2.  Periodical try the channel hopping process every few hours
                        //      or once per day
                        //  3.  Receive a request to start the channel hopping process. This
                        //      demo is an example of manually issue the request. In the 
                        //      real application, a Frequency Agility follower can send a 
                        //      message to request channel hopping and the Frequency Agility
                        //      starter will decide if start the process.
                        /*******************************************************************/
                        if( MiApp_InitChannelHopping(ChannelMap & 0xFFFFFFFF) == TRUE )
                        {
                            DemoOutput_FreqHopSuccess();
                        }
                        else
                        {
                            DemoOutput_FreqHopFail();
                        }    
                    }
                    break;
                 
                case 2:
                    
                    /*******************************************************************/                
                    // Button 2 (RB4 on PICDEM Z or RD7 on Explorer 16) pressed. We need
                    //  to send out the bitmap of word "P2P" encrypted.
                    // First call function MiApp_FlushTx to reset the Transmit buffer. 
                    //  Then fill the buffer one byte by one byte by calling function 
                    //  MiApp_WriteData
                    /*******************************************************************/
                    MiApp_FlushTx();                    
                    for(i = 0; i < 11; i++)
                    {
                        MiApp_WriteData(DE[(TxSynCount%6)][i]);
                    }
                    TxSynCount++;

                    /*******************************************************************/
                    // Function MiApp_UnicastConnection is one of the functions to 
                    // unicast a message.
                    //    The first parameter is the index of connection table for 
                    //       the peer device. In this demo, since there are only two
                    //       devices involved, the peer device must be stored in the 
                    //       first P2P Connection Entry of the connection table.
                    //    The second parameter is the boolean to indicate if we need 
                    //       to secure the frame. If encryption is applied, the 
                    //       security level and security key are defined in the 
                    //       configuration file for the transceiver
                    //
                    // Another way to unicast a message is by calling function
                    // MiApp_UnicastAddress. Instead of supplying the index of the 
                    // connection table of the peer device, this function requires the 
                    // input parameter of destination address directly.
                    /*******************************************************************/
                    if( MiApp_UnicastConnection(0, TRUE) == FALSE )
                    {
                        DemoOutput_UnicastFail();
                    }
                    else
                    {
                        TxNum++;
                    }
                    DemoOutput_UpdateTxRx(TxNum, RxNum);  
                    break;
                    
                default:
                    break;
            }   
        }
    }
}
Exemplo n.º 6
0
int main(void)
#endif
{   
    BYTE i, j;
    BYTE TxSynCount = 0;
    BOOL bReceivedMessage = FALSE;
    _U16  m;

    
     #define BAUDRG 77
    /*******************************************************************/
    // Initialize the system
    /*******************************************************************/

    ANCON0 = 0XFF;     /*desactiva entradas analogicas*/
    ANCON1 = 0XFF;     /*desactiva entradas analogicas*/

    PPSUnLock();
    PPSOutput(PPS_RP10, PPS_TX2CK2);    // TX2 RP17/RC6
    PPSInput(PPS_RX2DT2, PPS_RP9);     // RX2 RP18/RC7

    PPSOutput(PPS_RP23, PPS_SDO2);    // SDO2 RP23/RD6
    PPSInput(PPS_SDI2, PPS_RP24);     // SDI2 RP24/RD7
    PPSOutput(PPS_RP22, PPS_SCK2);    // SCK2 RP22/RD5

    PPSLock();

     System_PeripheralPinSelect( ExternalInterrupt3, 19);  /*external interrupt 3 B3*/

     BoardInit();
     ConsoleInit();

     Open2USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG);
     baud2USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF);

     Gpios_PinDirection(GPIOS_PORTD, 7, GPIOS_INPUT);  /*pin C0 como salida para SDI*/
     Gpios_PinDirection(GPIOS_PORTD, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/
     Gpios_PinDirection(GPIOS_PORTD, 5, GPIOS_OUTPUT); /*pin C2 como salida para SCK*/

     Spi_Init(SPI_PORT1, SPI_64DIV); /*Inicializamos SPI2*/
     Spi_Init(SPI_PORT2, SPI_64DIV); /*Inicializamos SPI2*/
     //Spi_SetMode(SPI_PORT1, 1);
     //Spi_SetMode(SPI_PORT1, 1);


    LED_1 = 1;
    LED_2 = 1;

    Read_MAC_Address();

    LED_1 = 0;
    LED_2 = 0;

                    ConsolePutROMString((ROM char *)"\r\n<MAC Addr:");
                 
                    PrintChar(myLongAddress[3]);
                    PrintChar(myLongAddress[2]);
                    PrintChar(myLongAddress[1]);
                    PrintChar(myLongAddress[0]);

                    ConsolePutROMString((ROM char *)"\r>");

        
    Printf("\r\nStarting Testing Interface for MiWi(TM) PRO Stack ...");
    #if defined(MRF24J40)
    Printf("\r\n     RF Transceiver: MRF24J40");
    #elif defined(MRF49XA)
    Printf("\r\n     RF Transceiver: MRF49XA");
    #elif defined(MRF89XA)
    Printf("\r\n     RF Transceiver: MRF89XA");
    #endif
    Printf("\r\n   Demo Instruction:");
    Printf("\r\n                     Press Enter to bring up the menu.");
    Printf("\r\n                     Type in hyper terminal to choose");
    Printf("\r\n                     menu item. ");
    Printf("\r\n\r\n");
   
    /*******************************************************************/
    // Following block display demo information on LCD of Explore 16 or 
    // PIC18 Explorer demo board.
    /*******************************************************************/
    #if defined(MRF49XA)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF49XA", 0, TRUE); 
    #elif defined(MRF24J40)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF24J40", 0, TRUE);
    #elif defined(MRF89XA)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF89XA", 0, TRUE); 
    #endif
    
    //if( (PUSH_BUTTON_1 == 0) || ( MiApp_ProtocolInit(TRUE) == FALSE ) )
    if (PUSH_BUTTON_1 == 1)
    {  

        MiApp_ProtocolInit(FALSE);


        LED_1 = 0;
        LED_2 = 0;

        #ifdef ENABLE_ACTIVE_SCAN
        
            myChannel = 0xFF;
            ConsolePutROMString((ROM char *)"\r\nStarting Active Scan...");
            
            LCDDisplay((char *)"Active Scanning", 0, FALSE);
    
            /*******************************************************************/
            // Function MiApp_SearchConnection will return the number of 
            // existing connections in all channels. It will help to decide 
            // which channel to operate on and which connection to add.
            // The return value is the number of connections. The connection 
            //     data are stored in global variable ActiveScanResults. 
            //     Maximum active scan result is defined as 
            //     ACTIVE_SCAN_RESULT_SIZE
            // The first parameter is the scan duration, which has the same 
            //     definition in Energy Scan. 10 is roughly 1 second. 9 is a 
            //     half second and 11 is 2 seconds. Maximum scan duration is 14, 
            //     or roughly 16 seconds.
            // The second parameter is the channel map. Bit 0 of the 
            //     double word parameter represents channel 0. For the 2.4GHz 
            //     frequency band, all possible channels are channel 11 to 
            //     channel 26. As the result, the bit map is 0x07FFF800. Stack 
            //     will filter out all invalid channels, so the application 
            //     only needs to pay attention to the channels that are not 
            //     preferred.
            /*******************************************************************/
            i = MiApp_SearchConnection(10, 0x02000000);
            
            if( i > 0 )
            {
                // now print out the scan result.
                Printf("\r\nActive Scan Results: \r\n");
                for(j = 0; j < i; j++)
                {
                    Printf("Channel: ");
                    PrintDec(ActiveScanResults[j].Channel );
                    Printf("   RSSI: ");
                    PrintChar(ActiveScanResults[j].RSSIValue);
                    Printf("\r\n");
                    myChannel = ActiveScanResults[j].Channel;
                    Printf("PeerInfo: ");
                    PrintChar( ActiveScanResults[j].PeerInfo[0]);
                }
            }
        #endif

    

        /*******************************************************************/
        // Function MiApp_ConnectionMode sets the connection mode for the 
        // protocol stack. Possible connection modes are:
        //  - ENABLE_ALL_CONN       accept all connection request
        //  - ENABLE_PREV_CONN      accept only known device to connect
        //  - ENABL_ACTIVE_SCAN_RSP do not accept connection request, but 
        //                          allow response to active scan
        //  - DISABLE_ALL_CONN      disable all connection request, including
        //                          active scan request
        /*******************************************************************/
        MiApp_ConnectionMode(ENABLE_ALL_CONN);
    
    
        if( i > 0 )
        {
            /*******************************************************************/
            // Function MiApp_EstablishConnection try to establish a new 
            // connection with peer device. 
            // The first parameter is the index to the active scan result, which 
            //      is acquired by discovery process (active scan). If the value
            //      of the index is 0xFF, try to establish a connection with any 
            //      peer.
            // The second parameter is the mode to establish connection, either 
            //      direct or indirect. Direct mode means connection within the 
            //      radio range; Indirect mode means connection may or may not 
            //      in the radio range. 
            /*******************************************************************/
            if( MiApp_EstablishConnection(0, CONN_MODE_DIRECT) == 0xFF )
            {
                Printf("\r\nJoin Fail");
            }
        }    
        else
        {
            /*******************************************************************/
            // Function MiApp_StartConnection tries to start a new network 
            //
            // The first parameter is the mode of start connection. There are 
            // two valid connection modes:
            //   - START_CONN_DIRECT        start the connection on current 
            //                              channel
            //   - START_CONN_ENERGY_SCN    perform an energy scan first, 
            //                              before starting the connection on 
            //                              the channel with least noise
            //   - START_CONN_CS_SCN        perform a carrier sense scan 
            //                              first, before starting the 
            //                              connection on the channel with 
            //                              least carrier sense noise. Not 
            //                              supported on currrent radios
            //
            // The second parameter is the scan duration, which has the same 
            //     definition in Energy Scan. 10 is roughly 1 second. 9 is a 
            //     half second and 11 is 2 seconds. Maximum scan duration is 
            //     14, or roughly 16 seconds.
            //
            // The third parameter is the channel map. Bit 0 of the 
            //     double word parameter represents channel 0. For the 2.4GHz 
            //     frequency band, all possible channels are channel 11 to 
            //     channel 26. As the result, the bit map is 0x07FFF800. Stack 
            //     will filter out all invalid channels, so the application 
            //     only needs to pay attention to the channels that are not 
            //     preferred.
            /*******************************************************************/
            #ifdef ENABLE_ED_SCAN
                //LCDDisplay((char *)"Active Scanning Energy Scanning", 0, FALSE);
                ConsolePutROMString((ROM char *)"\r\nActive Scanning Energy Scanning");
                MiApp_StartConnection(START_CONN_ENERGY_SCN, 10, 0x02000000);
            #endif
        }
        
        // Turn on LED 1 to indicate ready to accept new connections
        LED_1 = 1;
    }
    else
    {
        //LCDDisplay((char *)" Network Freezer    ENABLED", 0, TRUE);
        Printf("\r\nNetwork Freezer Feature is enabled. There will be no hand-shake process.\r\n");
        LED_1 = 1;
        DumpConnection(0xFF);
    }
                   
    LCDDisplay((char *)"Start Connection on Channel %d", currentChannel, TRUE);
    LCDDisplay((char *)"Testing Menu on  Hyper Terminal", 0, FALSE);

    while(1)
    {
        /*******************************************************************/
        // Function MiApp_MessageAvailable will return a boolean to indicate 
        // if a message for application layer has been received by the 
        // transceiver. If a message has been received, all information will 
        // be stored in the rxMessage, structure of RECEIVED_MESSAGE.
        /*******************************************************************/
        if( MiApp_MessageAvailable() )
        {
            /*******************************************************************/
            // If a packet has been received, following code prints out some of
            // the information available in rxFrame.
            /*******************************************************************/
            if( rxMessage.flags.bits.secEn )
            {
                ConsolePutROMString((ROM char *)"Secured ");
            }

            if( rxMessage.flags.bits.broadcast )
            {
                ConsolePutROMString((ROM char *)"Broadcast Packet with RSSI ");
            }
            else
            {
                ConsolePutROMString((ROM char *)"Unicast Packet with RSSI ");
            }
            PrintChar(rxMessage.PacketRSSI);
            if( rxMessage.flags.bits.srcPrsnt )
            {
                ConsolePutROMString((ROM char *)" from ");
                if( rxMessage.flags.bits.altSrcAddr )
                {
                    PrintChar(rxMessage.SourceAddress[1]);
                    PrintChar(rxMessage.SourceAddress[0]);
                }
                else
                {    
                    for(i = 0; i < MY_ADDRESS_LENGTH; i++)
                    {
                        PrintChar(rxMessage.SourceAddress[MY_ADDRESS_LENGTH-1-i]);
                    }
                }    
            }

            ConsolePutROMString((ROM char *)": ");
            
            
            for(i = 0; i < rxMessage.PayloadSize; i++)
            {
                ConsolePut(rxMessage.Payload[i]);
            }
            
            // Toggle LED2 to indicate receiving a packet.
            LED_2 ^= 1;
            
            /*******************************************************************/
            // Function MiApp_DiscardMessage is used to release the current 
            // received message. After calling this function, the stack can 
            // start to process the next received message.
            /*******************************************************************/          
            MiApp_DiscardMessage();
            
            bReceivedMessage = TRUE;
            
            /*******************************************************************/
            // Following block update the total received and transmitted messages
            // on the LCD of the demo board. 
            /*******************************************************************/
            LCDTRXCount(TxNum, ++RxNum);
        }
        else
        {
         ++m;

         if(m > 8000)
         {
             m=0;
             //LED_1 ^= 1;
             
                MiApp_FlushTx();
    	        MiApp_WriteData('H');
    	        MiApp_WriteData('o');
    	        MiApp_WriteData('l');
    	        MiApp_WriteData('a');
                MiApp_WriteData('a');
                MiApp_WriteData('a');
    	        MiApp_WriteData(0x0D);
    	        MiApp_WriteData(0x0A);
               MiApp_BroadcastPacket(FALSE);

         }



            if ( ConsoleIsGetReady() )
            {
                //ProcessMenu();
            } 
        }
    }
}
Exemplo n.º 7
0
/*********************************************************************
* Function:         void RangeDemo(void)
*
* PreCondition:     none
*
* Input:		    none
*
* Output:		    none
*
* Side Effects:	    none
*
* Overview:		    Following routine 
*                    
*
* Note:			    
**********************************************************************/                                
void RangeDemo(void)
{
    BOOL Run_Demo = TRUE;
    BOOL Tx_Packet = TRUE;
    BYTE rssi = 0;
	BYTE Pkt_Loss_Cnt = 0;
	MIWI_TICK tick1, tick2;
    BYTE switch_val;
    

	/*******************************************************************/
    // Dispaly Range Demo Splach Screen
    /*******************************************************************/	
    LCDBacklightON();
    LCDDisplay((char *)"   Microchip       Range Demo  ", 0, TRUE);
    LCDBacklightOFF();
        
	/*******************************************************************/
    // Read Start tickcount
    /*******************************************************************/	
	tick1 = MiWi_TickGet();
    
    while(Run_Demo)
    {	
        /*******************************************************************/
        // Read current tickcount
        /*******************************************************************/
    	tick2 = MiWi_TickGet();
        
    	// Send a Message
        if((MiWi_TickGetDiff(tick2,tick1) > (ONE_SECOND * TX_PKT_INTERVAL)))
    	{
        	LCDErase();
        	
        	if(Tx_Packet)
        	{	
            	LCDDisplay((char *)"Checking Signal Strength...", 0, TRUE);
            		
        	    MiApp_FlushTx();
        	    
        	    MiApp_WriteData(RANGE_PKT);
        	    MiApp_WriteData(0x4D);
        	    MiApp_WriteData(0x69);
        	    MiApp_WriteData(0x57);
        	    MiApp_WriteData(0x69);
        	    MiApp_WriteData(0x20);
        	    MiApp_WriteData(0x52);
        	    MiApp_WriteData(0x6F);
        	    MiApp_WriteData(0x63);
        	    MiApp_WriteData(0x6B);
        	    MiApp_WriteData(0x73);
        	    MiApp_WriteData(0x21);
        	    	    
                if( MiApp_UnicastConnection(0, FALSE) == FALSE )
                    Pkt_Loss_Cnt++;
        	    else
        	        Pkt_Loss_Cnt = 0;
        	        
        	    Tx_Packet = FALSE;   		
    		}
    		else
    		{	      	
            	if(Pkt_Loss_Cnt < 1)
            	{            		
            		if(rssi > 120)
            		{
                		sprintf((char *)&LCDText, (far rom char*)"Strength: High ");
                        LED0 = 1;
                        LED1 = 0;
                        LED2 = 0;
                    }  		
                	else if(rssi < 121 && rssi > 60)
            		{
                		sprintf((char *)&LCDText, (far rom char*)"Strength: Medium");
                        LED0 = 1;
                        LED1 = 1;
                        LED2 = 0;
                    } 
                  	else if(rssi < 61)
            		{
                		sprintf((char *)&LCDText, (far rom char*)"Strength: Low");
                        LED0 = 0;
                        LED1 = 1;
                        LED2 = 0;
                    }
                    
                    // Convert to dB
        		    //rssi = RSSIlookupTable[rssi];
                  	sprintf((char *)&(LCDText[16]), (far rom char*)"Rcv RSSI: %03d", rssi);                  	                  
                }       
                else
                {
                        LCDDisplay((char *)"No Device Found or Out of Range ", 0, TRUE);
                        LED0 = 0;
                        LED1 = 0;
                        LED2 = 1;
                }

                LCDUpdate();
                Tx_Packet = TRUE;
                        		
            } 	     
    	    /*******************************************************************/
            // Read New Start tickcount
            /*******************************************************************/
      		tick1 = MiWi_TickGet(); 
      		  
        }
        
    	// Check if Message Available
    	if(MiApp_MessageAvailable())
    	{
        	if(rxMessage.Payload[0] == EXIT_PKT)
        	{
            	MiApp_DiscardMessage();
            	MiApp_FlushTx();
    	        MiApp_WriteData(ACK_PKT);
    	        MiApp_UnicastConnection(0, FALSE);
            	Run_Demo = FALSE;
            	LCDBacklightON();
                LCDDisplay((char *)"   Exiting....     Range Demo  ", 0, TRUE);
                LCDBacklightOFF();
            }
            else if(rxMessage.Payload[0] == RANGE_PKT)
            {
            	// Get RSSI value from Recieved Packet
            	rssi = rxMessage.PacketRSSI;
        	    
        	    // Disguard the Packet so can recieve next
        	    MiApp_DiscardMessage();
        	}
        	else
            	MiApp_DiscardMessage(); 
    	}
    	
    	// Check if  Switch Pressed
    	switch_val = ButtonPressed();
    	
        if((switch_val == SW0) || (switch_val == SW1))
        {
            /*******************************************************************/
        	// Send Exit Demo Request Packet and exit Range Demo
        	/*******************************************************************/ 
            MiApp_FlushTx();    
            MiApp_WriteData(EXIT_PKT);
            MiApp_UnicastConnection(0, FALSE);
   
            LCDBacklightON();
            LCDDisplay((char *)"   Exiting....     Range Demo  ", 0, TRUE);
            LCDBacklightOFF();
            
            tick1 = MiWi_TickGet();
            // Wait for ACK Packet
            while(Run_Demo)
            {
                if(MiApp_MessageAvailable())
                {
                    if(rxMessage.Payload[0] == ACK_PKT)          
                        Run_Demo = FALSE;
                        
                    MiApp_DiscardMessage();
                }
                if ((MiWi_TickGetDiff(tick2,tick1) > (ONE_SECOND * EXIT_DEMO_TIMEOUT)))
                    Run_Demo = FALSE;
                    
                tick2 = MiWi_TickGet();
            }    
        }    
    }
}
Exemplo n.º 8
0
void ProjectorScreen(void)

{   
    int statusScreen = 0; //etat initialise a 0, l'ecran est roulé
    
    // Commentaires de Timer 3 - 2016 par Samuel Proulx
    // La routine d'interruption pour cette fonction se trouve dans "drv_mrf_miwi_24j40.c" à la ligne 1879
    // Nomenclature :  (REGISTERNAME . REGISTERBIT)
    PROJECTOR_TRIS = 0;
    RCONbits.IPEN = 1; // Interrupt Priority Level Bit . 1 = Enable Priority Levels
    T3CON = 0b00011111; // Timer 3 Control Register . Voir fin de ce fichier
    TCLKCONbits.T1RUN = 1; 
    TMR3 = 0xE000; //TMR3H + TMR3L  . C'est la valeur du timer (0 à 65536) 0XE000 =  57344
    IPR2bits.TMR3IP = 1; // Overflow Priority bit. 1 = High Priority
    INTCONbits.GIEH = 1; // INTCON = Interrupt Control Access Register . GIEH = Global Interrupt Enable Bit . 1 enables all.
    PIE2bits.TMR3IE  = 0; // Overflow Interrupt Enable Bit . 1 enables
    PIR2bits.TMR3IF = 0;// Timer 3 Overflow Interrupt Flag Bit . 1 = register overflowed(MUST BE CLEARED IN SOFTWARE)
    LCD_BKLT = 1;
    
    
    
    
    while(true)
    {

        if(MiApp_MessageAvailable())
        {
            if(rxMessage.Payload[0] == PROJECTOR_MOTOR_UP)
            {
                LED1 = 1 ;
                delay_ms(100);
                LED1 = 0 ;
                statusScreen = 0;
               pwm_value_high_time = 800;
               PIE2bits.TMR3IE  = 1;
            }
            else if (rxMessage.Payload[0] == PROJECTOR_MOTOR_DOWN)
            {      
                 LED2 = 1 ;
                delay_ms(100);
                LED2 = 0 ;
                statusScreen = 1;
                pwm_value_high_time = 0;
                PIE2bits.TMR3IE  = 1;
               
            }
            else if (rxMessage.Payload[0] == STATUS_SCREEN)
            {      
                if(statusScreen == 0)
				{
                
			      LED1 = 1;
                  MiApp_FlushTx();
                  MiApp_WriteData(SCREEN_UP);
                  MiApp_WriteData(myShortAddress.v[0]);
                  MiApp_WriteData(myShortAddress.v[1]);
                  MiApp_BroadcastPacket(false);
                  delay_ms(500);
                  LED1 = 0;
                }
	    	    else
                { LED1 = 1;
                  MiApp_FlushTx();
                  MiApp_WriteData(SCREEN_DOWN);
                  MiApp_WriteData(myShortAddress.v[0]);
                  MiApp_WriteData(myShortAddress.v[1]);
                  MiApp_BroadcastPacket(false);
                  delay_ms(500);
                  LED1 = 0;

		        }
            
            MiApp_DiscardMessage();
            }
        }
    }
}
Exemplo n.º 9
0
void PingPongStateMachine()
{
    BYTE    i;
    WORD    j, k;
    BYTE    packagerssi;
    switch(case_value)
            {
                case 0:     //Send 0x01 frame to initiate ping - pong test
                    MiApp_FlushTx();
                    MiApp_WriteData(0x01);
                    for(i = 0; i < sizeof(PingPongPacket); i++)
                    {
                        MiApp_WriteData(PingPongPacket[i]);
                    }

                    /*******************************************************************/

                    // Function MiApp_BroadcastPacket is used to broadcast a message
                    //    The only parameter is the boolean to indicate if we need to
                    //       secure the frame

                    /*******************************************************************/
                    MiApp_BroadcastPacket(FALSE);
                    PingPong_Count = 0;
                    previous_state = 0;
                    case_value = 8;
                    LCDDisplay((char *)"Transmitting...", 0, TRUE);

                    //Printf("\r\nIn case 0");
                    break;

                case 1:     //Send 0x04 frames - indicating data transmission
                    MiApp_FlushTx();
                    MiApp_WriteData(0x04);
                    for(i = 0; i < sizeof(PingPongPacket); i++)
                    {
                        MiApp_WriteData(PingPongPacket[i]);
                    }

                    if(PingPong_Count != PingPong_Package)
                    {
                        MiApp_BroadcastPacket(FALSE);
                        case_value = 1;
                        PingPong_Count++;
                        LED_1 ^= 1;
                        LCDErase();
                        sprintf((char *)LCDText, (far rom char *) "Transmitting...");
                        sprintf((char *) &(LCDText[16]), (far rom char *) "Count: %d", PingPong_Count);
                        LCDUpdate();
                    }
                    else
                    {
                        Printf("\r\nSent Packet Count: ");
                        PrintDec(PingPong_Package);
                        PingPong_Count = 0;
                        case_value = 2;
                    }

                    previous_state = 1;

                    //Printf("\r\nIn case 1");
                    break;

                case 2:

                    //Send 0x02 frame to get status response
                    MiApp_FlushTx();
                    MiApp_WriteData(0x02);
                    for(i = 0; i < sizeof(PingPongPacket); i++)
                    {
                        MiApp_WriteData(PingPongPacket[i]);
                    }

                    MiApp_BroadcastPacket(FALSE);
                    previous_state = 2;
                    case_value = 8;

                    //Printf("\r\n In case 2");
                    break;

                case 3:

                    //Ping Pong Receive Mode
                    if(MiApp_MessageAvailable())
                    {
                        if(rxMessage.Payload[0] == 0x01)
                        {
                            BYTE    rssi = rxMessage.PacketRSSI;
                            #if defined(MRF24J40)
                            rssi = RSSIlookupTable[rssi];
                            #endif
                            MiApp_DiscardMessage();
                            MiApp_FlushTx();
                            MiApp_WriteData(0x03);
                            for(i = 0; i < sizeof(PingPongPacket); i++)
                            {
                                MiApp_WriteData(PingPongPacket[i]);
                            }

                            MiApp_BroadcastPacket(FALSE);
                            PingPong_RxCount = 0;

                            //LCDDisplay((char *)"Ping Pong Test  Rcvng.. RSSI:", rssi, TRUE);
                            LCDErase();
                            sprintf((char *)LCDText, (far rom char *) "Receiving.. ");
                            #if defined(MRF24J40)
                            sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): --");
                            #else
                            sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): --");
                            #endif
                            LCDUpdate();
                            packagerssi = rssi;
                        }
                        else if(rxMessage.Payload[0] == 0x04)
                        {
                            BYTE    rssi = rxMessage.PacketRSSI;
                            #if defined(MRF24J40)
                            rssi = RSSIlookupTable[rssi];
                            #endif
                            MiApp_DiscardMessage();
                            PingPong_RxCount++;
                            previous_state = 3;
                            LED_2 ^= 1;

                            LCDErase();
                            sprintf((char *)LCDText, (far rom char *) "Receiving..  %d", PingPong_RxCount);
                            #if defined(MRF24J40)
                            sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): -%d", packagerssi);
                            #else
                            sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB):  -%d", packagerssi);
                            #endif
                            LCDUpdate();

                            case_value++;
                        }
                        else if(rxMessage.Payload[0] == 0x02)
                        {
                            Printf("\r\nReceived Packet Count:");
                            PrintDec(PingPong_RxCount);
                            MiApp_DiscardMessage();
                            case_value = case_value + 2;
                        }
                        else
                        {

                            //Printf("\r\nIllegal packet received with payload first byte set to - ");
                            //PrintDec(rxMessage.Payload[0]);
                            MiApp_DiscardMessage();
                        }
                    }

                    //Printf("\r\n In case 3");
                    break;

                case 4:
                    if(MiApp_MessageAvailable())
                    {
                        if(rxMessage.Payload[0] == 0x04)
                        {
                            BYTE    rssi = rxMessage.PacketRSSI;
                            MiApp_DiscardMessage();
                            PingPong_RxCount++;
                            LED_2 ^= 1;

                            LCDErase();
                            sprintf((char *)LCDText, (far rom char *) "Receiving..  %d", PingPong_RxCount);
                            #if defined(MRF24J40)
                            sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): -%d", packagerssi);
                            #else
                            sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): %d", packagerssi);
                            #endif
                            LCDUpdate();
                        }
                        else if(rxMessage.Payload[0] == 0x02)
                        {
                            Printf("\r\nReceived Packet Count:");
                            PrintDec(PingPong_RxCount);
                            MiApp_DiscardMessage();
                            case_value++;
                        }
                        else
                        {

                            //Printf("\r\nIllegal packet received with payload first byte set to - ");
                            //PrintDec(rxMessage.Payload[0]);
                            //Printf("\r\n");
                            MiApp_DiscardMessage();
                        }
                    }

                    //Printf("\r\n In case 4");
                    break;

                case 5:
                    MiApp_FlushTx();
                    MiApp_WriteData(0x03);
                    for(i = 0; i < sizeof(PingPongPacket); i++)
                    {
                        MiApp_WriteData(PingPongPacket[i]);
                    }

                    MiApp_BroadcastPacket(FALSE);
                    previous_state = 0;
                    case_value = 8;

                    //Printf("\r\n In case 5");
                    break;

                case 8:
                    case_value = previous_state;
                    DelayMs(20);
                    if(MiApp_MessageAvailable())
                    {
                        if(rxMessage.Payload[0] == 0x03)
                        {
                            case_value = (previous_state + 1);
                        }

                        if(rxMessage.Payload[0] == 0x01)
                        {
                            case_value = (previous_state + 1);
                        }

                        if(rxMessage.Payload[0] == 0x02)
                        {
                            case_value = 5;
                        }

                        MiApp_DiscardMessage();
                    }

                    //Printf("\r\nIn case 8");
                    break;

                default:
                    break;
            }               //end of switch statement
}
Exemplo n.º 10
0
void run_star_demo(void)
{
    #if defined(PROTOCOL_STAR)
        t1 = MiWi_TickGet();
        LCDDisplay((char *)"Sleeping!!", 0, false);
        while(1)
        {
           
            t2 = MiWi_TickGet();    // Calculate the Time for Sleeping device

            if((MiWi_TickGetDiff(t2,t1) > (ONE_SECOND * 20)))
            {
              awake = true;
              #if !defined(EIGHT_BIT_WIRELESS_BOARD)
              LCD_BacklightON();
              #endif
      
              MiApp_TransceiverPowerState(POWER_STATE_WAKEUP_DR);
              LCDDisplay((char *)"Woke Up!!!", 0, false);
              DELAY_ms(1000);
              STAR_DEMO_OPTIONS_MESSAGE (false);
              tt1 = MiWi_TickGet();  
            }
            while(awake)   
            {
                tt2 = MiWi_TickGet();    
                if((MiWi_TickGetDiff(tt2,tt1) > (ONE_SECOND * 10)))   
                {
                    // The Indirect Message for a Sleeping RFD is stored in PAN CO 
                    // We periodically send Data Requests for the Indirect Message to 
                    // not loose a message. 
                    CheckForData();
                    tt1 = MiWi_TickGet();
                }    
                /*******************************************************************/
                // Function MiApp_MessageAvailable returns a boolean to indicate if 
                // a packet has been received by the transceiver. If a packet has 
                // been received, all information will be stored in the rxFrame, 
                // structure of RECEIVED_MESSAGE.
                /*******************************************************************/

                if( MiApp_MessageAvailable())
                {

                    /*******************************************************************/
                    // If a packet has been received, update the information available 
                    // in rxMessage.
                    /*******************************************************************/
                    DemoOutput_UpdateTxRx(TxNum, ++RxNum);
                    DELAY_ms(2000);
                    // Toggle LED2 to indicate receiving a packet.
                    LED_2 ^= 1;

                    /*******************************************************************/
                    // Function MiApp_DiscardMessage is used to release the current 
                    //  received packet.
                    // After calling this function, the stack can start to process the
                    //  next received frame 
                    /*******************************************************************/        
                    MiApp_DiscardMessage();



                    /****************************************/
                }
                else
                {
                    /*******************************************************************/
                    // If no packet received, now we can check if we want to send out
                    // any information.
                    // Function ButtonPressed will return if any of the two buttons
                    // has been pushed.
                    /*******************************************************************/
                    uint8_t PressedButton = ButtonPressed();
                    if ( PressedButton == 1 || PressedButton == 2)
                    {
                        
                        uint8_t select_ed =0;
                        bool update_ed = true;
                        while(update_ed == true)
                        {

                            //User Selected Change end device
                            LCD_Erase();
                            if (myConnectionIndex_in_PanCo  == select_ed)
                            {   // if END_device displays itself , "me" is added in display to denote itself 
                                sprintf((char *)LCDText, (char*)"RB0:%02d-%02x%02x%02x-me",END_DEVICES_Short_Address[select_ed].connection_slot,END_DEVICES_Short_Address[select_ed].Address[0],
                                        END_DEVICES_Short_Address[select_ed].Address[1],END_DEVICES_Short_Address[select_ed].Address[2] );
                            }
                            else
                            {
                                sprintf((char *)LCDText, (char*)"RB0:%02d-%02x%02x%02x",END_DEVICES_Short_Address[select_ed].connection_slot,END_DEVICES_Short_Address[select_ed].Address[0],
                                        END_DEVICES_Short_Address[select_ed].Address[1],END_DEVICES_Short_Address[select_ed].Address[2] );
                            }
                            sprintf((char *)LCDText, (char*)"RB0:%02d-%02x%02x%02x",END_DEVICES_Short_Address[select_ed].connection_slot,END_DEVICES_Short_Address[select_ed].Address[0],
                                        END_DEVICES_Short_Address[select_ed].Address[1],END_DEVICES_Short_Address[select_ed].Address[2] );
                            sprintf((char *)&(LCDText[16]), (char*)"RB2: Change node");
                            LCD_Update();
                            chk_sel_status = true;
                            bool sw_layer_ack_status , mac_ack_status;
                            while(chk_sel_status)
                            {
                                uint8_t switch_val = ButtonPressed();
                                if(switch_val == 1)
                                {
                                    update_ed = false;
                                    chk_sel_status = false;
                                    update_ed = false;
                                    // Star_User_Data is defined in star_demo.c 
                                    // Its user data  , in case of Star Network 60 bytes of 
                                    // Data can be sent at a time from one END_DEVICE_TO_ANOTHER 
                                    // Edx --> Pan CO --> EDy
                                    if (myConnectionIndex_in_PanCo == select_ed)
                                    {
                                        MiApp_FlushTx();
                                        for (i = 0 ; i < 21 ; i++)
                                        {
                                            MiApp_WriteData(MiWi[(TxSynCount%6)][i]);
                                        }

                                        // IF on the demo , a END_Device displays its own Connection Detail
                                        // We unicast data packet to just PAN COR , No forwarding
                                        #if defined(ENABLE_SECURITY)
                                            mac_ack_status = MiApp_UnicastConnection (0, true);
                                        #else
                                            mac_ack_status = MiApp_UnicastConnection (0, false);
                                        #endif
                                            TxNum++;
                                    }
                                    else
                                    {
                                        // Data can be sent at a time from one END_DEVICE_TO_ANOTHER 
                                        // Edx --> Pan CO --> EDy
                                        // To forward a Packet from one ED to another ED , the first 4 bytes should holding
                                        // a CMD and end dest device short address (3 bytes)
                                        MiApp_FlushTx();
                                        MiApp_WriteData(CMD_FORWRD_PACKET);
                                        MiApp_WriteData(END_DEVICES_Short_Address[select_ed].Address[0]);// sending the first byte payload as the destination nodes
                                        MiApp_WriteData(END_DEVICES_Short_Address[select_ed].Address[1]);// sending the first byte payload as the destination nodes
                                        MiApp_WriteData(END_DEVICES_Short_Address[select_ed].Address[2]);// sending the first byte payload as the destination nodes
                                        for (i = 4 ; i < 25 ; i++)
                                        {
                                            MiApp_WriteData(MiWi[(TxSynCount%6)][i-4]);
                                        }
                                        #if defined(ENABLE_SECURITY)
                                            sw_layer_ack_status = MiApp_UnicastStar (true);
                                        #else
                                            sw_layer_ack_status = MiApp_UnicastStar (false);
                                        #endif


                                        #if defined(ENABLE_APP_LAYER_ACK)
                                            if (sw_layer_ack_status)
                                            {
                                                TxNum++;     // Tx was successful
                                            }
                                            else
                                            {
                                                LCDDisplay((char *)"Data_Sending_Fail!!", 0, false); 
                                            }
                                        #else    
                                            TxNum++;
                                        #endif

                                    }

                                } // end of switch_val == 1
                                else if(switch_val == 2)
                                {
                                    if (select_ed > end_nodes-1)
                                    {    
                                        select_ed = 0;
                                    }
                                    else
                                    {
                                        select_ed = select_ed+1;
                                    }
                                    chk_sel_status = false;

                                } // end of switch_val == 2
                            }  // end of chk_sel_status

                        } // end of updating the LCD info
                        STAR_DEMO_OPTIONS_MESSAGE (false);
                    } // end of actions on button press
                } // end of check for user inputs (button press check)

                t3 = MiWi_TickGet();
                if((MiWi_TickGetDiff(t3,t2) > (ONE_SECOND * 40)))
                {
                    awake = false;
                    #if !defined(EIGHT_BIT_WIRELESS_BOARD)
                              LCD_BacklightOFF();
                    #endif
                    MiApp_TransceiverPowerState(POWER_STATE_SLEEP);
                    LCDDisplay((char *)"Sleeping!!!", 0, false);
                    DELAY_ms(1000);
                    t1 = t3;

                }
                
                if (lost_connection && !role)
                {
                    MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT);
                    lost_connection = false;

                }

            }  // end of actions performed while node is awake
            
           

            
        } // end of while(1)
    #endif
}
Exemplo n.º 11
0
void main (void)
{
    uint8_t    i;
    
    
    SYSTEM_Initialize();
    CONSOLE_Initialize();

    /*******************************************************************/

    // Initialize the system

    /*******************************************************************/

    /*******************************************************************/

    // Following block display demo information on LCD of Explore 16 or
    // PIC18 Explorer demo board.

    /*******************************************************************/
    LCDDisplay((char *)"Chat Demo", 0, true);

    // Clear the screen (VT100)
    Printf("\x1b[2J");
    // Send the cursor home (VT100)
    Printf("\x1b[H");
    Printf("\r\nChat Demo");
            #if defined(MRF24J40)
    Printf("\r\nRF Transceiver: MRF24J40");
            #elif defined(MRF49XA)
    Printf("\r\nRF Transceiver: MRF49XA");
            #elif defined(MRF89XA)
    Printf("\r\nRF Transceiver: MRF89XA");
            #endif
    Printf("\r\n\r\nDemo Instruction:");
    Printf("\r\nUse Console to Chat with the Peer Device");
    Printf("\r\n");
    LED_1 = 0;
    LED_2 = 0;

   /******************************************************************/

    // Read the MAC address from the MAC EEPROM on the PICTail Card

    ReadMacAddress();

    // ..and display on terminal

	Printf("\r\n\r\nMy MAC Address: 0x");
    for(i = 0; i < MY_ADDRESS_LENGTH; i++)
    {
        CONSOLE_PrintHex(myLongAddress[MY_ADDRESS_LENGTH-1-i]);
    }
    /*******************************************************************/

    // Initialize Microchip proprietary protocol. Which protocol to use
    // depends on the configuration in ConfigApp.h

    /*******************************************************************/

    /*******************************************************************/

    // Function MiApp_ProtocolInit initialize the protocol stack. The
    // only input parameter indicates if previous network configuration
    // should be restored. In this simple example, we assume that the
    // network starts from scratch.

    /*******************************************************************/
    MiApp_ProtocolInit(false);

    // Set default channel
    if(MiApp_SetChannel(myChannel) == false)
    {
        Printf("\r\nERROR: Unable to program the channel\r\n");
        Printf("\r\nPress MCLR to start again\r\n");
        LCDDisplay((char *)"Error: Unable to Program Channel ", 0, TRUE);
        while(1);
        //Display error message on LCD and Console
    }

    /*******************************************************************/

    // Function MiApp_ConnectionMode defines the connection mode. The
    // possible connection modes are:
    //  ENABLE_ALL_CONN:    Enable all kinds of connection
    //  ENABLE_PREV_CONN:   Only allow connection already exists in
    //                      connection table
    //  ENABL_ACTIVE_SCAN_RSP:  Allow response to Active scan
    //  DISABLE_ALL_CONN:   Disable all connections.

    /*******************************************************************/
    MiApp_ConnectionMode(ENABLE_ALL_CONN);

    /*******************************************************************/

    // Display current opertion on LCD of demo board, if applicable

    /*******************************************************************/
    LCDDisplay((char *)"Connecting Peer  on Channel %d ", myChannel, true);
    Printf("\r\n\r\nConnecting to Peer...\r\n");

    /*******************************************************************/

    // Function MiApp_StartConnection will enable a node to start operating
    // in a variety of ways. Usually, this fucntion is called by the
    // PAN Coordinator who is the first in the PAN.
    //
    // The first parameter defines the mode to start the PAN in
    //
    // The second parameter defines the scan duration (if energy/carrier
    // sense scan is enabled). 0 if START_CONN_DIRECT used.
    //
    // The third parameter is a bit map of of the channels to perform the
    // noise scan on. 0 if START_CONN_DIRECT used.

    /*******************************************************************/

    MiApp_StartConnection(START_CONN_DIRECT, 0, 0) ;
    /*******************************************************************/

    // Function MiApp_EstablishConnection try to establish a new
    // connection with peer device.
    // The first parameter is the index to the active scan result,
    //      which is acquired by discovery process (active scan). If
    //      the value of the index is 0xFF, try to establish a
    //      connection with any peer.
    // The second parameter is the mode to establish connection,
    //      either direct or indirect. Direct mode means connection
    //      within the radio range; indirect mode means connection
    //      may or may not in the radio range.

    /*******************************************************************/
    #ifdef ENABLE_HAND_SHAKE
    i = 0xFF;
    while(i == 0xFF)
    {
        i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT);
    }
    #endif

    /*******************************************************************/

    // Display current opertion on LCD of demo board, if applicable

    /*******************************************************************/

    LCDDisplay((char *)"Joined  Network Successfully..", 0, true);

    /*******************************************************************/

    // Function DumpConnection is used to print out the content of the
    //  Connection Entry on the hyperterminal. It may be useful in
    //  the debugging phase.
    // The only parameter of this function is the index of the
    //  Connection Entry. The value of 0xFF means to print out all
    //  valid Connection Entry; otherwise, the Connection Entry
    //  of the input index will be printed out.

    /*******************************************************************/
    #ifdef ENABLE_DUMP
    DumpConnection(0xFF);
    #endif

    #ifndef ENABLE_POWERSAVE
    // Turn on LED 1 to indicate P2P connection established
    LED_1 = 1;
    #endif
    DELAY_ms(100);

    LCDBacklightON();
    LCD_Erase();
    sprintf((char *)LCDText, (char *)"MyAddr:   %02x%02x%02x", myLongAddress[2],
             myLongAddress[1], myLongAddress[0]);
    sprintf((char *) &(LCDText[16]), (char *)"PeerAddr: %02x%02x%02x", ConnectionTable[i].Address[2],
             ConnectionTable[i].Address[1], ConnectionTable[i].Address[0]);
    LCD_Update();

    /*******************************************************************/

    // Following block display demo instructions on LCD based on the
    // demo board used.

    /*******************************************************************/
    Printf("-------------------------------------------------------\r\n");
    Printf("Chat Window: \r\n");
    Printf("-------------------------------------------------------\r\n");
    Printf("$$");

    while(1)
    {
        if(MiApp_MessageAvailable())
        {  
            ProcessRxMessage();      
        }

        if(CONSOLE_IsGetReady())
        {
            FormatTxMessage();
            
        }

        if(messagePending)
        {
            tickCurrent = MiWi_TickGet();
            if
            (
                (MiWi_TickGetDiff(tickCurrent, tickPrevious) > (ONE_SECOND * 30)) ||
                (TxMessageSize >= MAX_MESSAGE_LEN) ||
                (transmitPending == true)
            )
            {
                
                TransmitMessage();


            }
        }

        // Display connection table if RB0 is pressed
        if(PUSH_BUTTON_1 == 0)
    	{
        	while(PUSH_BUTTON_1 == 0);
        	Printf("\r\n\r\nDumping Connection Table...\r\n");
        	DumpConnection(0xFF);
        	Printf("-------------------------------------------------------\r\n");
    		Printf("Chat Window: \r\n");
    		Printf("-------------------------------------------------------\r\n");
    		Printf("$$ ");
    	}


    }

    //Enable device to foward the received packet information to the console
}                           //end of main
Exemplo n.º 12
0
 //----------------------------------------------------------------------------//
 void Menu(void)
 {
      ReadButtons();
      
      
     if( Button1Pressed && Button2Pressed)   // si se han presionado ambos botones 
     {
      ++MenuIn;
     }
     else
     {
         MenuIn = 0;
     }
     
      if(MenuIn >=250)
      {
          MenuIndex = 1;
          MenuIn = 0;
      }
      else
      {
          MenuIndex = 0;
      }
     
      if(MenuIndex != 0)
      {
       switch(MenuIndex)
       {
         case 0:
         {
             
         }
         break;
         
         case 1:
         {
             LED_1 = 1;
             LED_2 = 1;
             
             ConsolePutROMString((ROM char *)"\r\n      MENU : Temperature Calibration ");
             
             
             while((Button1Pressed)&&(Button2Pressed))
             {
                 if( MiApp_MessageAvailable())
                 {
                     MiApp_DiscardMessage();
                 }
                 
                 ReadButtons();
                 ClrWdt();
             }
             
             ConsolePutROMString((ROM char *)"\r\n SW1: Increase offset value  || SW2 Decrease offset value");
             
             
             
             Button1Released = 1;
             Button2Released = 1;
             
             Exit = 0xff;
             OffsetValue = 100;
             
             while(Exit)
             {
                 ReadButtons();
                 
                 
                 
                 
                 
                 if( Button1Pressed && Button2Pressed)   // si se han presionado ambos botones
                 {
                     Exit = 0;
                     ConsolePutROMString((ROM char *)"\r\nExit");       
                 }
                 else
                 {
                     if( Button1Pressed && Button1Released)   // 
                   {
                     Button1Released = 0;
                     ++OffsetValue;
                     LED_1 ^= 1;
                     LED_2 ^= 1;
                     ConsolePutROMString((ROM char *)"\r\nIncreased offset value");
                   }
                 
                   if( Button2Pressed && Button2Released)   // 
                   {   
                     Button2Released = 0;
                     --OffsetValue;
                     LED_1 ^= 1;
                     LED_2 ^= 1;
                     ConsolePutROMString((ROM char *)"\r\nDecreased offset value");
                   }
                 }
                 
           
                 
                 
                 
                 if( MiApp_MessageAvailable())
                 {
                     MiApp_DiscardMessage();
                 }
                 
                 ClrWdt();
             }
             
             while((Button1Pressed)&&(Button2Pressed))
             {
              if( MiApp_MessageAvailable())
              {
                MiApp_DiscardMessage();
              }
                 
              ReadButtons();
              ClrWdt();
             }
             
             
             
             
         }
         break;
         
         case 2:
         {
             
         }
         break;
         
         case 3:
         {
             
         }
         break;
         
         
         default: break;
         
       }
 }
     
     
     
 }
Exemplo n.º 13
0
//----------------------------------------------------------------------------//
 void  TaskScheduler(void)
 {
     Timer1Tick();

     switch(EndDevStateMachine)
     {
         case 0:
         {
             if( MiApp_MessageAvailable())
             {
                if((rxMessage.Payload[1] == 0x00)&&((rxMessage.Payload[3] == OutputStat)))
                {
                    if(rxMessage.Payload[4] <= 16)
                    {
                        BaseTimeToTx = rxMessage.Payload[4];
                    }

                    SwTimer0 = 0;
                    LED_2 ^= 1;
                    EndDevStateMachine = 1;

                }

                 MiApp_DiscardMessage();
             }


         }
         break;

         case 1:
         {
             if(SwTimer0 >= (_U08)myNodeNumber)
             {

              MyTemp = TemperatureRead();

              MiApp_FlushTx();
              MiApp_WriteData(' ');
              MiApp_WriteData(myNodeNumber);
              MiApp_WriteData(MyTrackingNumber);
              MiApp_WriteData(OutputStat);
              MiApp_WriteData(MyStat);
              MiApp_WriteData(MyTemp);

              MiApp_BroadcastPacket(FALSE);

              EndDevStateMachine = 2;
             }
         }
         break;

         case 2:
         {
             LED_1 ^= 1;
             EndDevStateMachine = 0;

             //ConsolePutROMString( (ROM char * const) "  \r\n Temperature here:" );
             //PrintDec(MyTemp);

         }
         break;

         case 3:
         {

         }
         break;


         default:
         break;
     }

 }
Exemplo n.º 14
0
 void WirelessTxRx(void)
 {
     Timer1Tick();

     switch(EndDevStateMachine)
     {
         case 0:                      // recibe estado para relevadores y latencia de comunicacion
         {
             if( MiApp_MessageAvailable())
             {
                if((rxMessage.Payload[1] == 0x00)&&((rxMessage.Payload[3] == OutputStat)))
                {
                    BypassCounter = 0;
                    if(rxMessage.Payload[4] <= 16)
                    {
                        //BaseTimeToTx = rxMessage.Payload[4];
                        TickScaler = rxMessage.Payload[4];
                    }


                    j = (myNodeNumber-1)/8;
                    j += 5;

                    i = rxMessage.Payload[j];

                    j =  (myNodeNumber-1)%8;

                    if(QUERY_8BIT(i,j))
                    {

                        RLY_STATUS = 1;
                    }
                    else
                    {

                        RLY_STATUS = 0;
                    }


                    ConsolePutROMString((ROM char *)"\r\n Req Stat:");

                    for(i=0;i<rxMessage.PayloadSize;i++)
                    {
                        PrintChar(rxMessage.Payload[i]);
                    }
                    

                    SwTimer0 = 0;
                    WriteTimer1(56161);           
                    Tick = 0;
                    
                    LED_2 ^= 1;
                    EndDevStateMachine = 1;
                    SwTimer3 = 0;     // clear MIWIPRO STATUS TIMER


                }
                else
                {
                    if((rxMessage.Payload[1] == 0x00)&&((rxMessage.Payload[3] == ListenDevices)))
                    {
                        ConsolePutROMString((ROM char *)"\r\n Listen Devices:");

                        for(i=0;i<rxMessage.PayloadSize;i++)
                        {
                         PrintChar(rxMessage.Payload[i]);
                        }
                        
                        j = (myNodeNumber-1)/8;
                        j += 4;

                        i = rxMessage.Payload[j];

                        j =  (myNodeNumber-1)%8;
                        
                        
                        if(QUERY_8BIT(i,j))
                        {
                         ConsolePutROMString((ROM char *)"\r\n Link stablished correctly");
                         RestartCounter = 0;
                        }
                        else
                        {
                         ConsolePutROMString((ROM char *)"\r\n NO Link stablished!!");
                         ++RestartCounter;
                        }
                        
                        
                        
                    }
                    else
                    {
                        if((rxMessage.Payload[1] == 0x00)&&((rxMessage.Payload[3] == CalibrationProcedure)))
                        {
                            
                            ConsolePutROMString((ROM char *)"\r\n Temperature sensor calibration:");
                            
                            //TemperatureCalibrationValue = rxMessage.Payload[5];
                            
                            
                            if((rxMessage.Payload[5] == MyTemp)||(rxMessage.Payload[5] == 0))
                            {
                                TemperatureCalibrationValue = 0;
                            }
                            else
                            {
                                if(rxMessage.Payload[5] > MyTemp)              // la temp de referencia es mayor a la leida
                                {
                                    //TemperatureCalibrationValue = (rxMessage.Payload[5] - MyTemp) & 0x0F;
                                    
                                }
                                else                                           // la temperatura leida es mayor a la temp de referencia
                                {
                                    //TemperatureCalibrationValue = (MyTemp - rxMessage.Payload[5]) & 0x0F;
                                    //SET_8BIT(TemperatureCalibrationValue,7);
                                }
                            }
                            
                            //EEPROMWRITE(TemperatureCalibrationValue,0,1);
                        }
                    }
                    
                }
                

                 MiApp_DiscardMessage();
             }
         }
         break;

//-----------------------------------------------------------------------------//

         case 1:                // envia estado y temperatura
         {
             if(SwTimer0 >= (_U08)myNodeNumber)
             {

              MyTemp = TemperatureRead();
                                                       
              MiApp_FlushTx();
              MiApp_WriteData(' ');
              MiApp_WriteData(myNodeNumber);
              MiApp_WriteData(MyTrackingNumber);
              MiApp_WriteData(OutputStat);
              MiApp_WriteData(RLY_STATUS);
              MiApp_WriteData(MyTemp);

              MiApp_BroadcastPacket(FALSE);
              

             /*              
              if(RLY_STATUS == 1)
              {
                  RLY_1 = 1;
              }
              else
              {
                  RLY_1 = 0;
              }
              */
              
              
              //SDW_RLY_STATUS
              
              if(RLY_STATUS == 1)
              {
                  if(SDW_RLY_STATUS == 1)
                  {
                      RLY_1 = 1;
                      
                      if(EEPROMCHG == 0)
                      {
                        i = 0x55;
                        EEPROMWRITE(&i,0,1); 
                        EEPROMWRITE(&i,0,1); 
                        EEPROMWRITE(&i,0,1); 
                        EEPROMWRITE(&i,0,1); 
                        EEPROMWRITE(&i,0,1); 
                          
                          
                       //for(j=0;j<16;j++)
                       //{
                        //myDevicesOutputStatus[j] = 0x55;
                       //}
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                        
                        ConsolePutROMString((ROM char *)"\r\n Relay status updated in eeprom 55");
                      }
                      
                      EEPROMCHG = 1;
                  }
                  else
                  {
                      SDW_RLY_STATUS = 1;
                  }
              }
              else
              {
                  if(SDW_RLY_STATUS == 0)
                  {
                      RLY_1 = 0;
                      
                      if(EEPROMCHG == 1)
                      {
                       i = 0xAA;
                       EEPROMWRITE(&i,0,1); 
                       EEPROMWRITE(&i,0,1); 
                       EEPROMWRITE(&i,0,1); 
                       EEPROMWRITE(&i,0,1); 
                       EEPROMWRITE(&i,0,1); 
                          
                       //for(j=0;j<16;j++)
                       //{
                        //myDevicesOutputStatus[j] = 0xAA;
                       //}
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);   
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                          
                          
                       ConsolePutROMString((ROM char *)"\r\n Relay status updated in eeprom AA");
                      }
                      
                      EEPROMCHG = 0;
                      
                  }
                  else
                  {
                      SDW_RLY_STATUS = 0;
                  }
              }
              
              
              
              
              
              
              IRControl();
              

              EndDevStateMachine = 2;
             }
         }
         break;

//-----------------------------------------------------------------------------//

         case 2:
         {
             LED_1 ^= 1;
             EndDevStateMachine = 0;
         }
         break;

//-----------------------------------------------------------------------------//

         default:
         {
             EndDevStateMachine = 0;
         }
         break;


     }
 }
Exemplo n.º 15
0
void Repeater(void)
 {
     if( MiApp_MessageAvailable())
     {
            Printf("\r\n  ");
            if( rxMessage.flags.bits.secEn )
            {
                ConsolePutROMString((ROM char *)"Secured ");
            }

            if( rxMessage.flags.bits.broadcast )
            {
             ConsolePutROMString((ROM char *)"Broadcast Packet with RSSI ");
            }
            else
            {
             ConsolePutROMString((ROM char *)"Unicast Packet with RSSI ");
            }
            PrintChar(rxMessage.PacketRSSI);


           if( rxMessage.flags.bits.srcPrsnt )
            {
                ConsolePutROMString((ROM char *)" from ");
                if( rxMessage.flags.bits.altSrcAddr )
                {
                    PrintChar(rxMessage.SourceAddress[1]);
                    PrintChar(rxMessage.SourceAddress[0]);
                }
                else
                {
                    for(i = 0; i < MY_ADDRESS_LENGTH; i++)
                    {
                      PrintChar(rxMessage.SourceAddress[MY_ADDRESS_LENGTH-1-i]);

                    }
                }
            }

            ConsolePutROMString((ROM char *)": ");


            for(i = 0; i < rxMessage.PayloadSize; i++)
            {
              PrintChar(rxMessage.Payload[i]);
            }
         
       ClrWdt();  
       SwTimer3 = 0;  
         
       LED_2 ^= 1;
       MiApp_DiscardMessage();
       
     }
     
     
     if(SwTimer3 >= 500)           // if lost connection ... JL:Anteriormente 100, se cambio para
     {                              //lugares donde los mensajes llegan con mucho retardo entre uno y otro (area de pozo))
         Reset();
     }
 }
Exemplo n.º 16
0
int main(void)
#endif
{   
    BYTE i, j;
    BYTE OperatingChannel = 0xFF;
    BYTE TxSynCount = 0;
    BYTE TxSynCount2 = 0;
    BYTE TxPersistFailures = 0;
    BOOL ReadyToSleep = FALSE;
    BYTE TxNum = 0;
    BYTE RxNum = 0;
    BYTE PressedButton = 0;
    
    /*******************************************************************/
    // Initialize the system
    /*******************************************************************/
    BoardInit();         
    ConsoleInit();  
    DemoOutput_Greeting();

    /*********************************************************************/
    // Function MiApp_ProtocolInit intialize the protocol stack.
    // The return value is a boolean to indicate the status of the 
    //      operation.
    // The only parameter indicates if Network Freezer should be invoked.
    //      When Network Freezer feature is invoked, all previous network
    //      configurations will be restored to the states before the 
    //      reset or power cycle
    //
    // In this example, we assume that the user wants to apply Network
    //      Freezer feature and restore the network configuration if
    //      button 1 is pressed and hold when powering up.
    /*********************************************************************/
    if( (PUSH_BUTTON_1 == 0) && ( MiApp_ProtocolInit(TRUE) == TRUE ) )
    {  
        DemoOutput_NetworkFreezer();
        while(PUSH_BUTTON_1 == 0 );
    }
    else
    {
        /*********************************************************************/
        // Function MiApp_ProtocolInit intialize the protocol stack.
        // The return value is a boolean to indicate the status of the 
        //      operation.
        // The only parameter indicates if Network Freezer should be invoked.
        //      When Network Freezer feature is invoked, all previous network
        //      configurations will be restored to the states before the 
        //      reset or power cycle
        //
        // In this example, we assume that the user wants to start from
        // scratch and ignore previous network configuration if button 1
        // is released when powering up.
        /*********************************************************************/
        MiApp_ProtocolInit(FALSE);   
        DemoOutput_StartActiveScan();
            
        while(1)
        {
            /*********************************************************************/
            // Function MiApp_SearchConnection will return the number of existing 
            // connections in all channels. It will help to decide which channel 
            // to operate on and which connection to add
            // The return value is the number of connections. The connection data
            //     are stored in global variable ActiveScanResults. Maximum active
            //     scan result is defined as ACTIVE_SCAN_RESULT_SIZE
            // The first parameter is the scan duration, which has the same 
            //     definition in Energy Scan. 10 is roughly 1 second. 9 is a half 
            //     second and 11 is 2 seconds. Maximum scan duration is 14, or 
            //     roughly 16 seconds.
            // The second parameter is the channel map. Bit 0 of the double
            //     word parameter represents channel 0. For the 2.4GHz frequency
            //     band, all possible channels are channel 11 to channel 26.
            //     As the result, the bit map is 0x07FFF800. Stack will filter
            //     out all invalid channels, so the application only needs to pay
            //     attention to the channels that are not preferred.
            /*********************************************************************/
            j = MiApp_SearchConnection(10, 0xFFFFFFFF);
            OperatingChannel = DemoOutput_ActiveScanResults(j);
        
            if( OperatingChannel != 0xFF )
            {
                /*******************************************************************/
                // Function MiApp_SetChannel assign the operation channel(frequency)
                // for the transceiver. Channels 0 - 31 has been defined for the 
                // wireless protocols, but not all channels are valid for all 
                // transceivers, depending on their hardware design, operating
                // frequency band, data rate and other RF parameters. Check the
                // definition of FULL_CHANNEL_MAP for details.
                /*******************************************************************/
                MiApp_SetChannel(OperatingChannel);
                break;
            }
            DemoOutput_Rescan();
        }

        
        /*********************************************************************/
        // Function MiApp_ConnectionMode sets the connection mode for the 
        // protocol stack. Possible connection modes are:
        //  - ENABLE_ALL_CONN       accept all connection request
        //  - ENABLE_PREV_CONN      accept only known device to connect
        //  - ENABL_ACTIVE_SCAN_RSP do not accept connection request, but allow
        //                          response to active scan
        //  - DISABLE_ALL_CONN      disable all connection request, including
        //                          active scan request
        /*********************************************************************/
        MiApp_ConnectionMode(ENABLE_ALL_CONN);
        
        /*******************************************************************/
        // Function MiApp_EstablishConnection establish connections between
        // two devices. It has two input parameters:
        // The first parameter is the index of the target device in the 
        //     active scan table. It requires a MiApp_SearchConnection call
        //     before hand. If seraching connection is not performed in 
        //     advance, user can apply 0xFF to the first parameter to 
        //     indicate that it is OK to establish connection with any 
        //     device.
        // The second parameter is the connection mode, either directly or
        //     indirectly. Direct connection is a connection in the radio
        //     range. All protocol stack support this connection mode. 
        //     Indirect connection is the connection out of radio range. 
        //     An indirect connection has to rely on other device to route 
        //     the messages between two connected devices. Indirect 
        //     connection is also called "Socket" connection in MiWi 
        //     Protocol. Since MiWi P2P protocol only handles connection 
        //     of one hop, indirect connection is not supported in MiWi 
        //     P2P protocol, but supported in other networking protocols.
        // Function MiApp_EstablishConnection returns the index of the 
        //     connected device in the connection table. If no connection 
        //     is established after predefined retry times 
        //     CONNECTION_RETRY_TIMES, it will return 0xFF. If multiple 
        //     connections have been established, it will return the one 
        //     of the indexes of the connected device.
        /*******************************************************************/
        i = MiApp_EstablishConnection(0, CONN_MODE_DIRECT);
        DemoOutput_Connected();
    }
    
    // Turn on LED 1 to indicate connection established
    LED_1 = 1;
    
    /*******************************************************************/
    // Function DumpConnection is used to print out the content of the
    // P2P Connection Entry on the hyperterminal. It may be useful in 
    // the debugging phase.
    // The only parameter of this function is the index of the 
    // Connection Entry. The value of 0xFF means to print out all
    // valid Connection Entries; otherwise, the Connection Entry
    // of the input index will be printed out.
    /*******************************************************************/
    DumpConnection(0xFF);
    
    DemoOutput_Instruction();

    while(1)
    {   
        /*******************************************************************/
        // Function MiApp_MessageAvailable will return a boolean to indicate 
        // if a message for application layer has been received by the 
        // transceiver. If a message has been received, all information will 
        // be stored in rxMessage, structure of RECEIVED_MESSAGE.
        /*******************************************************************/
        if( MiApp_MessageAvailable() )
        {
            DemoOutput_HandleMessage();
            
            /*******************************************************************/
            // Function MiApp_DiscardMessage is used to release the current 
            // received message. After calling this function, the stack can 
            // start to process the next received message.
            /*******************************************************************/ 
            MiApp_DiscardMessage();
            
            // Toggle LED2 to indicate receiving a packet.
            LED_2 ^= 1;
            
            DemoOutput_UpdateTxRx(TxNum, ++RxNum);
        }
        else 
        {
            /***********************************************************************/
            // TxPersistFailures is the local variable to track the transmission 
            // failure because no acknowledgement frame is received. Typically,
            // this is the indication of either very strong noise, or the PAN
            // has hopped to another channel. 
            /***********************************************************************/
            if( TxPersistFailures > 3 )
            {
                DemoOutput_StartResync();

                /*******************************************************************/
                // Function MiApp_TransceiverPowerState is used to set the power state
                // of RF transceiver. There are three possible states:
                //   - POWER_STATE_SLEEP        Put transceiver into sleep
                //   - POWER_STATE_WAKEUP       Wake up the transceiver only
                //   - POWER_STATE_WAKEUP_DR    Wake up and send Data Request command
                /*******************************************************************/
                MiApp_TransceiverPowerState(POWER_STATE_WAKEUP);
                
                /***********************************************************************/
                // Function MiApp_ResyncConnection is used to synchronized connection
                // if one side of communication jumped to another channel, when 
                // frequency agility is performed. Usually, this is done by the 
                // sleeping device, since the sleeping device cannot hear the broadcast 
                // of channel hopping command.
                //
                // The first parameter is the index of connection table for the peer 
                // node, which we would like to resynchronize to.
                // The second parameter is the bit map of channels to be scanned
                /***********************************************************************/
                MiApp_ResyncConnection(0, 0xFFFFFFFF);    
                TxPersistFailures = 0;
                ReadyToSleep = FALSE;
                
                DemoOutput_EndResync();
            }
            else
            {
                ReadyToSleep = TRUE;
            }    
            
            /*******************************************************************/
            // If Data Request command and data transmision has been handled,
            // as the RFD device, it is time to consider put both the radio and 
            // MCU into sleep mode to conserve power.
            /*******************************************************************/
            if( ReadyToSleep )
            {   
                ReadyToSleep = FALSE;
                
                /*******************************************************************/
                // Function MiApp_TransceiverPowerState is used to set the power 
                // state of RF transceiver. There are three possible states:
                //   - POWER_STATE_SLEEP        Put transceiver into sleep
                //   - POWER_STATE_WAKEUP       Wake up the transceiver only
                //   - POWER_STATE_WAKEUP_DR    Wake up and send Data Request 
                //                              command
                /*******************************************************************/
                MiApp_TransceiverPowerState(POWER_STATE_SLEEP);
                                    
                /*******************************************************************/
                // Prepare the condition to wake up the MCU. The MCU can either be
                // waken up by the timeout of watch dog timer (Time Synchronization 
                // off), timeout of counter with external 32KHz crystal (Time 
                // Synchronization on), or by the pin change notification interrupt 
                // by pushing the button. MCU handling of sleep preparing for 
                // different demo boards can be found in HardwareProfile.c
                /*******************************************************************/
                PrepareWakeup();
                
                // Put MCU into sleep mode
                Sleep();
                
                /*******************************************************************/
                // Handling the wakeup procedure. The steps differ for different
                // demo boards and families of MCUs. Details can be found in 
                // HardwareProfile.c
                /*******************************************************************/
                AfterWakeup();
                
                PressedButton = ButtonPressed();   
                
                /*******************************************************************/
                // Function MiApp_TransceiverPowerState is used to set the power 
                // state of RF transceiver. There are three possible states:
                //   - POWER_STATE_SLEEP        Put transceiver into sleep
                //   - POWER_STATE_WAKEUP       Wake up the transceiver only
                //   - POWER_STATE_WAKEUP_DR    Wake up and send Data Request 
                //                              command
                /*******************************************************************/
                if( MiApp_TransceiverPowerState(POWER_STATE_WAKEUP_DR) > SUCCESS )
                {
                    TxPersistFailures++;
                    DemoOutput_ConnectionLost(TxPersistFailures);
                }
                else
                {
                    if( TxPersistFailures > 0 )
                    {
                        DemoOutput_UpdateTxRx(TxNum, RxNum);
                    }
                    TxPersistFailures = 0;
                }
                
                switch( PressedButton )
                {
                    case 1: 
                        /*******************************************************************/                
                        // Button 1 pressed.
                        // First use MiApp_FlushTx to reset the Transmit buffer. Then fill 
                        // the TX buffer by calling function MiApp_WriteData
                        /*******************************************************************/
                        MiApp_FlushTx();
                        for(i = 0; i < 21; i++)
                        {
                            MiApp_WriteData(MiWi[(TxSynCount%6)][i]);
                        }
                        TxSynCount++;
                        
                        /*******************************************************************/
                        // Function MiApp_BroadcastPacket is used to broadcast a message
                        //    The only parameter is the boolean to indicate if we need to
                        //    secure the message
                        /*******************************************************************/
                        MiApp_BroadcastPacket(FALSE);
                        DemoOutput_UpdateTxRx(++TxNum, RxNum);   
                        break;
      
                    case 2:
                        /*******************************************************************/                
                        // Button 2 pressed.
                        // First use MiApp_FlushTx to reset the Transmit buffer. Then fill 
                        // the TX buffer by calling function MiApp_WriteData
                        /*******************************************************************/
                        MiApp_FlushTx();                   
                        for(i = 0; i < 11; i++)
                        {
                            MiApp_WriteData(DE[(TxSynCount2%6)][i]);
                        }
                        TxSynCount2++;
                        
                        /*******************************************************************/
                        // Function MiApp_UnicastConnection is one of the functions to 
                        // unicast a message.
                        //    The first parameter is the index of connection table for 
                        //       the peer device. In this demo, since there are only two
                        //       devices involved, the peer device must be stored in the 
                        //       first Connection Entry in the connection table.
                        //    The second parameter is the boolean to indicate if we need 
                        //       to secure the frame. If encryption is applied, the 
                        //       security level and security key are defined in the 
                        //       configuration file for the transceiver
                        //
                        // Another way to unicast a message is by calling function
                        // MiApp_UnicastAddress. Instead of supplying the index of the 
                        // connection table of the peer device, this function requires the 
                        // input parameter of destination address directly.
                        /*******************************************************************/
                        if( MiApp_UnicastConnection(0, TRUE) == FALSE )
                        {
                            DemoOutput_UnicastFail();
                        }
                        else
                        {
                            TxNum++;
                        }

                        DemoOutput_UpdateTxRx(TxNum, RxNum);
                        break;
                        
                    default:
                        break;
                }
            }
        }
    }
}