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

📄 demozrfdapp.c

📁 zbee potocol 無線通訊測試.平台:microchip 18f452 與 cc2420 zbee 晶片.含coord端與rfd端
💻 C
📖 第 1 页 / 共 3 页
字号:
/*********************************************************************
 *
 *                  Demo RFD App
 *
 *********************************************************************
 * FileName:        DemoZRFDApp.c
 * Dependencies:
 * Processor:       PIC18F
 * Complier:        MCC18 v2.30 or higher
 *                  HITECH PICC-18 V8.10PL1 or higher
 * Company:         Microchip Technology, Inc.
 *
 * Software License Agreement
 *
 * The software supplied herewith by Microchip Technology Incorporated
 * (the 揅ompany? for its PICmicro?Microcontroller is intended and
 * supplied to you, the Company抯 customer, for use solely and
 * exclusively on Microchip PICmicro Microcontroller products. The
 * software is owned by the Company and/or its supplier, and is
 * protected under applicable copyright laws. All rights are reserved.
 * Any use in violation of the foregoing restrictions may subject the
 * user to criminal sanctions under applicable laws, as well as to
 * civil liability for the breach of the terms and conditions of this
 * license.
 *
 * THIS SOFTWARE IS PROVIDED IN AN 揂S IS?CONDITION. NO WARRANTIES,
 * WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
 * TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
 * IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
 * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
 *
 * HiTech PICC18 Compiler Options excluding device selection:
 *                  -FAKELOCAL -G -Zg -E -C
 *
 * 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 "zAPL.h"           // APL layer functions
#include "Debug.h"          // For debug output support
#include "zdo.h"            // Required because of custom binding
                            // Don't need to include if not using demo custom
                            // binding
#include "zAPS.h"           // For EP operations defs

#include "S2OnEndDevice.h"
#include "D1OnEndDevice.h"
#include "LedOnEndDevice.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 = 0b00000110;      // 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)"

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


// This menu is displayed when in configuration mode.
// A configuration mode can be entered by powering the board with S3 pushed down.
// Once the micro is programmed with new code, this application will
// automatically enter into config mode.
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     2: Join a network."
    "\r\n     3: Perform quick demo binding (Must perform #2 first)."
    "\r\n     4: Leave a previously joined network (Must perform #2 first)."
    "\r\n     5: Change to next channel."
    "\r\n     6: Transmit unmodulated signal."
    "\r\n     7: Transmit random modulated signal."
    "\r\n     0: Save changes and exit."

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

// enums to execute menu options.
typedef enum _MENU_CMD
{
    MENU_CMD_START = '0',
    MENU_CMD_QUIT = '0',
    MENU_CMD_SET_ID,
    MENU_CMD_JOIN,
    MENU_CMD_DEMO,
    MENU_CMD_LEAVE,
    MENU_CMD_NEXT_CHANNEL = 'A',
    MENU_CMD_UNMODULATED_OP,
    MENU_CMD_RANDOM_OP,
    MENU_CMD_STOP
} MENU_CMD;


// Various informational messages as part of configuration process.
ROM char * const testTxMsg             = "\r\n\r\nNow transmitting test signal..."
                                         "\r\nYou must reset the board to perform other action.";
ROM char * const continueMsg           = "\r\n\r\nPress any key to continue...";
ROM char * const currentChannelMsg     = "\r\n\r\nCurrent channel is ";
ROM char * const invalidValueMsg       = "\r\nInvalid value received.\r\n";
ROM char * const associateSuccessMsg   = "\r\nSuccessfully associated.\r\n";
ROM char * const associateFailMsg      = "\r\nFailed to associate.\r\n";
ROM char * const leaveSuccessMsg       = "\r\nSuccessfully left the network.\r\n";
ROM char * const leaveFailMsg          = "\r\nFailed to leave.\r\n";
ROM char * const idEntryMsg            = "\r\nEnter exact 4 digit long decimal board id: ";
ROM char * const exitMsg               = "\r\nNow running application...\r\n";
ROM char * const addrSavedMsg          = "\r\nNode is saved; Press any key to continue...\r\n";
ROM char * const resetMsg              = "\r\n******Unexpected reset occurred.******\r\n";
ROM char * const macAddrNotAssignedMsg = "\r\nMAC Address is not assigned, entering Configuration mode...\r\n";
ROM char * const D1BindingMsg          = "Attempting to bind D1 EP.\r\n";
ROM char * const S2BindingMsg          = "Attempting to bind S2 EP.\r\n";
ROM char * const LEDSrcBindingMsg         = "Attempting to bind LED_S EP.\r\n";
ROM char * const LEDDecBindingMsg         = "Attempting to bind LED_D EP.\r\n";
ROM char * const demoBindCompleteMsg   = "Demo binding complete.\r\n";
ROM char * const ledSrcBindCompleteMsg    = "LED source binding complete.\r\n";
ROM char * const ledDesBindCompleteMsg    = "LED destination binding complete.\r\n";
ROM char * const demoBindFailedMsg     = "\r\nBinding failed.  Not associated?\r\n";
ROM char * const joinAttemptMsg        = "Attempting to join a coordinator...\r\n";
ROM char * const tc77TestingMsg        = "Testing TC77...\r\n";
ROM char * const tc77ProblemMsg        = "Auto test of TC77 failed.\r\n";
ROM char * const tc77TestSuccessMsg    = "TC77 test successful.\r\n";
ROM char * const rejoinSuccessMsg      = "Rejoin successful.\r\n";
ROM char * const rejoinFailedMsg       = "Rejoin failed.\r\n";

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


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

typedef enum _CUSTOM_BIND_ACTION
{
    CUSTOM_BIND_SOURCE = 0,
    CUSTOM_BIND_DEST,
    CUSTOM_BIND_DEMO
} CUSTOM_BIND_ACTION;

static BYTE customEP;
static CUSTOM_BIND_ACTION customAction;

static void InitCustomBind(void);
static BOOL IsCustomBindComplete(void);
static BOOL IsLEDBindComplete(void);

#define StartCustomBind(action, ep)     \
{  smBind = SM_BIND_IDLE; customEP = ep; customAction = action; }

#define StartLEDCustomBind(action, ep)     \
{  ledBind = LED_BIND_IDLE; customEP = ep; customAction = action; }


/*
 * Custom binding information
 */
