This is the multi-page printable view of this section. Click here to print...

Return to the regular view of this page

As of 2025-09-10

TWENETcmpt - AHI Compatibility Layer

Compatibility layer for the GOLD series providing APIs compatible with the BLUE / RED series
Explanation of the TWENETcmpt library. It enables the use of some AHI functions, previously available on TWELITE BLUE/RED, on TWELITE GOLD.

TWENETcmpt - AHI Compatibility Layer

This library is intended to provide compatibility with the AHI library.

  • It aims to enable the build and operation of TweApps, not to achieve full compatibility.
  • The implementation uses the TWENETmwf library (a C++ library implemented with the FSL library).

Below are notes regarding various definitions of the compatibility layer.

LinkDescription
Common & OthersMiscellaneous functions
ADCADC-related APIs
GPIOGPIO-related APIs
PWMPWM-related APIs
I2C (SMBus)I2C-related APIs
SPISPI bus
RandomRandom number generation
UARTUART-related APIs
WDTWatchdog Timer
WTIMERWake Timer, FRWT
OnChipTempOn-chip temperature sensor (ADC)

1 - AHI-Compatible Functions

Explanation of the TWENET library and the AHI compatibility layer
This section covers general topics for AHI-compatible functions and provides explanations for AHI functions not associated with any specific peripheral.

AHI-Compatible Functions

Some of the AHI functions are implemented for source-level compatibility.

The following describes the AHI-compatible functions. Some items such as SPI and I2C are documented in separate files.

General Functions

u32AHI_Init()

uint32 u32AHI_Init();

Performs initialization for the AHI library in principle, but in this library, only a subset of variables is initialized.

bAHI_SetClockRate(), u8AHI_GetSystemClkRate()

bool_t bAHI_SetClockRate(uint8 u8clk_code);
uint8 u8AHI_GetSystemClkRate();

Sets or retrieves the CPU clock speed.

The configured clock values differ significantly from those of TWELITE BLUE/RED, so caution is required.

u8clk_codeTWELITE BLUE/REDTWELITE GOLD
04Mhz12Mhz
18Mhz12Mhz
216Mhz32Mhz
332Mhz48Mhz
4..ConfigurableIgnored
  • Although clocks such as kFROM1M_to_MAIN_CLK can be configured in the fsl library, they are disabled here due to severe operational issues.
  • Using a debugger may interfere with clock changes.
  • The default value is 2, corresponding to 32Mhz (TWELITE GOLD). (Reference: 16MHz on TWELITE BLUE/RED)

bAHI_Set32KhzClockMode()

bool_t bAHI_Set32KhzClockMode(uint8 u8mode);

Does nothing.

vAHI_CpuDoze()

static inline void vAHI_CpuDoze() { __WFI(); }

Enters the low-power DOZE state while waiting for interrupts. On TWELITE-GOLD, it issues WFI (Wait For Interrupt).

vAHI_SwReset()

static inline void vAHI_SwReset() { NVIC_SystemReset(); }

Performs a reset.

u16AHI_PowerStatus()

uint16 u16AHI_PowerStatus();

This function reports the following bitmaps:

BitDescription
bit01 when waking up from sleep
bit11 when RAM was retained

At POR, the value is 0, and for normal wake-up from RAM-retention sleep, the value is 3.

vAHI_BrownOutConfigure()

static inline void vAHI_BrownOutConfigure(
    uint8       const u8VboSelect,
    bool_t      const bVboRstEn,
    bool_t      const bVboEn,
    bool_t      const bVboIntEnFalling,
    bool_t      const bVboIntEnRising) { ; } // DUMMY FUNC

This definition exists only to avoid compilation errors. The function itself does nothing.

About Sleep

void ToCoNet_vSleep(uint8 u8Device, uint32 u32Periodms, bool_t bPeriodic, bool_t bRamOff)

Sleep in the TWENET C library uses the ToCoNet_vSleep() function.

Note: In the mwx library, use the_twelite.sleep().

  • If bRamOff is set to TRUE, the system enters sleep mode without retaining any RAM segments. Even in this case, PM_POWER_DOWN from the JN518x FSL library definitions is used, not PM_DEEP_DOWN.

About Sleep Failures (TWELITE GOLD)

On TWELITE GOLD, the procedure for sleep transition (POWER_EnterPowerMode()) in the semiconductor library occasionally fails, resulting in the device not entering sleep mode. To address this, the following measures are taken:

  • When the semiconductor library procedure fails, the function exits immediately, but after a delay loop equivalent to 100 µsec (DelayLoopN(100)), the sleep procedure is retried.
  • If the above retry fails 3 times, ToCoNet_vSleep() enters an infinite loop, and a watchdog timer reset normally occurs. In our experience, 2 or 3 retries have not been observed, but we allow up to 3 retries as a precaution.
  • After executing the above sleep procedure, if the value of extern uint8 g_twenet_power_down_fails; is non-zero upon waking up from sleep, it indicates that retries were performed. However, this variable is reset when a watchdog timer reset occurs.

For internal processing

u32AppApiInit()

uint32
u32AppApiInit(PR_GET_BUFFER prMlmeGetBuffer,
              PR_POST_CALLBACK prMlmeCallback,
              void *pvMlmeParam,
              PR_GET_BUFFER prMcpsGetBuffer,
              PR_POST_CALLBACK prMcpsCallback,
              void *pvMcpsParam);

Performs the initialization process for AppQAPI.

vAHI_RegEvMgr_MW()

void vAHI_RegEvMgr_MW();

Constructs the management object (mwf::the_sys_ev_manager) for managing class objects in the TWENETmwf library.

vAHI_OnWakeup_MW(), vAHI_OnWakeupRamOff_MW()

void vAHI_OnWakeup_MW(bool_t b_init_2nd);
void vAHI_OnWakeupRamOff_MW(bool_t b_init_2nd);

This procedure is executed upon wake-up. Refer to the processing in twenet_main.c of TWENETmcu.

  • Executes the wake-up processing of class objects in the TWENETmwf library: mwf::the_sys_ev_manager->on_wakeup().
  • Calls vAHI_DioOnWakeup_MW() to store the pins that triggered the wake-up.
  • If b_init_2nd is FALSE, it is called in the early stage of startup; if TRUE, it is called after a certain amount of initialization has been completed (before cbAppWarmStart(TRUE) is called).

vAHI_OnWakeupRamOff_MW() is called when waking up from RAM non-retentive sleep.

  • If b_init_2nd is FALSE, it is called in the early stage of startup; if TRUE, it is called after a certain amount of initialization has been completed (after cbAppWarmStart(TRUE) is called).

vAHI_OnSleep_MW()

vAHI_OnSleep_MW();

This procedure is executed before entering sleep.

  • Executes the pre-sleep processing of class objects in the TWENETmwf library: mwf::the_sys_ev_manager->on_sleep().
  • Calls vAHI_DioOnSleep_MW() to configure the DIO wake-up pins.

vAHI_DMAEnable_MW(), vAHI_DMADisable_MW()

void vAHI_DMAEnable_MW();
void vAHI_DMADisable_MW();

Enables or disables the DMA feature.

vAHI_DMADisable_MW() does not perform any operation.

2 - ADC-Related AHI Functions and Explanations

TWENET Library, AHI Functions and Explanations Related to ADCs
Explanation of the AHI functions related to ADC in the TWENET library.

ADC

Some parts related to AHI’s ADC (Analog-to-Digital Conversion) are implemented for the purpose of source code compatibility.

Overview

The hardware specifications of the ADC vary depending on the model.

TWELITE BLUETWELITE REDTWELITE GOLD
Resolution (bits)10bit10bit12bit
Full Scale2470mV2470mV3600mV
Number of Channels
(not supported by API)
44 (2)4 (2)

This library provides processing for using four channels (ADC0..3) and Vcc.
However, compatibility of conversion time or conversion data is not handled by the library; it is assumed that adjustments will be made in the application source.

For conversions up to 6 pins or for ADC combining multiple channels, the AHI library does not provide support; please use mwf::the_adc directly.

Related: On-chip Temperature Sensor

Pins

PIONotes
ADC015
ADC114Shared with DIO8
ADC216
ADC317

AHIcmpt_ADC.cpp

This library describes the differences from the AHI library for TWELITE BLUE/RED.
For API specifications, please also refer to the AHI library manual.

vAHI_ApConfigure()

void   vAHI_ApConfigure(
    bool_t      bAPRegulator,
    bool_t      bIntEnable,
    uint8       u8SampleSelect,
    uint8       u8ClockDivRatio,
    bool_t      bRefSelect);

