⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 demozrfdapp.c

📁 通过cc2420+pic实现无线通信
💻 C
📖 第 1 页 / 共 2 页
字号:
/*********************************************************************
 *
 *                  Demo RFD App
 *
 *********************************************************************
 * FileName:        DemoZRFDApp.c
 * Dependencies:
 * Processor:       PIC18F
 * Complier:        MCC18 v2.30 or higher
 *                  HITECH PICC-18 V8.10PL1 or higher
 * Author               Date    Comment
 *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * Nilesh Rajbharti     7/12/04 Rel 0.9
 * Nilesh Rajbharti     11/1/04 Pre-release version
 *
 *    组团协议
 *******************************************************************/
// Uncomment ENABLE_DEBUG line to enable debug mode for this file.
// Or you may also globally enable debug by defining this macro
// in zigbee.h file or from compiler command-line.
#ifndef ENABLE_DEBUG
//#define ENABLE_DEBUG
#endif

#if defined(WIN32)
#include <stdio.h>
#endif

#include <string.h>
#include "zigbee.h"         // Zigbee defs
#include "Tick.h"           // Tick manager
#include "Debug.h"          // For debug output support
#include "zMAC.h"
#include "S2OnEndDevice.h"
#include "D1OnEndDevice.h"

#if defined(WIN32)
    #include "physim.h"     // Not distributed.
#endif


// Switches and LEDs locations.
#define S2              RB5
#define S3              RB4

#define D1              LATA0
#define D2              LATA1

// This defines how LEDs will be blinked when unexpected RESET is detected.
#define FATAL_ERROR_BLINK_PERIOD    (1*TICK_SECOND)

// Configuration fuse bits.
// If other than 18F4620 device is used, you must define config values of your
// choice or set them via MPLAB interface.
#if defined(MCHP_C18) && defined(__18F4620)
    #pragma romdata CONFIG1H = 0x300001
    const rom unsigned char config1H = 0b00000010;      // HSPLL oscillator

    #pragma romdata CONFIG2L = 0x300002
    const rom unsigned char config2L = 0b00011111;      // PWRTEN disabled, BOR enabled in hardware @ 2.0V

    #pragma romdata CONFIG2H = 0x300003
    const rom unsigned char config2H = 0b00001110;      // HW WD disabled, 1:128 prescaler

    #pragma romdata CONFIG3H = 0x300005
    const rom unsigned char config3H = 0b10000001;      // PORTB digital on RESET

    #pragma romdata CONFIG4L = 0x300006
    const rom unsigned char config4L = 0b10000001;      // DEBUG disabled,
                                                        // XINST disabled
                                                        // LVP disabled
                                                        // STVREN enabled

    #pragma romdata

#elif defined(HITECH_C18) && defined(_18F4620)
    // Set configuration fuses for HITECH compiler.
    __CONFIG(1, 0x0600);    // HSPLL oscillator
    __CONFIG(2, 0x0E1F);    // PWRTEN disabled, HW WD disabled, 1:64 prescaler, BOR enabled in hardware @ 2.0V
    __CONFIG(3, 0x8100);    // PORTB digital on RESET
    __CONFIG(4, 0x0081);    // DEBUG disabled,
                            // XINST disabled
                            // LVP disabled
                            // STVREN enabled
#endif


#define STARTUP_MSG "ZigBee Demo RFD Application v1.0 (Microchip Stack for ZigBee v1.0.0)"
#define MAC_RESPONSE_WAITFOR_DURATION  (50)
#define MAC_ACK_WAITFOR_DURATION   (50)
#define QUERY_INT_DURATION  (200)
#define MAC_QUERY_WAIT_DURATION (25)
#define MAC_WAITFOR_QUERY_DURATION (250)


#if defined(ENABLE_DEBUG)
    #define BUILD_MODE  " (Debug Build)"
#else
    #define BUILD_MODE  " (Non-debug Build)"
#endif

ROM char * const menu =
    "\r\n"
    "\r\n****************************************************************************"
    "\r\n"STARTUP_MSG       \
    "\r\n     Built on " __DATE__ BUILD_MODE
    "\r\n****************************************************************************"

    "\r\n     1: Set node ID..."
    "\r\n     0: Save changes and exit."

    "\r\n\r\nEnter a menu choice: ";

typedef enum _MENU_CMD
{
    MENU_CMD_START = '0',
    MENU_CMD_QUIT = '0',
    MENU_CMD_SET_ID,

} MENU_CMD;
// Various informational messages as part of configuration process.
ROM char * const idEntryMsg            = "\r\nEnter  long decimal board id(0-10000): ";
ROM char * const exitMsg               = "\r\nNow running application...\r\n";
ROM char * const resetMsg              = "\r\n******Unexpected reset occurred.******\r\n";
ROM char * const invalidValueMsg       = "\r\nInvalid value received.\r\n";
ROM char * const macAddrNotAssignedMsg = "\r\nMAC Address is not assigned, entering Configuration mode...\r\n";