struct
{
    CUSTOM_BIND_ACTION cmd;
    LONG_ADDR nodeAddr;
    BYTE ep;
    BYTE clusterID;
} bindInfo;

typedef enum _SM_BIND
{
    SM_BIND_IDLE = 0,
    SM_BIND_SEND,
    SM_BIND_WAIT
} SM_BIND;

typedef enum _LED_BIND
{
    LED_BIND_IDLE = 0,
    LED_BIND_SEND,
    LED_BIND_WAIT
} LED_BIND;

static EP_HANDLE hCustomBind;
static SM_BIND smBind;
static LED_BIND ledBind;

// Custom binding functions.
#define CUSTOM_BINDER_EP                (0xfe)
#define CUSTOM_BINDER_CLUSTER_ID        (0xfe)

// 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);



void main(void)
{
    // Main state machine states.
    enum
    {
        SM_APP_INIT = 0,
        SM_APP_INIT_RUN,
        SM_APP_RUN,
        SM_APP_CONFIG_START,
        SM_APP_NORMAL_START,
        SM_APP_NORMAL_START_WAIT,
        SM_APP_NORMAL_RUN,
        SM_APP_RUN_S2_TASK,
        SM_APP_RUN_D1_TASK,
        SM_APP_RUN_BINDING_TASK,
        SM_APP_SLEEP
    } smApp;

    // 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();

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

    if ( TO == 0 )
    {
        // Clear watchdog to set TO bit.
        CLRWDT();

        // Clear flags so that we can detect it next time.
        STKPTR &= 0x3F;
        RCON |= 0x1F;

        // Display message on terminal.
        ConsolePutROMString(resetMsg);

        // Since core is going to sleep in coming lines, make sure that
        // UART finishes its transmission.
        while( !ConsoleIsPutReady() );

        // Disable all interrupts
        INTCON = 0;

        // Prepare for alternating flashing LED sequence.
        D1 = 0;
        D2 = 1;

        // On this error, blink LEDs.
        while(1)
        {
            CLRWDT();

            // This is to make sure that we don't waste battery.
            // At least one LED is always ON so saving would not be
            // that much - actual application may do something different.
            SLEEP();
            NOP();

            D1 ^= 1;
            D2 ^= 1;

        }
    }

    // Test on-board temperature sensor TC77 - This version does not use TC77.
    // This test is done here because SPI is initialized in PHY.h
    // You may change it so that SPI is initialized in main file instead of stack file.
    TestTC77();

    // This demo application uses S3 switch to enter into configuration mode.
    // Actual application may implelement any logic to select configuratoin mode
    // or may not have any - completely application dependent.
    if ( S3 == 0 )
        appFlags.bits.bInConfigMode = TRUE;


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

    // This is main Zigbee stack initialization call.
    // MAC will be in disable state until enabled.
    APLInit();

    // We have to enable MAC separately. This way you can disable and enable as per your
    // requirement.
    APLEnable();

    // Start with Init state.
    smApp = SM_APP_INIT;

    // 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();

        // This is the main stack task, responsible for Zigbee stack related functionality.
        // This function must be called before all Zigbee tasks.
        // Actual application task function can be called in any order.
        APLTask();

        // This demo application provides two modes of operations - config and normal.
        // In config mode, this node will attempt to associate with available coordinator.
        // In normal mode, it will simply rejoin previously associated coordinator.
        // You may change this logic as per your application requirements.
        switch(smApp)
        {
        case SM_APP_INIT:
            // Initialize all local end point tasks
            InitCustomBind();
            //S2Init();
            //D1Init();
	    LEDInit();

            // If S3 was pressed on startup, go to config mode.
            if ( appFlags.bits.bInConfigMode == TRUE )
                smApp = SM_APP_CONFIG_START;

            // Or else go in normal mode.
            else
                smApp = SM_APP_NORMAL_START;

            break;


        case SM_APP_CONFIG_START:
            // While in config mode, disable watchdog.
            // Normally, you would want to keep watchdog enabled all the time, but in this demo that would
            // amount to increased complexity and make this demo difficult to understand.
            // Actual application code may afford extra complexity.
            DISABLE_WDT();

            DEBUG_OUT("In Configuration mode...\r\n");

            // This is a blocking call. Note that watchdog is already disabled.
            ConfigTask();

            // Mark that we are no longer in config mode.
            appFlags.bits.bInConfigMode = FALSE;

            smApp = SM_APP_NORMAL_START;

            // After config mode, enable watchdog
            ENABLE_WDT();

            break;

        case SM_APP_NORMAL_START:
            // In normal mode, this node will try to rejoin previously associated network.
            // This will make sure that we join to a known network.
            // Actual logic would depend on the application requirements.
            DEBUG_OUT("Rejoining previous network...\r\n");

            APLRejoin();

            smApp = SM_APP_NORMAL_START_WAIT;
            break;

        case SM_APP_NORMAL_START_WAIT:
            // See if rejoin is complete.

⌨️ 快捷键说明

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