Initializes the ADC (mwf::the_adc object construction and the_adc->init() initialization).

  • Specify bAPRegulator as TRUE to enable the ADC. If set to FALSE, the ADC is disabled.
  • Specify bIntEnable as TRUE to enable ADC interrupts.
  • u8SampleSelect and bRefSelect are ignored.
  • u8ClockDivRatio is also currently not applied.
  • A stabilization wait process for the analog circuit using bAHI_APRegulatorEnabled() is required.

bAHI_APRegulatorEnabled()

bool_t bAHI_APRegulatorEnabled(void)

When the wake timer (FRWT) is not running (which is the default in the C library), this function performs a fixed delay process (300 µsec). In this case, it is recommended to call this function immediately after invoking vAHI_ApConfigure(). Even if sufficient time has already passed, the fixed delay will still be executed.

When FRWT is enabled, the function performs the required waiting process based on the timer count value. If sufficient time has already passed, no additional waiting will be performed within this function.

vAHI_APRegisterCallback()

void   vAHI_APRegisterCallback(PR_HWINT_APPCALLBACK prApCallback);

Registers an interrupt handler. This will be called when the ADC conversion is completed.

vAHI_AdcEnable()

void   void   vAHI_AdcEnable(
    bool_t      bContinuous,
    bool_t      bInputRange,
    uint8       u8Source);

Configures the ADC conversion.

  • If bContinuous is selected, continuous conversion is performed. However, since internal interrupts occur on each conversion, performance considerations are necessary.
  • Specifying bInputRange has no effect because the hardware does not support this feature.
  • During this call, the pin corresponding to u8Source is configured for ADC use.
  • If bAHI_APRegulatorEnabled() was not executed after vAHI_ApConfigure() and the waiting process was skipped, the waiting process will be performed within this call.

vAHI_AdcDisable()

void   vAHI_AdcDisable(void);

Stops the ADC.

vAHI_AdcStartSample()

 void   vAHI_AdcStartSample(void);

Starts the ADC conversion.

  • In principle, the initial state is set as input; however, strictly speaking, the initial state is determined by the BOARD_InitPins() initialization in the TWENETmcu library’s pinmux.c.

bAHI_AdcPoll()

bool_t bAHI_AdcPoll(void);

Used for the polling wait process while(bAHI_AdcPoll()); to wait for ADC completion.

  • After the ADC completion interrupt, this call returns FALSE only once.

u16AHI_AdcRead(), i16AHI_AdcRead_mv()

uint16 u16AHI_AdcRead(void);
int16 i16AHI_AdcRead_mv(void); // 非AHI独自関数

Reads the executed ADC value.

  • u16AHI_AdcRead() returns the ADC value in 12-bit (0..4095). On error, it returns 0xffff.
  • i16AHI_AdcRead_mv() is a custom function not present in the AHI library. It returns the ADC value in mV, and on error, it returns -32768.

s_adc_int_handler()

static void s_adc_int_handler(uint32_t a1, uint32_t a2);

A static function defined in AHIcmpt_ADC.cpp that acts as an interrupt handler when the ADC conversion completes, passing the interrupt to TWENET’s AppQApi.

  • If a callback function is specified with vAHI_APRegisterCallback(), this handler will not be called.

Experimental Implementation

Batch Processing for Multiple Channels

// TWELITE GOLD only
//   Uses the FSL driver feature to acquire ADC values from multiple channels in a single operation.

// Execute ADC (parameters are the same as vAHI_AdcEnable())
void   vAHI_AdcEnableSeq(
    bool_t      bContinuous,
    bool_t      bInputRange,
    uint32      u32MaskSource);
// Read ADC value
uint16 u16AHI_AdcReadSeq(
    uint8     u8Source
    );
// Read ADC value (in mV)
int16 i16AHI_AdcReadSeq_mv(
    uint8     u8Source
    );

sensor_driver, adc.c, adc.h

sensor_driver is a set of processing functions used in existing TWEApps applications, providing a mechanism to abstract sensor processing. adc.c and .h describe the sequential processing for operating the on-chip ADC with sensor_driver, including issuing a series of commands, waiting, and acquiring data. Additionally, TWENETmwx/sensors/legacy contains implementations for several sensors other than ADC.

When migrating projects from TWELITE BLUE/RED to TWELITE GOLD, use the adjusted files stored in App_Twelite/Common. However, since project contents may differ, modifications may be required as needed.

Source NameDescription
adc.cADC processing part (ADC value conversion adjusted for TWELITE GOLD’s range)
adc.hDefinition part
sensor_driver.cSensor processing abstraction part
sensor_driver.hDefinition part

Code Example

Please refer to the comments within the following code.

#include "sensor_driver.h"
#include "adc.h"

tsObjData_ADC sObjADC; // ADC management structure (data section)
tsSnsObj sADC;         // ADC management structure (control section)
int16 a1,a2,ab;        // Variables for storing results

...
    // ADC initialization
    vSnsObj_Init(&sADC);
    vADC_Init(&sObjADC, &sADC, TRUE);
    vADC_WaitInit(); // Wait for hardware initialization

...
    // Specify the ports to measure with ADC (here: power supply voltage, ADC1, ADC2)
    sObjADC.u8SourceMask = TEH_ADC_SRC_VOLT
        | TEH_ADC_SRC_ADC_1 | TEH_ADC_SRC_ADC_2;

    // Start ADC
    vSnsObj_Process(&sADC, E_ORDER_KICK); // Start command

// Wait until processing of one ADC channel completes (=E_AHI_DEVICE_ANALOGUE interrupt)
// and call vSnsObj_Process() sequentially.
void cbToCoNet_vHwEvent(uint32 u32DeviceId, uint32 u32ItemBitmap) {
    switch (u32DeviceId) {
    case E_AHI_DEVICE_ANALOGUE:
        // ADC completion interrupt
        vSnsObj_Process(&sADC, E_ORDER_KICK);
        if (bSnsObj_isComplete(&sADC)) {
            // All channels have finished processing.
            // The values are stored as follows:
            a1=sObjADC.ai16Result[TEH_ADC_IDX_ADC_1]; // ADC1 [mV]
            a2=sObjADC.ai16Result[TEH_ADC_IDX_ADC_2]; // ADC2 [mV]
            ab=sObjADC.ai16Result[TEH_ADC_IDX_VOLT];  // Power supply voltage [mV]

            // Return to the initial state before ADC start
            vSnsObj_Process(&sADC, E_ORDER_KICK);

            // For continuous execution, call E_ORDER_KICK again
            vSnsObj_Process(&sADC, E_ORDER_KICK);
        }
        break;

    default:
        break;
    }
}

Functions

vSnsObj_Init()

void vSnsObj_Init(tsSnsObj *pSnsObj)

Initializes the sensor management structure. Call this function right before vADC_Init().

vADC_Init()

void vADC_Init(tsObjData_ADC *pData, tsSnsObj *pSnsObj, bool_t bInitAPR)

Initializes the ADC. Prepare the tsObjData structure (for storing results) and the tsSnsObj structure (for ADC management) in advance.

  • If bInitAPR is TRUE, the ADC hardware is initialized. Since hardware initialization takes some time, always execute vADC_WaitInit() to wait for initialization.

vSnsObj_Process()

void vSnsObj_Process(tsSnsObj *pObj, teEvent eEv)

Advances the ADC processing. Specifically, this function is called each time the conversion for one ADC port is completed.

During this process, the ADC value is retrieved, converted to mV, and stored in the tsSnsObj structure.

This process handles events for the state transitions managed by the tsSnsObj structure. Immediately after calling this process, call bSnsObj_isComplete() to check whether processing is complete. To return to the initial state, execute this process again with E_ORDER_KICK as the argument (in other words, to run the ADC again, execute E_ORDER_KICK twice after completion).

tsObjData_ADC structure

This structure contains the specified ADC channels and the resulting voltage values.

  • u8SourceMask: A bitmap specifying the ports for ADC. The specified ports become ADC targets.
    • TEH_ADC_SRC_VOLT: Power supply voltage
    • TEH_ADC_SRC_ADC_1-4: ADC1,2,3,4
  • u8InputRangeMask: Specifies the range (0-Vref or 0-2Vref) for the ADC target ports. Specified ports use 0-Vref; unspecified ports use 0-2Vref.
  • ai16Result[]: Structure for storing ADC values. Results are stored as mV values.
    • TEH_ADC_IDX_VOLT: Power supply voltage
    • TEH_ADC_IDX_ADC_1-4: ADC1,2,3,4

3 - AHI Functions and Explanations for DIO (GPIO)

Explanations of the TWENET library and AHI functions related to DIO (GPIO)
This section provides explanations of the TWENET library and AHI functions related to DIO (GPIO).

DIO (GPIO)

Some of the AHI functions related to DIO (GPIO) are implemented for source-level compatibility.

Overview

The pin assignment architecture differs from that of TWELITE BLUE/RED. Here, pins used in TWELITE BLUE/RED are labeled as DIO0..19/DO0..1/ADC0…3, while the pin names for the semiconductor used in TWELITE GOLD are labeled as PIO0..21. For details about the pins, refer to the semiconductor datasheet for each module.

  • Some pins on the module are not mapped one-to-one:
    • PIO0 is shared with DIO11 and DO0.
    • PIO14 is shared with DIO8 and ADC1.
  • Regarding DIO interrupts, there are the following differences:
    • DIO0..19 supported independent interrupts, but since this feature does not exist here, the GINT (group interrupt) feature is used to achieve similar behavior. (Another feature called PINT supports independent interrupts but only for up to four ports, so it is not used in this library.)
    • Hardware interrupt detection is only available on both edges; internal interrupts occur on either edge.
      • While running (not in sleep mode), whether to call the AHI interrupt handler is determined by the pin state after the interrupt occurs, so the fact that detection is on both edges is not apparent.
      • The edge for wake-up from sleep cannot be specified.

Pin Assignment

DIODIOPIONotes
DIO0016
DIO1117
DIO2218
DIO3319
DIO447
DIO556
DIO668
DIO779
DIO8814Shared with ADC1
DIO9912
DIO10104
DIO11110Shared with DO0
DIO121213
DIO13131
DIO141410
DIO151511
DIO161620
DIO171721
DIO18182
DIO19193
DO0 (PROG)0Shared with DIO11
DO15
ADC214Shared with DIO8
ADC115

AHIcmpt_Dio.cpp - Definitions and Constants

Definitions

#define BOARD_GPIO_PORT_MAX_PIN_COUNT 22 // Number of pins
#define BOARD_GPIO_PIN_TABLE_SIZE 24     // Rounded up to a multiple of 4 for 22 pins

g_twenet_ioport_remap_by_PIOn[]

const uint8 g_twenet_ioport_remap_by_PIOn[BOARD_GPIO_PIN_TABLE_SIZE];

(For internal library use) Table for converting PIO numbers to DIO numbers.

  • 0x80: SPIMISO pin
  • 0x90: ADC1 pin (analog only)
  • 0xFF: Unused / undefined

g_twenet_ioport_remap_by_AHIn[]

const uint8 g_twenet_ioport_remap_by_AHIn[BOARD_GPIO_PIN_TABLE_SIZE];

(For internal library use) Table for referencing PIO numbers from AHI numbers.

AHIcmpt_Dio.cpp - Definitions

Variables

uint32 G_TWENET_IOPORT_OUTPUT_BM() = 0;       // DIO bitmap for output ports
uint32 G_TWENET_IOPORT_INT_ENABLED_BM() = 0;      // DIO bitmap for interrupt-enabled ports
uint32 G_TWENET_IOPORT_INT_RISING_BM() = 0;       // DIO bitmap for rising-edge interrupt-enabled ports
uint32 G_TWENET_IOPORT_INT_FALLING_BM() = 0;      // DIO bitmap for falling-edge interrupt-enabled ports
volatile uint32 G_TWENET_IOPORT_INT_STATUS() = 0; // DIO bitmap recording wake-up pins when woken by DIO interrupt
uint32 G_TWENET_IOPORT_WAKE_STATUS() = 0;         // DIO bitmap storing I/O interrupt sources at wake-up
  • Each DIO bitmap corresponds bit n to DIOn (e.g., for DIO0 and DIO3, use (1UL << 0) | (1UL << 3)).

check_pio(), get_pio(), get_dio()

static inline bool check_pio(uint8 u8pio);
static inline uint8 get_pio(const uint8 u8dio);
static inline uint8 get_dio(const uint8 u8pio);
  • check_pio(): An inline function that checks whether the specified PIO number is valid and not already used by another peripheral.
  • get_pio(): Returns the PIO number corresponding to the specified DIO number. Returns 0xff if the assignment is invalid.
  • get_dio(): Returns the DIO number corresponding to the specified PIO number. Returns 0xff if the assignment is invalid.

s_gpio_int_handler()

static void s_gpio_int_handler(uint32 bm_pio, uint32 bm_pio_changed, void* p_data);

Interrupt handler function internally called when a DIO interrupt occurs.

  • If there is a pin change, interrupt information is sent via AppQAPI using __twenet_vAppQApiPostHwIntT().

AHIcmpt_Dio.cpp - AHI Function Definitions

vAHI_DioSetDirection()

void   vAHI_DioSetDirection(
    uint32      u32Inputs,
    uint32      u32Outputs);

Configures the input/output direction of ports.

  • In principle, ports are set to input state at initialization, but strictly speaking, the initial state is defined by the BOARD_InitPins() initialization in the TWENETmcu library’s pinmux.c.

vAHI_DioSetOutput()

void   vAHI_DioSetOutput( // u32On:HIGH, u32Off::LOW
    uint32      u32On,
    uint32      u32Off);

Changes the output state of ports. u32On is the DIO bitmap for pins to set HIGH, and u32Off is the DIO bitmap for pins to set LOW.

  • When multiple pins are specified, the changes are not simultaneous.
    • This is because, in the internal implementation, each pin is set individually within a loop.

vAHI_DioSetPullup()

void   vAHI_DioSetPullup(
    uint32      u32On,
    uint32      u32Off);

Configures the pull-up state.

  • In principle, the default is pull-up enabled, but strictly speaking, the initial state is defined by the BOARD_InitPins() initialization in the TWENETmcu library’s pinmux.c.

u32AHI_DioReadInput()

uint32 u32AHI_DioReadInput(void);

Retrieves the state of all ports at once.

  • The return value is a bitmap representing the state of all ports: bits set to 1 indicate HIGH level, and bits set to 0 indicate LOW level.
  • The values for non-existent DIO numbers or ports used by peripherals are undefined.

vAHI_DioWakeEnable()

void   vAHI_DioWakeEnable(
    uint32      u32Enable,
    uint32      u32Disable);

Starts DIO interrupts. u32Enable specifies the DIO bitmap for adding interrupt handling, and u32Disable specifies the DIO bitmap for removing interrupt handling. Additionally, you must specify the interrupt edge for the enabled pins using vAHI_DioWakeEdge().

  • The behavior is undefined when specifying pins that are not configured as inputs (e.g., output pins or pins assigned to other peripheral functions).

vAHI_DioWakeEdge()

void   vAHI_DioWakeEdge(
    uint32      u32Rising,
    uint32      u32Falling);

Configures the interrupt pins. This call sets both rising and falling edges for the specified pins at once. Note that you cannot add or remove edges individually.

Although the function name contains “Wake,” it configures both runtime interrupt handling and wake-up-from-sleep behavior.

  • If the same pin is specified for both u32Rising and u32Falling, interrupts occur on both edges due to the design principle. (However, since this is not a valid AHI setting, it is outside the scope of operation verification.)
  • During interrupt operation, vAHI_DioWakeEnable() is called internally for reconfiguration.
  • The behavior is undefined when specifying pins that are not configured as inputs (e.g., output pins or pins assigned to other peripheral functions).
  • For wake-up from sleep, the interrupt edge is always set to both edges.

u32AHI_DioWakeStatus()

uint32 u32AHI_DioWakeStatus(void);

Returns the bitmap of pins that triggered the wake-up during a DIO interrupt.

  • Internally, it returns the value of __twenet_ioport_int_status at the time of the call. After the call, the value is set to 0.

bAHI_DoEnableOutputs()

static inline bool_t bAHI_DoEnableOutputs(bool_t bEnableDO) {
	return bAHI_DoEnableOutputsEx_MW(bEnableDO, bEnableDO);
}

Configures the DO0 and DO1 pins as output.

  • Both DO0 and DO1 are configured as output.
  • To configure only one pin, call bAHI_DoEnableOutputsEx_MW().
    • DO1 (PIO5) is assigned to the pin used to determine transition to program mode (ISP_ENT) at startup, so it requires attention in hardware design. Unless there is a special reason, it is recommended to use a different pin.
  • DO0 (PIO0) is also assigned to DIO11, so if both are used, code adjustments (excluding control of one side) are required.

vAHI_DoSetDataOut()

void vAHI_DoSetDataOut(
    uint8       u8On,
    uint8       u8Off);

Configures output settings for DO0 (PIO0) and DO1 (PIO1).

  • DO0 is specified by bit0 (0x1), and DO1 is specified by bit1 (0x2) in the bitmap.
  • Setting a bit in u8On sets the output to HIGH level, while setting it in u8Off sets the output to LOW level.

vAHI_DoSetPullup()

 void vAHI_DoSetPullup(
    uint8       u8On,
    uint8       u8Off);

Does nothing.

AHIcmpt_Dio.cpp - AHI Extended API

Functions with the _MW suffix are custom extensions not present in the AHI library.

bAHI_DoEnableOutputsEx_MW()

bool_t bAHI_DoEnableOutputsEx_MW(
    bool_t bEnableDO0, bool_t bEnableDO1);

Configures DO0 and DO1 as outputs.
This function was added because bAHI_DoEnableOutputs() configures both ports simultaneously.

vAHI_DioInterruptDisablePinsIntWhenChanged_MW(), vAHI_DioInterruptReavtivate_MW()

void vAHI_DioInterruptDisablePinsIntWhenChanged_MW(bool_t bSet);
void vAHI_DioInterruptReavtivate_MW();

Temporarily disables interrupts for pins where an interrupt has been detected.

  • When called with bSet set to TRUE, interrupts for the affected pins are temporarily disabled when a DIO interrupt occurs.
  • For inputs such as mechanical buttons with significant chattering, enable this setting and call vAHI_DioInterruptReavtivate_MW() after a certain time has passed since the interrupt to resume interrupts.

vAHI_DioOnSleep_MW()

void vAHI_DioOnSleep_MW();

An internal processing function not intended to be called by users.
It handles DIO interrupt-related processing before entering sleep, specifically configuring the DIO wake-up pins.

vAHI_DioOnWakeup_MW()

void vAHI_DioOnWakeup_MW(bool_t b_init_2nd);

An internal processing function not intended to be called by users.
It handles DIO interrupt-related processing at wake-up and stores the pins that triggered the wake-up.

  • When called with b_init_2nd set to false, it runs at the very early stage of the WarmMain() process to identify the wake-up sources.
  • It is then called again with true just before the call to cbAppWarmStart(TRUE).

vAHI_DioRetentionRelease_MW()

void vAHI_DioRetentionRelease_MW();

Releases the DIO output state retention after waking up from sleep.
This function is used when waking from RAM-OFF sleep and inside cbAppColdStart().

On JN518X, the register setting (SYSCON->RETENTIONCTRL) to retain DIO output states is configured before entering sleep.
DIO pins with output settings retain their states as configured in the register, and after waking from sleep, the output states remain until the register settings are changed. Calling this function releases the output state retention.

To restore the same configuration as before sleep, call vAHI_DioSetDirection() or vAHI_DioSetOutput() before calling this function to explicitly configure the output settings. This is necessary because DIO internal registers are cleared during sleep.

After the call to cbAppColdStart(), the TWENETmcu library performs the same process as this function. To avoid unintended HI/LO transitions on ports, configure the port outputs inside cbAppColdStart().

Others

Notes When Not Using This Library

Do not call functions from this library. Even if you do not call them, this library still depends on the TWENETmcu and TWENETlib libraries.

Refer to the following to resolve dependencies:

  • Regarding interrupt pins when performing sleep procedures:
    • You need to adjust vAHI_DioOnSleep_MW() and vAHI_DioOnWakeup_MW().
      • These two functions are called from vAHI_OnSleep_MW() and vAHI_OnWakeup_MW() in TWENETcmpt.
    • The vAHI_OnSleep_MW() function depends on the closed-source TWENETlib library.
      • In vAHI_DioOnSleep_MW(), specify the PIO bitmap for wake-up interrupt detection in __twenet_ioport_int_status. It is applied inside ToCoNet_vSleep() to execute sleep properly.
    • vAHI_OnWakeup_MW() and vAHI_DioOnWakeup_MW() are called within the TWENETmcu library source. Modify the processing as needed.

4 - AHI Functions and Explanations for Timer (PWM)

Explanations of the TWENET library and AHI functions related to Timer (PWM)
This section provides explanations of the TWENET library and AHI functions related to Timer (PWM).

Timer (PWM)

Some parts of the AHI Timer-related APIs are implemented for source code compatibility.

AHI APIについて

vAHI_TimerFineGrainDIOControl()

void vAHI_TimerFineGrainDIOControl(uint8 u8BitMask)

Specifies the bitmask to disable output pins. Only the bits corresponding to TIMER_0 … TIMER_4 are valid.

  • Call this function before executing vAHI_TimerEnable().
  • Even if output is enabled in the parameters of vAHI_TimerEnable(), pins set to be disabled by this function will be treated as output-disabled.

vAHI_TimerAssignPIOPin_MW()

void vAHI_TimerAssignPIOPin_MW(
		uint8 u8_timer_id,
		uint8 u8_pin_id)

This function is specific to TWELITE GOLD.

Specifies the PIO number of the pin to be used with the specified timer device (u8_timer_id).

Each PIO number is linked to a specific PWM channel. Some PIO numbers do not support PWM. Depending on how you specify them, it is possible to create conflicting settings, such as using the same PWM channel multiple times. Refer to the pin assignment table for mapping between PIO numbers and PWM channels.

  • u8_timer_id specifies the target timer device (E_AHI_DEVICE_TIMER0-4).
  • Settings in vAHI_TimerFineGrainDIOControl() are also valid, but output enable/disable is controlled by bOutputEnable in vAHI_TimerEnable().
  • Even if output is disabled and only timer interrupts are used, specify the pin number corresponding to the PWM channel to be used.

This is a custom function of this library.

vAHI_TimerEnable()

void vAHI_TimerEnable(
    uint8       u8_timer_id,
    uint8       u8Prescale,
    bool_t      bIntRiseEnable,
    bool_t      bIntPeriodEnable,
    bool_t      bOutputEnable)

Enables the timer.

  • If bIntRiseEnable == TRUE, it is treated as bIntPeriodEnable == TRUE.
  • Even if bOutputEnable == TRUE is set, if the pin is disabled by vAHI_TimerFineGrainDIOControl(), it is treated as FALSE.
  • The behavior is undefined if this function is called again for a timer ID that has already been enabled.
When Hardware Resource Conflicts Occur

Due to hardware differences from TWELITE BLUE/RED, not all timer devices can be used in the same way. Refer to the pin assignment section described later for details.

  • If PWM output is enabled, software-based PWM output emulation will be performed.
  • If PWM output is disabled, the purpose is limited to timer interrupts, so the available PWM3 or PWM5 will be used without pin output.
  • No API or procedure is provided to check whether the above assignment has been made.

vAHI_TimerDisable()

void  vAHI_TimerDisable(uint8 u8_timer_id)

Disables the timer.

  • The output port is reverted to input (the pull-up setting is not changed).

vAHI_TimerDisable()

void  vAHI_TimerDisable(uint8 u8_timer_id)

Disables the timer.

  • The output port is reverted to input (the pull-up setting is not changed).

vAHI_TimerConfigure()

void vAHI_TimerConfigure(
		uint8       u8_timer_id,
		bool_t      bInvertPwmOutput,
		bool_t      bGateDisable)

Modifies the timer settings.

  • Configures bInvertPwmOutput.
  • bGateDisable is ignored.

vAHI_TimerStartRepeat()

void  vAHI_TimerStartRepeat(
		uint8       u8_timer_id,
	    uint16      u16Hi,
	    uint16      u16Lo)

Starts the timer.

  • This function can also be called while the timer is running and is used to change the PWM duty cycle settings.

vAHI_TimerStop()

void  vAHI_TimerStop(uint8 u8_timer_id)

Stops the timer.

vAHI_TimerSetLocation()

void vAHI_TimerSetLocation(
		uint8 u8Timer,
		bool_t bLocation,
		bool_t bLocationOverridePWM3andPWM2)

Changes the pin assignment.

  • Call this function before executing vAHI_TimerEnable().

vAHI_TimerXRegisterCallback

PUBLIC void  vAHI_Timer0RegisterCallback(
    PR_HWINT_APPCALLBACK        prTimer0Callback);
PUBLIC void  vAHI_Timer1RegisterCallback(
    PR_HWINT_APPCALLBACK        prTimer1Callback);
PUBLIC void vAHI_Timer2RegisterCallback(
    PR_HWINT_APPCALLBACK        prTimer2Callback);
PUBLIC void vAHI_Timer3RegisterCallback(
    PR_HWINT_APPCALLBACK        prTimer3Callback);
PUBLIC void vAHI_Timer4RegisterCallback(
    PR_HWINT_APPCALLBACK        prTimer4Callback);

The interrupt handler registration functions are not implemented. The interrupt handler is invoked via AppQAPI.

If you want to define a custom interrupt handler, implement the WEAK-defined handler functions below.
Refer to the implementation in AHIcmpt_TImers.cpp.
At a minimum, you need to call PWM_ClearStatusFlags(PWM, kPWM_PwmX);.

WEAK void PWM0_DriverIRQHandler(void); // MONO WIRELESS, DEFINED AS WEAK FUNCTION.
WEAK void PWM1_DriverIRQHandler(void);
WEAK void PWM2_DriverIRQHandler(void);
WEAK void PWM3_DriverIRQHandler(void);
WEAK void PWM4_DriverIRQHandler(void);
WEAK void PWM5_DriverIRQHandler(void);
WEAK void PWM6_DriverIRQHandler(void);
WEAK void PWM7_DriverIRQHandler(void);
WEAK void PWM8_DriverIRQHandler(void);
WEAK void PWM9_DriverIRQHandler(void);

Other Functions

void vAHI_TimerClockSelect(
    uint8       u8Timer,
    bool_t      bExternalClock,
    bool_t      bInvertClock);
void vAHI_TimerStartSingleShot(
    uint8       u8Timer,
    uint16      u16Hi,
    uint16      u16Lo);

These are either undefined functions or dummy functions that do nothing.

About Output Pins

  • Output pins are initialized for PWM use when calling vAHI_TimerEnabled().
  • Output pins are reset to input ports (without changing pull-up settings) when calling vAHI_TimerDisable().

About Interrupts

Interrupts at intermediate output transition points within a cycle are not supported. Only interrupts for each full cycle are supported.

Interrupt Handlers

Interrupt handlers are only supported in the standard TWENET callbacks cbToCoNet_u8HwInt() and cbToCoNet_vHwEvent(). Additional handlers cannot be registered.

If you want to define individual handlers, define the PWMx_IRQHandler() functions separately. In this case, events will not be reported to TWENET from the defined handler.

Pin Assignment

Pin assignment can be configured individually for each TIMER_ID, but due to hardware differences in TWELITE BLACK, assignments may be difficult in some cases.

Standard

AHI TIMER ID01234
SMD PIN##1216131519
AHI DIO##1011121317
PIO##4013121
PWM channel40219

When Using DO1,2 in Standard Mode

AHI TIMER ID01234
SMD PIN##12161219
AHI DIO##1011DO0DO117
PIO##400521
PWM channel400N/A9
  • TIMER_1 and TIMER_2 assignments conflict.
  • The output pin for TIMER_3 does not have hardware timer functionality.

Secondary Assignment

AHI TIMER ID01234
SMD PIN##678910
AHI DIO##45678
PIO##768914
PWM channel76891

When Using DO1,2 in Secondary Assignment

AHI TIMER ID01234
SMD PIN##671910
AHI DIO##45DO0DO18
PIO##760514
PWM channel760N/A1
  • The output pin for TIMER_3 does not have hardware timer functionality.

Others

Behavior When Pin Assignment Conflicts Occur

  • If a pin configured for PWM output has a conflict (e.g., the pin does not support PWM), software emulation will be used.
    • The software emulation controls the output under the system timer (SysTick) interrupt, using 16 clocks per cycle. If running at 1 kHz, the PWM period is 1000/16 ≈ 62 Hz.
  • If a pin without PWM output configured has a conflict (e.g., duplicate PWM device numbers), the available PWM3 or PWM5 is assigned. PWM interrupts will operate even without pin output.

When Not Using This Library’s PWM Features

  • Do not call AHI timer-related APIs (?AHI_Timer???).
    • Calling these APIs creates processing objects for AHI compatibility. Behavior is undefined if you then call APIs defined in fsl_pwm.h in this state.
  • Define PWM0_IRQHandler()PWM9_IRQHandler() separately. Since these are specified with weak linkage, your application’s non-weak definitions will take precedence at link time.

Behavior on Wake from Sleep

  • For RAM-retention sleep, the PWM output state immediately before sleep is restored. For RAM-off sleep, normal DIO initialization is performed.
void vAHI_TimerFineGrainDIOControl(
    uint8 u8BitMask);
PUBLIC void vAHI_TimerConfigure(
    uint8       u8Timer,
    bool_t      bInvertPwmOutput,
    bool_t      bGateDisable);
PUBLIC void  vAHI_TimerEnable(
    uint8       u8Timer,
    uint8       u8Prescale,
    bool_t      bIntRiseEnable,
    bool_t      bIntPeriodEnable,
    bool_t      bOutputEnable);
PUBLIC void  vAHI_TimerDisable(
    uint8       u8Timer);
PUBLIC void  vAHI_TimerClockSelect(
    uint8       u8Timer,
    bool_t      bExternalClock,
    bool_t      bInvertClock);
PUBLIC void  vAHI_TimerStartRepeat(
    uint8       u8Timer,
    uint16      u16Hi,
    uint16      u16Lo);
PUBLIC void  vAHI_TimerStop(
    uint8 u8_timer_id);
PUBLIC void vAHI_TimerSetLocation(
    uint8 u8Timer,
    bool_t bLocation,
    bool_t bLocationOverridePWM3andPWM2);

※ Some function names are redefined by macros.
※ The timer library in utils.h also uses the above APIs.

Example Handler Definitions

Minimal definitions including the essential steps.

void PWM0_IRQHandler(void) { PWM_ClearStatusFlags(PWM, kPWM_Pwm0); }
void PWM1_IRQHandler(void) { PWM_ClearStatusFlags(PWM, kPWM_Pwm1); }
void PWM2_IRQHandler(void) { PWM_ClearStatusFlags(PWM, kPWM_Pwm2); }
void PWM3_IRQHandler(void) { PWM_ClearStatusFlags(PWM, kPWM_Pwm3); }
void PWM4_IRQHandler(void) { PWM_ClearStatusFlags(PWM, kPWM_Pwm4); }
void PWM5_IRQHandler(void) { PWM_ClearStatusFlags(PWM, kPWM_Pwm5); }
void PWM6_IRQHandler(void) { PWM_ClearStatusFlags(PWM, kPWM_Pwm6); }
void PWM7_IRQHandler(void) { PWM_ClearStatusFlags(PWM, kPWM_Pwm7); }
void PWM8_IRQHandler(void) { PWM_ClearStatusFlags(PWM, kPWM_Pwm8); }
void PWM9_IRQHandler(void) { PWM_ClearStatusFlags(PWM, kPWM_Pwm9); }
  • When you define these functions, interrupts/events will not be forwarded to TWENET.

About This Library’s Implementation

  • The main implementation code is in AHIcmpt_Timer.cpp.
  • The above code references _periph_pwm.hpp and _periph_pwm.cpp. These are class libraries that consolidate procedures using the platform drivers (driver/fs_???).

5 - Explanation of SMBus.c,h Defining SMBUS (I2C)-Related Procedures

Explanations of the TWENET library: SMBUS (I2C)-related procedures defined in SMBus.c,h
This section provides explanations of the TWENET library and the SMBUS (I2C)-related procedures defined in SMBus.c and SMBus.h.

SMBUS (I2C)

In many sample and application codes using TWENET, the I2C bus is typically not accessed directly through the low-level AHI library procedures.
Instead, a set of simplified read/write functions defined in SMBus.c and SMBus.h is used.

The following is a list of the function names provided:

void vSMBusInit(void);
void vSMBusInit_setClk(uint32 u32Clk);
void vSMBusDeInit();
void vSMBusDeInit(void);
bool_t bSMBusWrite(uint8 u8Address, uint8 u8Command,
						  uint8 u8Length, uint8* pu8Data);
bool_t bSMBusSequentialRead(uint8 u8Address, uint8 u8Length,
		   uint8* pu8Data);

SMBus.c SMBus.h

These are a set of functions summarizing typical I2C procedures, with source code stored in TWENETmwx/source/sensors/legacy.

  • If the TWENETmwx library is not linked (C project), copy and use this source code.

vSMBusInit()

void vSMBusInit(void);

Initializes the I2C bus.
The pins used are DIO14 (CLK) and DIO15 (DATA), with a clock frequency of 100 Kbps.

vSMBusInit_setClk(uint32)

{{{cpp {noln=true} void vSMBusInit_setClk(uint32 u32Clk); }}}

Using this function instead of vSMBusInit() initializes the I2C bus with the clock specified by u32clk.

  • If u32clk >= 7 and u32clk <= 255 ⇒ Initializes with clock frequency 3200000ul / (u32clk + 1). For example, specifying 31 gives 100 kHz, and 7 gives 400 kHz.
  • If u32clk >= 12500 and u32clk <= 400000 ⇒ Initializes with u32clk directly.
  • Otherwise ⇒ Undefined behavior.