// Private variables
static union
{
    struct
    {
        unsigned int bInConfigMode : 1;
        unsigned int S2Toggled : 1;
	unsigned int S3Toggled : 1;
    } bits;
    BYTE Val;
} appFlags;


// Private helper functions
static void InitializeBoard(void);
static void ConfigTask(void);
static BOOL ExecuteMenuChoice(MENU_CMD choice);


// Persistent MAC address, defined in "NVM.c" file.
extern ROM LONG_ADDR macLongAddr;


#define SaveMACLongAddr(a) \
            NVMWrite((NVM_ADDR*)&macLongAddr, (BYTE*)a, sizeof(LONG_ADDR))
static BOOL IsMACAddrAssigned(void);

static BYTE taskswitchcount,chanalcount;

NODE_STUTAS  thisnode;
TICK  current_time0;
TICK  current_time1;
TICK  current_time2;
TICK  starttime0;
TICK  starttime1;

BYTE  Newcaptain[2];
BOOL GROUPUpdate();
void ResetsubmacCurrentFrame();
void JudgeNewCaptain();
//BOOL INTCOUNT(TICK START,TICK CURRENT,TICK DURATION);
void ConsolePutInitData(int highval,int lowval);

void main(void)
{
    // Main state machine states.
    enum
    {       
        SM_APP_WAIT_FOR_RESPONSE,
        SM_APP_WAIT_FOR_ACK,
        SM_APP_CAPTAINSLEEP,
        SM_APP_WAIT_FOR_ACK_QUERY,
        SM_APP_MEMBERSLEEP
    } smApp;
BYTE i;
BYTE j;


BYTE a;
BYTE u=0;
    // Enable watchdog
    ENABLE_WDT();

    // Clear all flags in the begining.
    appFlags.Val = 0x00;

    // Initialize the board hardware.
    InitializeBoard();

    // This is to initialize tick manager required for Zigbee stack modules.
    TickInit();
    starttime0=TickGet();
    

    // Blink on LEDs on startup to provide visual feedback
    // LEDs are turned off before main loop is started.
    D1 = 1;
    D2 = 1;
	
ConsolePutROMString(exitMsg);



  
if ( S3 == 0)
        	appFlags.bits.bInConfigMode = TRUE;


	// If MAC long address is not assigned, enter configuration by default.
	if ( !IsMACAddrAssigned() )
	{    
	BYTE        *p;

		// Initialize the MAC address
		p = (BYTE *)&macInfo.longAddr;
		*p++ = 0xe4;//MAC_LONG_ADDR_BYTE0;
		*p++ = 0x03;//MAC_LONG_ADDR_BYTE1;
		*p++ = MAC_LONG_ADDR_BYTE2;
		*p++ = MAC_LONG_ADDR_BYTE3;
		*p++ = MAC_LONG_ADDR_BYTE4;
		*p++ = MAC_LONG_ADDR_BYTE5;
		*p++ = MAC_LONG_ADDR_BYTE6;
		*p   = MAC_LONG_ADDR_BYTE7;
       //NVMWrite((NVM_ADDR*)&macLongAddr, (BYTE*)macInfo.longAddr, sizeof(LONG_ADDR))
SaveMACLongAddr(&macInfo.longAddr);

		// Now ask the Stack to set our address in the transceiver.
	//	MACUpdateAddressInfo();
}

    // If MAC long address is not assigned, enter configuration by default.
  /*  if ( !IsMACAddrAssigned() )
    {
        ConsolePutROMString(macAddrNotAssignedMsg);
        appFlags.bits.bInConfigMode = TRUE;
    }*/

    if( appFlags.bits.bInConfigMode == TRUE)
    	{DISABLE_WDT();
	  ConsolePutROMString("In Configuration mode...\r\n");					          
	 ConfigTask();
            // Mark that we are no longer in config mode.
         appFlags.bits.bInConfigMode = FALSE;
           // After config mode, enable watchdog
         ENABLE_WDT();
        appFlags.bits.S3Toggled = FALSE;
	}
	
	//APLInit();
	MACInit();
       submacCurrentFrame.sub_type.Val=0xff;
		
	MACEnable();
	// Start with Init state.

//init thisnode
       chanalcount = 15;
	PHYSetChannel(chanalcount );
	S2Init();
	D1Init();
	//Send1();
	//MACStart();		
	PHYSetTRXState(PHY_TRX_RX_ON);
       thisnode.NODEID[0]=macInfo.longAddr.v[0] ;
       thisnode.NODEID[1]=macInfo.longAddr.v[1] ;
       thisnode.NODESTATE=GROUP_CAPTAIN;  //ADD BY YY
       thisnode.MEMBERNUM=0;
	ConsolePutROMString("This node's ID is:");
	ConsolePutInitData(thisnode.NODEID[1],thisnode.NODEID[0]);
	
	
	smApp = SM_APP_CAPTAINSLEEP;

	// Turn off LEDs
	D1 = 0;
	D2 = 0;

	while( 1 )
	{
		// Toggle RA4 to indicate how long we execute this loop
		LATA4 ^= 1;

		// Keep watchdog happy
		CLRWDT();

		//APLTask();
		MACTask();
		if ( MACIsGetReady() )
		{
			NOP();
			MACDiscardRx();
		}
              a=submacCurrentFrame.sub_type.Val;
              
if(D1Task())
	{	D2=0;
	     switch(smApp)
		{
                case SM_APP_WAIT_FOR_RESPONSE://add by yy
                      if(a==MEMBER_ALERT)
                      	{
				  ConsolePutROMString("The node in danger is:");
				  ConsolePutInitData(submacCurrentFrame.sub_source_addr.v[1],submacCurrentFrame.sub_source_addr.v[0]);
                              ResetsubmacCurrentFrame();
			       }
                     else 
                         {if(a==RESPONSE_UNITE_REQ)			      
                           {JudgeNewCaptain();  
                            SEND(ACK_UNITE) ;				 
				 if( GROUPUpdate())
				              { smApp=SM_APP_CAPTAINSLEEP;
				                ConsolePutROMString("This node's member num is:");
				                ConsolePut(thisnode.MEMBERNUM+0x30);
						  ConsolePut('\r');	
                                            ConsolePut('\n');						  
						  ConsolePutROMString("This node's members are:");
						  j=0;
						  while(j<thisnode.MEMBERNUM*2)
						  	{ConsolePutInitData(thisnode.MEMBER_OR_CAPTAIN[j+1],thisnode.MEMBER_OR_CAPTAIN[j]);
						         j=j+2;
						  	}
						 if(thisnode.MEMBERNUM==MAX_NUM)
                                           ConsolePutROMString("This node's member number is MAX!\r\n"); 
				 	       }
			 	 else       				    
			 	              {starttime1=TickGet();
			 	                smApp=SM_APP_MEMBERSLEEP;
			 	        	}
				 ConsolePutROMString("Complete unite!\r\n");				 
				 ResetsubmacCurrentFrame();
                           }					 
                     else
				if ( TickGetDiff(TickGet(), current_time0) >=MAC_RESPONSE_WAITFOR_DURATION )
                                 {ConsolePutROMString("Wait for response time out!\r\n");
					smApp=SM_APP_CAPTAINSLEEP;
                            	} 	
                     	}
		  break;



                case  SM_APP_WAIT_FOR_ACK:
			 if(a==MEMBER_ALERT)
                      	{
				  ConsolePutROMString("The node in danger is:");
				  ConsolePutInitData(submacCurrentFrame.sub_source_addr.v[1],submacCurrentFrame.sub_source_addr.v[0]);
				  ResetsubmacCurrentFrame();
                      	}
                      else 
			   {if(a==ACK_UNITE)
                          { Newcaptain[0]=submacCurrentFrame.data[ submacCurrentFrame.databytenum-2];
			       Newcaptain[1]=submacCurrentFrame.data[ submacCurrentFrame.databytenum-1];
				if( GROUPUpdate())
				    {smApp=SM_APP_CAPTAINSLEEP;
				     ConsolePutROMString("This node's member num is:");
				     ConsolePut(thisnode.MEMBERNUM+0x30);
				     ConsolePut('\r');	
                                 ConsolePut('\n');	
				     ConsolePutROMString("This node's members are:");
					 j=0;
				     while(j<thisnode.MEMBERNUM*2)
						 {ConsolePutInitData(thisnode.MEMBER_OR_CAPTAIN[j+1],thisnode.MEMBER_OR_CAPTAIN[j]);
						   j=j+2;
						 }	
				      if(thisnode.MEMBERNUM==MAX_NUM)
                                  ConsolePutROMString("This node's member number is MAX!\r\n"); 
				    }
			 	else  
					{starttime1=TickGet();
			 	         smApp=SM_APP_MEMBERSLEEP;
			 	       }			 	 
				ConsolePutROMString("Complete unite!\r\n");
				ResetsubmacCurrentFrame();
                           }                     
			else
				if ( TickGetDiff(TickGet(), current_time1) >=MAC_ACK_WAITFOR_DURATION )
			       {ConsolePutROMString("Wait for ack time out!\r\n");
			         smApp=SM_APP_CAPTAINSLEEP; 
                     	}
                      	}
		    break;

			

                  case SM_APP_CAPTAINSLEEP:
			     if(a==MEMBER_ALERT)
                      	{
				  ConsolePutROMString("The node in danger is:");
				  ConsolePutInitData(submacCurrentFrame.sub_source_addr.v[1],submacCurrentFrame.sub_source_addr.v[0]);
				  ResetsubmacCurrentFrame();
                      	}
			     if(TickGetDiff(TickGet(),starttime0)>=QUERY_INT_DURATION)
                             {SEND(QUERY_MEMBER);
			          smApp=SM_APP_WAIT_FOR_ACK_QUERY;
				   current_time2=TickGet();
		                 starttime0=TickGet();
                     	 }				
			     else
                              if(thisnode.MEMBERNUM<MAX_NUM)  			     
				   {if(a==UNITE_REQ)
					  { if((submacCurrentFrame.data[0]+thisnode.MEMBERNUM+1)<=MAX_NUM)
			                      {SEND(RESPONSE_UNITE_REQ) ;
		                               smApp=SM_APP_WAIT_FOR_ACK;
			                        current_time1=TickGet();			                  	 
					          ResetsubmacCurrentFrame();
						  }					   
					   }
						   
				     else 
					   {SEND(UNITE_REQ) ;
			                   smApp =SM_APP_WAIT_FOR_RESPONSE;			
			                   //GIEL = 0;			
		                          current_time0=TickGet();							
					    }
				   }				  	
		    break;






                  case SM_APP_WAIT_FOR_ACK_QUERY:
		   if(a==MEMBER_ALERT)
                      	{
				  ConsolePutROMString("The node in danger is:");
				  ConsolePutInitData(submacCurrentFrame.sub_source_addr.v[1],submacCurrentFrame.sub_source_addr.v[0]);
				  ResetsubmacCurrentFrame();
                      	}
                 else
		     {if( a==ACK_QUER)
				{thisnode.MEMBER_OR_CAPTAIN[u]=submacCurrentFrame.sub_source_addr.v[0];
			         thisnode.MEMBER_OR_CAPTAIN[u+1]=submacCurrentFrame.sub_source_addr.v[1];
                              u=u+2;
				  //ConsolePutROMString("Receive a ack query frame!\r\n");			  
				  ResetsubmacCurrentFrame();			 
				 }							                       
			else 
			     if ( TickGetDiff(TickGet(), current_time2) >=MAC_QUERY_WAIT_DURATION )
				{ConsolePutROMString("The end  time waiting for query  reach!\r\n");
				  ConsolePutROMString("The current member number is:");				 
				  thisnode.MEMBERNUM=u/2;
			         u=0;
				  ConsolePut(thisnode.MEMBERNUM+0x30);
				  ConsolePut('\r');	
                              ConsolePut('\n');
                              if(thisnode.MEMBERNUM!=0)
				       {ConsolePutROMString("They are:");
				         j=0;
				         while(j<thisnode.MEMBERNUM*2)
					      {ConsolePutInitData(thisnode.MEMBER_OR_CAPTAIN[j+1],thisnode.MEMBER_OR_CAPTAIN[j]);
					        j=j+2;
					      }	
                                    }
			         smApp=SM_APP_CAPTAINSLEEP;
				}
                 	}
		break;



					
		    case SM_APP_MEMBERSLEEP:
			if ( appFlags.bits.S2Toggled ) // 按下 S2 按键
			{     for(i=0;i<5;i++)
				SEND(MEMBER_ALERT);  //发送5个包
				appFlags.bits.S2Toggled = FALSE;
			}
			
			else
			   {if(a==CAPTAIN_INF)
			        {if(submacCurrentFrame.sub_source_addr.v[0]==thisnode.MEMBER_OR_CAPTAIN[0]&&
                                          submacCurrentFrame.sub_source_addr.v[1]==thisnode.MEMBER_OR_CAPTAIN[1])
	                         { thisnode.MEMBER_OR_CAPTAIN [0]=submacCurrentFrame.data[0];
	                            thisnode.MEMBER_OR_CAPTAIN [1]=submacCurrentFrame.data[1];
					ConsolePutROMString("This node's captain is changedto be:");
					ConsolePutInitData(thisnode.MEMBER_OR_CAPTAIN[1],thisnode.MEMBER_OR_CAPTAIN[0]);					
                                   ResetsubmacCurrentFrame();}
				 }
                         else  
			         {if( a==QUERY_MEMBER)
			            { if(submacCurrentFrame.sub_source_addr.v[0]==thisnode.MEMBER_OR_CAPTAIN[0]&&
                                           submacCurrentFrame.sub_source_addr.v[1]==thisnode.MEMBER_OR_CAPTAIN[1])
			                   {
			                      TICK iii;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -