// *********************************************************************
// *                          E09 - LINK                               *
// *                           RF link                                 *
// *********************************************************************
// Example of simple RF link checker.
//
// Intended for:
//   HW: - TR-7xG (types with LEDs on board) + CK-USB-04x, DK-EVAL-04x development kit (2 pcs.)
//
//   OS: - v4.06G
//
// Description:
//   - This program applied in two devices perpetually transmits
//     and attempts to receive RF packets. Green LED indicates transmitting
//     and red LED indicates every successful receipt.
//   - Thus, red LED flashing indicates RF connection.
//     This can be used for RF range test.
//   - For better synchronization RF timeouts are set to vary slightly
//     from part to part.
//
// ---------------------------------------------------------------------
// Online IQRF OS Reference Guide: https://doc.iqrf.org/IQRF-OS-Reference-guide
//
// Copyright (c) IQRF Tech s.r.o.
//
// File:    E09-LINK.c
// Version: v3.00                                   Revision: 10/06/2021
//
// Revision history:
//   v3.00: 10/06/2021  First release for TR-7xG.
//
// *********************************************************************
// Default IQRF include (modify the path according to your setup)
#include "IQRF.h"

// *********************************************************************
#define RX_FILTER               0
#define DELAY                   40          // Delay between pings

// *********************************************************************

void APPLICATION()
{
uns8 random, trType;

    moduleInfo();
    trType = bufferINFO[5] & 0xF0;          // Get TR type (high nibble of bufferINFO[5])
    if (trType == 0xC0)                     // The max. allowed TX power for TR-77Dx is level 6.
        setRFpower(6);
        
    setRFmode(_WPE | _RX_STD | _TX_STD);
    toutRF = 1;

    while (1)
    {
        PIN = 0;
        DLEN = 10;
        RFTXpacket();                       // Send RF packet
        pulseLEDG();

        random = randomValue & 0x07;        // Get random value generated by IQRF OS
        random += DELAY;                    // Variable timeout based on TMR6 reg and lowest MID byte.

        startDelay(random);
        
        while (isDelay())
        {
            if (checkRF(RX_FILTER))
            {
                if (RFRXpacket())           // RF packet received?
                {                           // Yes:
                    pulseLEDR();            //   Indicate by red LED
                    waitDelay(DELAY >> 2);
                    break;
                }
            }
        }
    } 
}

// *********************************************************************
