.. _sec-custom-hardware:

Custom Hardware
===============

This section will explain how to adapt a |STACK| application from the |SDK| to run on
custom hardware. In general, the steps required to migrate a |STACK| application
from a development kit to a custom board are minimal and involve changing the
pin configuration as well as selecting the correct RF configuration.
These steps, including a bring up guide, are detailed in the subsections below.

Designing a Custom Board
------------------------

Design guidelines for CC13x2 and CC26x2 boards can be found in the `CC13xx/CC26xx
Hardware Configuration and PCB Design Considerations`_ app note. This app note
includes RF front-end, schematic, PCB, and antenna design considerations. The
report also covers crystal oscillator tuning, optimum load impedance as well as
a brief explanation of the different power supply configurations.

.. note::
  A similar app note will be produced for the |DEVICE| devices. In the meantime,
  we recommend leveraging the reference designs available in the MSR folder.

Creating a Custom Board File
----------------------------

Board files are used by TI drivers to store device specific settings and I/O
mapping. The board file abstraction allows one TI-drivers implementation
to support many hardware implementations by just setting up new board files.
Examples utilize SysConfig to generate these board files. The generated
structures are placed in the ``ti_drivers_config.c`` and ``ti_drivers_config.h``
files. The SysConfig user interface can be utilized to determine pins and
resources used. Information on pins and resources used is also present in both
of these generated files. It is recommended to use SysConfig to generate the
board files for custom hardware as described
`here <https://software-dl.ti.com/ccs/esd/sysconfig/docs/guide/custom-board.html>`_.