※ The actual frequency will be the closest available based on the hardware clock divisor. For detailed calculations, refer to the source code (for TWELITE GOLD, see NXP’s FSL library specifications).

// Implementation for TWELITE GOLD
PUBLIC void  TWENET_smbus_vSMBusInit_setClk(uint32_t u32clk)
{
    ...
	if (u32clk >= 7 && u32clk <= 255) { // given by divisor
		u32clk = 3200000ul / (u32clk + 1);
	}

	if (u32clk < 12500ul || u32clk > 400000ul) {
		u32clk = 100000ul;
	}

	// initialize the I2C
    //... rest of the implementation
      _conf.baudRate_bps = u32clk;
      I2C_MasterGetDefaultConfig(&_conf); // FSL library function
}

// Implementation for TWELITE BLUE/RED
void vSMBusInit_setClk(uint32 u32Clk)
{
    /* convert clock to clock divisor */
    if (u32Clk > 255) {
    	u32Clk = (3200000UL / u32Clk) - 1;
    }
    if (u32Clk < 7 || u32Clk > 255) u32Clk = 31; // set 100kHz

    /* run bus at specified value */
    vAHI_SiMasterConfigure(TRUE, FALSE, u32Clk);
    // 16/[(PreScaler + 1) x 5]MHz
    //		--> 31:100KHz, 7:400KHz, 47:66KHz
}

vSMBusDeInit()

void vSMBusDeInit();

Stops the use of the I2C bus.

  • For TWELITE BLUE/RED, calls vAHI_SiMasterDisable().
  • For TWELITE GOLD, stops the I2C bus usage and restores DIO14 and DIO15 pins to the TWENET library’s initial configuration (input ports with pull-up).

bSMBusWrite()

bool_t bSMBusWrite(
	uint8 u8Address,
    uint8 u8Command,
	uint8 u8Length,
    uint8* pu8Data)

Performs a write operation on the I2C bus.

  • u8Address ⇒ Specifies the device address on the I2C bus.
  • u8Command ⇒ Specifies the command (first transfer byte) for the write operation.
  • u8Length ⇒ Number of subsequent bytes. If 0, only the command byte is transferred. If greater than 0, pu8Data must be defined.
  • pu8Data ⇒ Pointer to the memory area containing the bytes to be transferred.

Returns TRUE if the transfer succeeds, and FALSE if it fails.

bSMBusSequentialRead()

bool_t bSMBusSequentialRead(
    uint8 u8Address,
    uint8 u8Length,
	uint8* pu8Data)

Performs a read operation on the I2C bus.

  • u8Address ⇒ Specifies the device address on the I2C bus.
  • u8Length ⇒ Specifies the number of bytes to read (must be 1 or more).
  • pu8Data ⇒ Pointer to the memory area where the read bytes will be stored.

Returns TRUE if the transfer succeeds, and FALSE if it fails.

Others

Handling During Sleep

  • For TWELITE BLUE/RED, hardware reinitialization is required after waking from sleep.
    If vSMBusDeInit() is not called, the pin state is undefined (or follows the JN516x peripheral specification).
    You can reinitialize by calling vSMBusInit() or vSMBusInit_setClk() again.

  • For TWELITE GOLD, the behavior is as follows:

    • RAM ON (normal) sleep: If the I2C bus was initialized before sleep, it will be reinitialized upon waking. If the I2C bus was not in use, normal general-purpose IO wake-up handling will apply.
    • RAM OFF (deep) sleep: Upon waking, TWENET will reinitialize the pins as input pins with pull-up enabled.

TWELITE GOLD Implementation

AHI-compatible functions are not provided; instead, corresponding functions are implemented in SMBus.c and SMBus.h.

// Implementations in the TWENETcmpt library
PUBLIC void TWENET_smbus_vSMBusInit(void);
PUBLIC void TWENET_smbus_vSMBusDeInit(void);
PUBLIC void TWENET_smbus_vSMBusInit_setClk(uint32 u32clk);
PUBLIC bool_t  TWENET_smbus_bSMBusWrite(uint8 u8Address,
    uint8 u8Command, uint8 u8Length, uint8* pu8Data);
PUBLIC bool_t TWENET_smbus_bSMBusSequentialRead(uint8 u8Address,
    uint8 u8Length,  uint8* pu8Data);

// SMBus.h uses inline definitions to call the above functions
static inline void vSMBusInit(void) {
	TWENET_smbus_vSMBusInit();
}
static inline void vSMBusInit_setClk(uint32 u32Clk) {
	TWENET_smbus_vSMBusInit_setClk(u32Clk);
}
static inline void vSMBusDeInit() {
	TWENET_smbus_vSMBusDeInit();
}
static inline void vSMBusDeInit(void) {
	TWENET_smbus_vSMBusInit();
}
static inline bool_t bSMBusWrite(uint8 u8Address, uint8 u8Command,
						  uint8 u8Length, uint8* pu8Data) {
	return TWENET_smbus_bSMBusWrite(u8Address, u8Command, u8Length, pu8Data);
}
static inline bool_t bSMBusSequentialRead(uint8 u8Address, uint8 u8Length,
		   uint8* pu8Data) {
	return TWENET_smbus_bSMBusSequentialRead(u8Address, u8Length, pu8Data);
}

6 - AHI Functions and Explanations for SPI

Explanations of the TWENET library and AHI functions related to SPI
This section provides explanations of the TWENET library and AHI functions related to SPI.

SPI

This section covers the implementation of AHI-compatible functions for SPI.

The following pins are used for SPI operation:

SignalPin Name (PIO No.)Description
SCKSPLCLK=DIO11(PIO0)Clock signal
This pin is shared with SPICLK and DIO11
MOSIDIO18(PIO2)SPIMOSI. Output from TWELITE side, input to external SPI device.
MISOSPIMISO(PIO5)SPIMISO. Input to TWELITE side, output from external SPI device.
SEL0DIO19(PIO3)
SEL1DIO0(PIO16)
SEL2DIO1(PIO17)

When using alternate pin assignments (set via vAHI_SpiSetLocation_MW(FALSE)):

SignalPin Name (PIO No.)Description
SCKADC1(PIO15)Clock signal
MOSIDIO1(PIO17)SPIMOSI. Output from TWELITE side, input to external SPI device.
MISODIO2(PIO18)SPIMISO. Input to TWELITE side, output from external SPI device.
SEL0DIO0(PIO16)
SEL1DIO8=ADC2(PIO14)This pin is shared with DIO8 and ADC2
SEL2DIO12(PIO13)

SPI operates using hardware functionality, so there may be some differences in pin behavior (especially the HIGH/LOW state when no transfer is occurring).

  • The implementation uses blocking transfers. To maintain code compatibility, ensure to include polling wait code immediately after transfer API calls (bAHI_SpiPollBusy(), vAHI_SpiWaitBusy()).

vAHI_SpiConfigure()

void   vAHI_SpiConfigure(
    uint8       u8SlaveEnable,
    bool_t      bLsbFirst,
    bool_t      bPolarity,
    bool_t      bPhase,
    uint8       u8ClockDivider,
    bool_t      bInterruptEnable,
    bool_t      bAutoSlaveSelect);

Initializes the SPI.

  • bInterruptEnable is not supported; this parameter is ignored.

vAHI_SpiDisable()

void vAHI_SpiDisable(void);

Stops the use of SPI.

vAHI_SpiSelect()

void   vAHI_SpiSelect(
    uint8       u8SlaveMask)

Selects the SPI SELECT pin.

  • If bAutoSlaveSelect in vAHI_SpiConfigure() is set to TRUE, specifies the pin to control but does not control it at the time of this call.
  • If bAutoSlaveSelect in vAHI_SpiConfigure() is set to FALSE, controls the SELECT pin (sets the target pin LOW, all others HIGH).

vAHI_SpiStop()

PUBLIC void   vAHI_SpiStop(void);

Deselects the SELECT pin.
Performs the same operation as vAHI_SpiSelect(0).

vAHI_SpiStartTransfer()

void vAHI_SpiStartTransfer(
    uint8       u8CharLen,
    uint32      u32Out);

void   vAHI_SpiStartTransfer32(uint32 u32Out);
void   vAHI_SpiStartTransfer16(uint16 u16Out);
void   vAHI_SpiStartTransfer8(uint8 u8Out);

Executes an SPI transfer.

  • This process runs in blocking mode.
  • If the bit length is not a multiple of 8, the transfer will be split into 2–3 parts.
  • When specifying 32-bit transfers, regardless of the memory byte order (endianness), data is sent from the most significant byte to the least significant byte.
    As a result, the transfer waveform will be identical on both BLUE and GOLD.