.. only:: sdk_includes_ble

  Clock configuration for Bluetooth LE
  ------------------------------------

  Clock accuracies and Bluetooth LE
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  The |CORESPEC| defines two clock accuracies, the "Active clock accuracy"
  (|CORESPEC| Vol 6, Part B, §4.2.1) and the "Sleep clock accuracy"
  (|CORESPEC| Vol 6, Part B, §4.2.1).
  In general, the HF XTAL (high frequency crystal oscillator) is used as active
  clock and the LF XTAL (low frequency crystal oscillator) is used as sleep
  clock. Tuning of the HF XTAL and LF XTAL is discussed in the 
  `HW Configuration Guide <https://www.ti.com/lit/swra640>`_.

  The |CORESPEC| require the active clock to have a drift less than or equal
  to ±50 ppm and there is no way (nor need) to specify its accuracy to the
  |BLE5_STACK|.

  The |CORESPEC| require the sleep clock to have a drift less than or equal
  to ±500 ppm. The accuracy of this clock has a real impact on the timing of
  the radio operations. This is why its accuracy should be communicated to
  the |BLE5_STACK| using the function :ble_api:`HCI_EXT_SetSCACmd`.

  As mentioned before, the accuracy of the sleep clock has an impact on the
  timing of the radio operations. This effect is called window widening and is
  described in details in the |CORESPEC| Vol 6, Part B, §4.2.4.

    *The Link Layer is expecting to receive a packet within a certain window
    (extending from receiveWindowStart to receiveWindowEnd) or at a certain time
    (in which case receiveWindowStart and receiveWindowEnd are both that time)
    but, because of active clock accuracies and sleep clock accuracies there is
    uncertainty as to the exact timing of that window at the sending Link Layer.
    The recipient should therefore adjust its listening time to allow for this
    uncertainty. The increase in listening time is called the window widening.
    Assuming the clock inaccuracies are purely given in parts per million (ppm),
    it is calculated as follows:*

      .. math::

        \textrm{transmitterAllowance} = (\textrm{txCA} / \textrm{1000000}) * (\textrm{receiveWindowEnd} - \textrm{timeOfLastSync}) + \textrm{J us}

    *where J shall be 2 when the active clock applies and 16 when the sleep clock
    applies and the other parameters are specified in Table 4.1. of* |CORESPEC|
    *Vol 6, Part B, §4.2.4.*

  The connection parameters can be chosen independently of the clock accuracy
  – absolutely all the combinations of clock accuracy and connection parameters
  are allowed. As can be observed in the formula, for a given clock accuracy,
  the listening window length is proportional to the effective connection
  interval. At a certain point this might have a significant impact on the
  energy consumption.
  
  Using 32-kHz Crystal-Less Mode (LFOSC)
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  |STACKVER| includes support for operating the |DEVICEHIGH| in a 32-kHz
  crystal-less mode for all BLE roles, and |DEVICELOW| for peripheral and broadcaster (beacon) role configurations.
  By using the internal low-frequency RC oscillator (LFOSC), the 32-kHz crystal
  can be removed from the board layout.

  LFOSC should be enabled as Low Frequency clock
  in ``SysConfig`` -> ``TI Devices`` -> ``Device Configuration`` ->
  ``Low Frequency Clock Source`` selecting ``LF RCOSC``.
  This leads SysConfig to generate code to enable the usage of the
  LFOSC by calling ``PowerLPF3_selectLFOSC()`` in the ``Board_init()``
  function (``ti_drivers_config.c`` file). 
  
  For the |DEVICELOW|, other configurations are
  set by SysConfig at the same time to ensure the stack accounts for the
  lower LF clock accuracy obtained by applying the workaround described in
  the |DEVICELOW| errata document for Advisory CLK_01. The Sleep Clock Accuracy (SCA) 
  obtained with the LFOSC is not as accurate as
  a 32-kHz crystal. For this reason,

  * In accordance with the |CORESPEC|, the first listening (Rx)
    operation duration of the Bluetooth LE connection events are increased.
    The longer time between connection events, the more the Rx operation
    durations are increased, directly impacting the average power consumption
    (see |CORESPEC| Vol 6, Part B, §4.2.2 for details on the Rx window
    calculation). The power consumption while advertising is not impacted, 
    making the 32-kHz crystal-less mode particularly advantageous for beacon-applications
    or for use-cases requiring infrequent connections and/or 
    short connection intervals.

  * Connection events are more likely to be missed. When a connection event is
    missed, the device enlarges its Rx window to increase chances to catch
    the next connection event. The Rx window duration is reverted to its
    regular duration after properly ack-ed connection events. 
    The duration of the Rx window used after an unsuccessful connection event
    depends on the maximum inaccuracy expected on the LFOSC.
    The parameter ``Peripheral Extra LFOSC PPM`` in ``SysConfig`` -> ``BLE``
    -> ``Advanced Settings`` (only available when LFOSC has been selected)
    should be set with the maximum inaccuracy expected on the LFOSC.
    The default value set in SysConfig is expected to fit most of the use cases. 
    Developers can consider adjusting this value based on the specific requirements
    of the use case targeted.

  * The Sleep Clock Accuracy (SCA) is automatically set by the stack to the
    maximum value (500 ppm). Overwriting this value may lead to connection
    establishment issues and frequent disconnections.  

For the |DEVICEHIGH|, a Sleep Clock Accuracy (SCA) of 500 ppm can be achieved by measuring 
LFOSC to HFXT and periodically calibrating the LFOSC. This can be done by doing the following:

  1.  Set ``Enable LFOSC Compensation`` in ``SysConfig`` -> ``TI Devices`` -> 
  ``Device Configuration`` -> ``LFOSC Compensation``.
  
  2.  Click on ``Add`` under ``LFOSC Compensation Profiles``.

  3.  Fill in the parameters for ``LFOSC Compensation Profiles`` according to your system requirments. For BLE applications, ``System PPM Requirement`` should be set to maximum 500 ppm.

RF Temperature Compensation
^^^^^^^^^^^^^^^^^^^^^^^^^^^

If the selected HFXT source is not accurate enough for the selected RF protocol, 
RF temperature Compensation may be enabled via ``SysConfig`` |rarr| ``TI Devices``
|rarr| ``Device Configuration``. RF Temperature Compensation compensates HFXT frequency
for temperature during radio transmissions. This improves the accuracy of the 
CLKSVT and CLKREF over temperature. 

  .. note:: 
    Each crystal will have different parameters. You may request the parameters for
    your specific crystal by contacting the crystal vendor/manufacturer. 

  * HFXT Compensation Threshold: HFXT will only be automatically compensated
    when the measured device temperature exceeds this threshold (in degrees
    Celsius). This can help to reduce power consumption if temperature
    compensation is not required below a certain temperature. If set to -41,
    then compensation will be enabled across the entire operating temperature
    range of [-40, +125].

  * HFXT Compensation Delta: HFXT will be automatically compensated if the
    temperature drifts more than this delta-value in either direction (in
    degrees Celsius). For example, if the temperature is measured to 30 degrees
    when the device boots (measured within ``Board_init()``), but later drifts
    to 30 + delta or 30 - delta, then HFXT temperature compensation will be
    performed, and the temperature setpoint updated accordingly.

  .. note::
    Temperature is calculated using the Temperature driver. Please see
    :tidrivers_api:`Temperature.h` for more information.

Configuring Device Parameters for Custom Hardware
-------------------------------------------------

  1.  Set parameters, such as the sleep clock accuracy of the 32.768-kHz
      crystal. 

  2.  Define the CCFG parameters in Device Configuration in SysConfig.

.. note::
    For a description of CCFG configuration parameters, see the |TRM|.

.. _sec-creating-a-custom-ble-app-rf-front-end-and-antennas:

HFXT Amplitude Compensation 
---------------------------

High Frequency Crystal (HFXT) Amplitude Compensation feature adjusts the power amplitude to 
ensure the high frequency crystal receives sufficient power. The standard HFXT Amplitude 
Compensation is always enabled - the |DEVICE| power driver takes care of this.

* HFXT Amplitude Compensation: At boot within ``Power_init()``, HFXT amplitude is configured
  to the highest possible value. After this, HFXT amplitude is adjusted to the 
  optimal value each time the device enters standby. It will take up to five iterations after 
  boot until the optimal amplitude is found. This process ensures that the amplitude 
  remains in an optimal range if operating conditions change. This feature will 
  always be enabled, unless Initial HFXT Amplitude Compensation is enabled. 
  
* Initial HFXT Amplitude Compensation: If the application rarely enters
  standby, initial HFXT Amplitude Compensation can be enabled when the application requires  
  the optimal amplitude to be found at or after boot. HFXT will take longer 
  to be ready after boot, but when ready the amplitude is already in the 
  optimal range. This process is done asynchronously and is enabled via ``SysConfig`` |rarr| 
  ``TI Devices`` |rarr| ``Device Configuration`` |rarr| ``Initial HFXT Amplitude Compensation``.

  .. note:: 
    Enabling initial HFXT amplitude compensation will result in more flash usage 
    and a longer time from boot to first RF operation.

Initial Board Bring Up
----------------------

When powering up a custom board with the |DEVICE| for the first time, it is
recommended to follow the Board Bring-Up section on `CC13xx/CC26xx Hardware
Configuration and PCB Design Considerations`_. After confirming that the board
is being powered correctly by the battery or power supply and can be identified
by the SWD tool, programming the device with a minimal SW application to verify
stability is also suggested.