AHI_SpiReadTransfer()

static inline uint32 u32AHI_SpiReadTransfer32(void);
static inline uint16 u16AHI_SpiReadTransfer16(void);
static inline uint8  u8AHI_SpiReadTransfer8(void);

Call this after the transfer completes to return the read value.

bAHI_SpiPollBusy()

bool_t bAHI_SpiPollBusy(void);
inline void vAHI_SpiWaitBusy(void) { while(bAHI_SpiPollBusy()); }

Always returns FALSE because the transfer API performs blocking transfers.

bAHI_SpiTransferBlocking_MW()

bool_t bAHI_SpiTransferBlocking_MW(
    uint8       *au8tx,
	uint8       *au8rx,
	uint8		u8len);

Performs byte-level SPI transfers.
au8tx is the transmit data array, au8rx is the receive data array, and u8len is the number of bytes to transfer.

  • Data is transferred sequentially from the beginning of the array.
    To transfer from LSB first, store the LSB-side bytes first in the array. The same applies to the received data.

vAHI_SpiWaitBusy()

void vAHI_SpiWaitBusy(void);

Returns immediately.

vAHI_SpiSetLocation_MW()

void vAHI_SpiSetLocation_MW(bool_t bLocation);

Changes the pin assignment configuration.
If using the default pin assignments, calling this function is unnecessary.
If using the alternate pins, call this function before invoking vAHI_SpiConfigure().

  • bLocation == FALSE (default) → Uses the default pin assignments.
  • bLocation == TRUE → Uses the alternate pin assignments.

Others

Transfer Splitting

When performing transfers with vAHI_SpiStartTransfer() that are not a multiple of 8 bits (e.g., 8, 16, 24, 32 bits),
the transfer is internally split into two parts.
As a result, the waveform will be held for a certain period between the first and second transfers.

Behavior on Wake from Sleep

If the SPI bus was initialized before entering RAM-retention sleep, the initialization state will be restored upon wake-up. For RAM-off sleep, normal DIO initialization will be performed at startup.

To improve code compatibility with BLUE/RED, explicitly call vAHI_SpiDisable() before sleep.

7 - AHI Functions and Explanations for Random Numbers

Explanations of the TWENET library and AHI functions related to random numbers
This section provides explanations of the TWENET library and AHI functions related to random numbers.

Random (Random Numbers)

Implementation of AHI-compatible functions related to random number generation.

vAHI_Start|StopRandomNumberGenerator()

void vAHI_StartRandomNumberGenerator(bool_t const bMode, bool_t const bIntEn);
void vAHI_StopRandomNumberGenerator(void);

Starts or stops random number generation.

u16AHI_ReadRandomNumber()

uint16 u16AHI_ReadRandomNumber(void);

Reads a 16-bit random value.

  • If random number generation has not been started, returns 57005.

u32AHI_ReadRandomNumber_MW()

uint32 u32AHI_ReadRandomNumber_MW(void);

(TWELITE GOLD only) Reads a 32-bit random value.

  • If random number generation has not been started, returns 3735928559.

vAHI_ReinitRandomNumberGenerator_MW()

void vAHI_ReinitRandomNumberGenerator_MW();

(TWELITE GOLD only) Reinitializes the random number generator device.

8 - AHI Functions and Explanations for UART

Explanations of the TWENET library and AHI functions related to UART
This section provides explanations of the TWENET library and AHI functions related to UART.

UART

UART usage relies on serial.c, .h and uart.c, .h found in TWENETutils.
This section explains AHI-compatible functions with behaviors specific to TWELITE GOLD.

  • When using UART1, you must call vAHI_UartSetLocation() or vAHI_UartSetLocationByPio_MW() to specify the assigned ports beforehand.
  • UART0 does not require any special procedure like UART1 for usage.

vAHI_UartSetLocation()

void vAHI_UartSetLocation(uint8_t u8port, bool_t bSel);

Specifies the port assignment for UART.

  • Does not affect UART0 assignment; it cannot be changed from the default ports (DIO6,7).
  • Two assignment options are available for UART1.
  • This function must be called when using UART1.
  • To assign other options for UART1, use vAHI_UartSetLocationEx_MW().
bSelTXRX
FALSEDIO14(PIO10)DIO15(PIO11)
TRUEDIO11(PIO0)*1DIO13(PIO1)

*1 This overlaps with the default SPICLK pin.

vAHI_UartSetLocationByPio_MW()

void vAHI_UartSetLocationByPio_MW(uint8_t u8port, uint8 u8TxPort, uint8 u8RxPort)

Assigns ports for UART.
Specify E_AHI_UART_1 for u8port.
Set the PIO numbers for the TX and RX ports using u8TxPort and u8RxPort.

Available PIO numbers (DIO numbers):

  • TX: 0 (DO0, DIO11), 6 (DIO5), 10 (DIO14), 20 (DIO16)
  • RX: 7 (DIO4), 1 (DIO13), 11 (DIO15), 19 (DIO13)

vAHI_UartDisable()

void vAHI_UartDisable(uint8_t u8port)

Disables the UART port specified by u8port.
The pin state will return to its initial configuration as defined in TWENETmcu/board/pin_mux.c at startup.

9 - AHI Functions and Explanations for WatchDog (WDT)

Explanations of the TWENET library and AHI functions related to WatchDog (WDT)
This section provides explanations of the TWENET library and AHI functions related to WatchDog (WDT).

WatchDog(WDT)

vAHI_WatchdogStart()

void vAHI_WatchdogStart(uint8 u8Prescale);

Starts the Watchdog Timer (WDT).

  • The timeout period is set approximately. Specifically, when u8Prescale == 0, the timeout is 8 ms; otherwise, it is set as ((1UL << (u8Prescale - 1)) + 1) * 8 ms, passed to the_wwdt->init().
  • If a value outside the valid range (u8Prescale > 12) is specified, u8Prescale = 10 (about 4 seconds) will be used.
  • When compiled with -DDEBUG, this process is skipped, and the WDT remains stopped.

vAHI_WatchdogStop()

void vAHI_WatchdogStop();

On TWELITE GOLD, once started, the watchdog cannot be stopped.
This function is called when changing the watchdog timer’s timeout period, as shown below:

...
vAHI_WatchdogStop(); // Calls the stop API (actually does not stop)
vAHI_WatchdogStart(12); // Reconfigures to approximately 16 seconds

vAHI_WatchdogRestart()

void   vAHI_WatchdogRestart();

Call this before the watchdog timer times out.

  • When compiled with -DDEBUG, this process is skipped.

10 - AHI Functions and Explanations for WakeTimer

Explanations of the TWENET library and AHI functions related to WakeTimer

WakeTimer

Implementation of vAHI_WakeTimer-related compatible functions.

The Wake Timer has two channels, both running continuously regardless of sleep state.
The counter operates in a decrementing manner, generating an interrupt when it reaches zero.
Additionally, since the wake timer keeps running, it can be used as a clock to measure elapsed time since startup.
For this purpose, a set of FRWT (Free Running WTimer) functions is also provided.

  • Timer width: E_AHI_WAKE_TIMER_0 = 41-bit, E_AHI_WAKE_TIMER_1 = 28-bit.
    The latter differs from BLUE/RED (JN516x); note that the maximum count value is 0x0FFFFFFF when calculating time differences.
    For example, to compute elapsed counts between ct1 and ct2, use (((ct2 << 4) - (ct1 << 4)) >> 4).
  • This library does not provide functions handling timer values exceeding 32 bits.
  • In the mwx library and some applications, one timer (E_AHI_WAKE_TIMER_0) is used continuously for time measurement through the Free Running WTimer (FRWT) API.

vAHI_WakeTimerEnable()

void vAHI_WakeTimerEnable(uint8 u8Timer,
						  bool_t bIntEnable)

Initializes the timer.

vAHI_WakeTimerStart()

void vAHI_WakeTimerStart(uint8 u8Timer, uint32 u32Count)

Starts the timer.
u32Count specifies the counter value.
For TWELITE GOLD, to trigger an interrupt after 1 second, specify 32768 (the frequency of the 32KHz crystal oscillator).

vAHI_WakeTimerStop()

void vAHI_WakeTimerStop(uint8 u8Timer)

Stops the timer.

u32AHI_WakeTimerCalibrate()

uint32 u32AHI_WakeTimerCalibrate(void);

Returns the wake timer calibration value 10000.

  • Normally, with a low-precision RC timer, this value would vary by about ±30%, but since TWELITE GOLD uses a 32KHz crystal-based timer circuit, this calibration is unnecessary, and the function always returns 10000.