.. only:: sdk_includes_ble

  TI recommends using the basic_ble sample application for initial board
  bring up with modifications to the ``ti_drivers_config.c`` file to:

  1. Disable all GPIO pin access
  2. Select the correct RF front end setting (done by SysConfig)


  The TI |STACK| does not require any GPIO pins to be configured in order to
  establish and maintain a BLE connection. Ensure that ``Display_DISABLE_ALL``
  is defined in the application Predefined Symbols so that diagnostic logging
  data is not routed to any GPIO pin. If your custom board uses a different device
  configuration, such as the 32 kHz crystal-less RCOSC_LF configuration, be sure
  to make these device changes to the project. With this minimal application
  configuration you should be able to establish a BLE connection
  (e.g., with a smart phone or BTool) to your board at the expected range.
  If you are not able to complete this step, then it is likely there is a
  misconfiguration of the RF front end or you have other board related or layout
  issues.

  After confirming that your board can maintain a BLE connection, you can now
  validate that your BLE application functions as expected on the custom board.
  Again, it is suggested to enable your GPIO pins one at a time in the board file
  and comment-out access to other GPIO pins in your application. If you do
  encounter a CPU exception (HWI abort) during this phase it is likely that a
  GPIO pin is incorrectly mapped in your custom board file or your application is
  attempting to access a GPIO pin that does not exist in your device package type.

.. _sec-migrating_to_qfn24_4x4:

Using the RGE QFN24 package variant
-----------------------------------

The |DEVICE| is also available with a 4-mm x 4-mm RGE QFN24 (12 GPIOs) package 
variant. See the `CC23xx Datasheet`_ for all the package options and IO descriptions.

In order to build |SDK| project using the RGE package, a few settings must be made
in SysConfig.

* First open the SysConfig file, click the icon on the top right hand corner ``Show Board View``
* Click the button ``SWITCH``
* Select ``NONE`` in the Board | New Value field
* Select the ``CC2340R5RGE`` device in the Device field. It automatically updates the package to ``RGE``.
* Finally click ``CONFIRM``

.. _fig-SysConfig_RGE_Package_Switch_CC23xx:
.. figure:: resources/SysConfig_RGE_Package_Switch_CC23xx.png
    :align: center

    Switch to RGE Package

After clicking ``CONFIRM``, the pins of the SysConfig file may change. If error
messages appear, check that the pins changed in SysConfig are consistent with
the implemented hardware design.

.. figure:: resources/SysConfig_RGE_Package_Switch_CC23xx_Error.png
    :align: center

    Check the new configuration generated by SysConfig

For each error, review the suggested configuration value,
and accept it or modify it.
  
Tuning HFXT capacitors 
----------------------

One of the features offered by SmartRF Studio 8 is the ability to tune the HFXT capacitors. 
Generally the RF link could be affected by variations in hardware, this is normally difficult to
fix; however with HFXT the RF link can be adjusted by changing the two capacitor values 
in SmartRF Studio 8.

.. tip::
  TI recommends tuning the HFXT capacitors values for the design. The RF performances improvements 
  obtained by tuning the HFXT capacitors values for each unit on the production line generally do 
  not justify the complexity and added costs.

1. Download the latest SmartRF 8 Studio 
    * `SmartRF Studio`_ 8

2. Open SmartRF Studio 8 and open the target device

.. figure:: resources/smartrf_studio_8_start.png
    :align: center

3. Select the RF settings used by your design. Once SmartRF Studio 8 is open you can view and 
select various PHYs, to edit a PHY you will need to create a new PHY by clicking on the box next 
to the PHY name.

.. figure:: resources/smartrf_studio_8_landing.png
    :align: center

4. You can edit various settings on the PHY properties page such as the custom name,
frequency, sync word, and tx power. 

.. figure:: resources/smartrf_studio_8_edit.png
    :align: center

5. To tune HFXT cap-array tuning change disable to enable and then edit values as needed. 

.. figure:: resources/smartrf_studio_8_edit_hfxt.png
    :align: center

6. To implement the HFXT capacitors values found in the embedded code, open the project 
in your favorite IDE open the SysConfig file -> Device Configuration and click on 
"Override HFXT Cap Array Trims" and input the two values found. 

.. figure:: resources/ccs_hfxt_edit_values.png
    :align: center