u32AHI_WakeTimerRead()

uint32 u32AHI_WakeTimerRead(uint8 dev)

Returns the counter value. The wake-up interrupt occurs when the counter reaches zero. Afterward, the counter continues decrementing (after 0, it rolls over to the maximum value).

u8AHI_WakeTimerStatus()

uint8 u8AHI_WakeTimerStatus(void)

Returns the bitmap indicating the timer status.
E_AHI_WAKE_TIMER_0E_AHI_WAKE_TIMER_MASK_0 (1)
E_AHI_WAKE_TIMER_1E_AHI_WAKE_TIMER_MASK_1 (2)

u8AHI_WakeTimerFiredStatus()

uint8 u8AHI_WakeTimerFiredStatus()

Used immediately after wake-up.
If the wake-up source is WTIMER, a non-zero value is returned.

  • For E_AHI_WAKE_TIMER_0, returns E_AHI_WAKE_TIMER_MASK_0 (1).
  • For E_AHI_WAKE_TIMER_1, returns E_AHI_WAKE_TIMER_MASK_1 (2).

Free Running WTimer (FRWT)

Uses one channel of the WAKE TIMER (typically E_AHI_WAKE_TIMER_0) as a continuously running real-time counter. This allows time measurement regardless of the sleep state.

Global Variables

G_TWENET_FREE_RUNNING_WTIMER_ENABLED()

uint8_t G_TWENET_FREE_RUNNING_WTIMER_ENABLED() // MACRO

This variable is set in the cbAppColdStart(FALSE) call. Specify 0x80 to operate E_AHI_WAKE_TIMER_0 as FRWT. While the WAKE TIMER counter decrements over time, FRWT increments.

  • In the mwx library, FRWT with E_AHI_WAKE_TIMER_0 is automatically configured.

g_twenet_free_running_wtimer_boot_tick

uint32_t g_twenet_free_running_wtimer_boot_tick

Stores the counter value immediately after waking from sleep (with RAM retention). This is set when vAHI_FRWTSetBootCount_MW() is called from within the TWENET library.

vAHI_FRWTStart_MW()

void vAHI_FRWTStart_MW(uint8_t u8Timer)

This function is primarily used within the TWENET library and should not be used in user programs. FRWT is started based on the setting of the global variable G_TWENET_FREE_RUNNING_WTIMER_ENABLED().

u32AHI_FRWTGetCurrentCount_MW()

uint32 u32AHI_FRWTGetCurrentCount_MW()

Returns the FRWT counter value (32000 counts/second).

u32AHI_FRWTGetCurrentCount_msec_MW()

uint32 u32AHI_FRWTGetCurrentCount_msec_MW(uint32* dec_part)

Returns the current FRWT count in milliseconds.

  • dec_part specifies either NULL or a pointer to a uint32 variable.
    If provided, it returns the value in 1/10 millisecond units (0..9).

u32AHI_FRWTConvertCount_msec_MW()

static inline uint32 u32AHI_FRWTConvertCount_msec_MW(uint32 ct, uint32* dec_part) {
	// note: see wtimer::freerun_ct_convert_msec()
	uint64_t v = 1000ull * ct;
	if(dec_part) *dec_part = (10*(v & 32767)) >> 15;
	return (uint32)(v >> 15);
}

Converts the FRWT counter value to milliseconds.
If dec_part is specified, it returns the value in 1/10 millisecond units (0..9).

i32AHI_FRWTCompareCount_MW()

int32 i32AHI_FRWTCompareCount_MW(uint32 val_past, uint32 val_now)

Compares FRWT counter values. Specify val_now as the more recent value and val_past as the older value. In this case, the function returns a positive count value.

i32AHI_FRWTCompareCount_msec_MW()

int32 i32AHI_FRWTCompareCount_msec_MW(uint32 val_past, uint32 val_now)

Compares FRWT counter values.
Specify val_now as the more recent value and val_past as the older value.
In this case, the function returns the positive value in milliseconds.

vAHI_FRWTSetBootCount_MW()

void vAHI_FRWTSetBootCount_MW()

This function is primarily used within the TWENET library and should not be used in user programs.

It is used to save the FRWT counter value when waking up from sleep (with RAM retention, warm boot).

uint32 u32AHI_FRWTGetBootCount_MW()

uint32 u32AHI_FRWTGetBootCount_MW()

Returns the FRWT counter value when waking up from sleep (with RAM retention, warm boot).

u32AHI_FRWTGetBootCount_msec_MW()

uint32 u32AHI_FRWTGetBootCount_msec_MW()

Converts and returns the FRWT counter value in milliseconds when waking up from sleep (with RAM retention, warm boot).

11 - AHI Functions and Explanations for Onchip Temp Sensor

Explanations of the TWENET library and AHI functions related to the Onchip temp sensor

Onchip Temp Sensor

In TWELITE GOLD, a temperature sensor is implemented inside the chip.
The sensor value is used as a parameter for initializing the wireless MAC layer.

Handling of Temperature Sensor During MAC Layer Initialization

  • If the temperature sensor value cannot be obtained, initialization is performed with a default value of 20°C.
  • If more than G_TWENET_CHIPSENSOR_ADC_INTERVAL_MS() milliseconds have elapsed when waking up from sleep (RAM retained), the temperature is measured again at wake-up, and the MAC layer is reinitialized based on the sensor value.

Global Variables

uint8 G_TWENET_CHIPSENSOR_AUTO_ON_BOOT()
// Macro for variable access

A configuration variable to automatically acquire the temperature sensor value. Set it in cbAppColdStart(FALSE).

SettingDescriptionNotes
0Do not automatically acquire the temperature sensor value.MAC layer temperature correction uses a fixed value (20°C).
1Automatically acquire the temperature sensor value.
uint8_t G_TWENET_CHIPSENSOR_ADC_TIMES_SCALER()
// Macro for variable access
SettingADC Count
01
12
24
38

Specifies the scaler value corresponding to the number of ADC measurements for the temperature sensor.

int32 G_TWENET_CHIPSENSOR_TEMP128TH()
// Macro for variable access

Stores the temperature measured by the chip sensor in the TWENET library (value in °C multiplied by 128).

int16 g_twenet_chipsensor_volt_on_boot;

TWENET library stores the measured voltage value [mV].
This value is recorded at the same time as the temperature sensor measurement.

uint32 G_TWENET_CHIPSENSOR_ADC_INTERVAL_MS()
  = (10*60*1000ul)
// Macro for variable access

If the time elapsed since the last measurement is within the period specified by this variable, the temperature sensor reading will be skipped.
Set this in cbAppColdStart(FALSE).

uint8 g_twemet_chipsensor_capture_this_time;

An internal flag that determines whether to perform a temperature measurement at boot.

bAHI_AdcTemp_Measure_MW()

bool_t bAHI_AdcTemp_Measure_MW(
    int32 *i32temp_128th,
    int16 *i16volt_mv,
    uint8 adc_times_scaler,
    bool_t bTurnOnSensor)

Performs the temperature sensor measurement.

  • i32temp_128th is a pointer to an int32 variable that stores the temperature measurement result.
  • i16volt_mv is the power supply voltage [mV] measured at the same time.
  • adc_times_scaler specifies the scaler value corresponding to the number of ADC measurements for the temperature sensor. For configuration values, refer to the explanation of G_TWENET_CHIPSENSOR_ADC_TIMES_SCALER().
  • If bTurnOnSensor is set to TRUE, the function powers on the temperature sensor and performs the required waiting process. If set to FALSE, you must call vAHI_AdcTemp_TurnOn_MW() beforehand and ensure the required wait time has passed.

vAHI_AdcTemp_TurnOn_MW()

void vAHI_AdcTemp_TurnOn_MW()

Powers on the temperature sensor. A waiting time of 100 μs is required after this call.

uint32 u32AHI_AdcTemp_GetCaptTick_MW()

uint32 u32AHI_AdcTemp_GetCaptTick_MW()

Returns the FRWT timestamp of the last temperature sensor measurement in 32KHz count units.

uint32 u32AHI_AdcTemp_GetCaptTick_msec_MW()

uint32 u32AHI_AdcTemp_GetCaptTick_msec_MW()

Returns the FRWT timestamp of the last temperature sensor measurement in milliseconds.

u32AHI_AdcTemp_ElapsedFromCapt_msec_MW(), u32AHI_AdcTemp_TickrefFromCapt_msec_MW()

uint32 u32AHI_AdcTemp_ElapsedFromCapt_msec_MW()
uint32 u32AHI_AdcTemp_TickrefFromCapt_msec_MW(uint32 tick_ref)

Returns the elapsed time in milliseconds since the last temperature measurement.