Adding Custom Control Functions

The motor control application is structured to make it straightforward to add custom control logic at three different execution rates:

  1. Interrupt-based routines — triggered by a new hardware event (timer, GPIO, etc.)

  2. Synchronous routines — execute at the same rate as the FOC ISR (every PWM cycle)

  3. Asynchronous routines — execute in the low-priority background loop (~1 ms)


Execution Context Summary

digraph execution_contexts { rankdir=TB; node [shape=box, style="filled,rounded", fontname="Helvetica", fontsize=10, margin="0.2,0.08"]; edge [color="#555555"]; subgraph cluster_high { label="High Priority — ISR rate (= PWM freq, e.g. 66 µs at 15 kHz)"; style=filled; fillcolor="#fff8f8"; color="#e74c3c"; A [label="ADC0_INT1_IRQHandler\nisr.c", fillcolor="#f9ebea", color="#e74c3c"]; B [label="application_run()\nFOC Feedback → Observers → State Machine → Feedforward", fillcolor="#f9ebea", color="#e74c3c"]; C [label="Custom synchronous code here\nAfter FOC_runFeedforward()", fillcolor="#d5f5e3", color="#27ae60"]; A -> B -> C; } subgraph cluster_medium { label="Medium Priority — Custom rate"; style=filled; fillcolor="#fffdf5"; color="#e67e22"; D [label="Custom ISR here\nNew timer / GPIO / peripheral ISR\nNVIC priority LOWER than ADC ISR", fillcolor="#fdebd0", color="#e67e22"]; } subgraph cluster_low { label="Low Priority — ~1 ms"; style=filled; fillcolor="#f5f9ff"; color="#2980b9"; E [label="main() background loop", fillcolor="#d4e6f1", color="#2980b9"]; F [label="FOC_runLowPriorityStateMachine()\nFault check, monitor, trajectory", fillcolor="#d4e6f1", color="#2980b9"]; G [label="Custom async code here\nUART, LED, logging, host comms", fillcolor="#d4e6f1", color="#2980b9"]; E -> F -> G; } }


1. Adding an Interrupt-Based Routine

Use this approach when you need to respond to a hardware event (timer overflow, GPIO edge, SPI completion, etc.) at a rate independent of the FOC ISR.

Step 1 — Add the Peripheral in SysConfig

Open the .syscfg file and add the new peripheral. For example, to add a 1 kHz timer:

  1. Add a timer module instance

  2. Set the period to 1 ms

  3. Enable the interrupt

  4. Note the generated instance name (e.g., TIMER_0)

SysConfig generates the IRQ handler name in ti_sdk_dl_config.h:

/* Generated by SysConfig */
#define TIMER_0_INST                    TIMA0
#define TIMER_0_INST_IRQHandler         TIMA0_IRQHandler
#define TIMER_0_INST_INT_IRQN           TIMA0_INT_IRQn

Step 2 — Add the ISR Handler in isr.c

Add the new ISR handler in isr.c:

/* isr.c */
#include "application.h"
#include "mtr_config.h"

/* Existing FOC ISR — DO NOT MODIFY */
MOTOR_CTRL_RAMFUNC void ADC0_INT1_IRQHandler(void)
{
    HAL_ackMtrADCInt(&motorVars_M1.halInterface->halFOCConfigHandle->intCfg);
    HAL_setGPIOHigh((uint32_t)MTR1_FOC_CTRL_ISR_TIMING_PORT, MTR1_FOC_CTRL_ISR_TIMING_PIN);
    application_run((MOTOR_Handle)&motorVars_M1);
    HAL_setGPIOLow((uint32_t)MTR1_FOC_CTRL_ISR_TIMING_PORT, MTR1_FOC_CTRL_ISR_TIMING_PIN);
    systemVars.timerCntFOCCtrlISR++;
}

/* Custom 1 kHz timer ISR */
void TIMA0_IRQHandler(void)
{
    /* Acknowledge interrupt */
    DL_TimerA_clearInterruptStatus(TIMER_0_INST, DL_TIMER_INTERRUPT_ZERO_EVENT);

    /* Custom logic here — e.g., update a communication protocol,
     * read a sensor, or update a slow control loop */
    myCustom1kHzTask();
}

Step 3 — Set NVIC Priority

Warning

The FOC ADC ISR (ADC0_INT1_IRQHandler) must always have the highest NVIC priority among motor control interrupts. Any custom ISR must be assigned a lower priority (higher numeric value) to prevent it from preempting the FOC loop.

Preempting the FOC ISR can cause:

  • PWM duty cycle update missed → current distortion

  • Observer state corruption → loss of angle tracking

  • Timing violations → motor instability or fault

Set the NVIC priority in main.c after SYSCFG_DL_init():

/* main.c — after SYSCFG_DL_init() */

/* FOC ADC ISR — highest priority (lowest numeric value) */
NVIC_SetPriority(ADC0_INT_IRQn, 0);

/* Custom timer ISR — lower priority than FOC */
NVIC_SetPriority(TIMA0_INT_IRQn, 2);

/* Enable custom timer interrupt */
NVIC_EnableIRQ(TIMA0_INT_IRQn);

NVIC Priority Guidelines

ISR

Recommended Priority

Rationale

ADC0_INT1_IRQHandler (FOC)

0 (highest)

Must never be preempted

Gate driver nFAULT GPIO ISR

1

Fast fault response

Custom timer / sensor ISR

2–3

Non-critical, can be delayed

UART / SPI communication ISR

4–7

Tolerates latency


2. Adding Synchronous Routines (Same Rate as FOC ISR)

Use this approach when your custom algorithm must execute every PWM cycle — for example, a custom current feedforward, a custom observer, or a data capture buffer.

Where to Add Code

Add custom code in application.c inside application_run(), after FOC_runFeedforward():

/* application.c */
MOTOR_CTRL_RAMFUNC void application_run(MOTOR_Handle motorHandle)
{
    MOTOR_Vars_t *obj = (MOTOR_Vars_t *)motorHandle;

    obj->ISRCount++;

    /* Section 1: FOC Feedback */
    FOC_runFeedback(obj);

    /* Section 2: Observers */
    FOC_runObservers(obj);

    /* Section 3: State Machine */
    FOC_runStateMachine(obj);

    /* Section 4: FOC Feedforward */
    FOC_runFeedforward(obj);

    /* ================================================================
     * Section 5: CUSTOM SYNCHRONOUS CODE
     * Executes every PWM cycle (at USER_M1_PWM_FREQ_kHz rate).
     * All FOC outputs (Idq, Vdq, angleFOC, speed) are available here.
     * ================================================================ */
    myCustomSynchronousTask(obj);
}

Accessing FOC Data

Inside your custom function, all FOC data is available through the MOTOR_Vars_t pointer:

/* Custom synchronous function example */
static void myCustomSynchronousTask(MOTOR_Vars_t *obj)
{
    /* Read FOC outputs */
    float32_t speedHz    = obj->outVars.speed_Hz;
    float32_t iqCurrent  = obj->outVars.Idq_in_A.value[1];
    float32_t angleFOC   = obj->outVars.angleFOC_rad;
    float32_t vdcBus     = obj->adcData->VdcBus_V;

    /* Read current references */
    float32_t idRef = obj->outVars.Idq_out_A.value[0];
    float32_t iqRef = obj->outVars.Idq_out_A.value[1];

    /* Custom computation */
    /* ... */

    /* Optionally modify current references (use with care) */
    /* obj->outVars.Idq_out_A.value[0] += myIdFeedforward; */
}

Execution Budget

Warning

The total ISR execution time (all 5 sections + custom code) must fit within the PWM period: 1000 / USER_M1_PWM_FREQ_kHz µs (e.g. 66 µs at 15 kHz, 10 µs at 100 kHz). The motor control algorithm itself consumes approximately 6–10 µs; the remaining budget is available for custom code. Use CPU_TIME_Obj to measure:

/* main.h already declares: */
extern CPU_TIME_Obj    cpuTime;
extern CPU_TIME_Handle cpuTimeHandle;

/* In main.c, after init: */
CPU_TIME_run(cpuTimeHandle);  /* Start measurement */
/* Check cpuTime.deltaTimeUsec in watch window */

If the ISR overruns, reduce PWM frequency in user_mtr1.h or move non-critical computation to the low-priority background loop.

RAM Placement

Custom synchronous functions that are called from the ISR should be placed in RAM to avoid flash wait-state latency:

/* Place custom ISR-rate function in RAM */
MOTOR_CTRL_RAMFUNC static void myCustomSynchronousTask(MOTOR_Vars_t *obj)
{
    /* ... */
}

3. Adding Asynchronous Low-Priority Routines

Use this approach for tasks that do not need to run every PWM cycle — communication protocols, LED control, fault logging, host interface updates, or slow outer-loop control.

Option A — Add to the Background Loop in main.c

The simplest approach: add code directly in the main() while-loop, gated by the 1 ms timer:

/* main.c */
while (systemVars.flagEnableSystem == true)
{
    if (systemVars.timerCntFOCCtrlISR > LOW_PRIORITY_WAIT_TIME_1ms)
    {
        systemVars.timerCntFOCCtrlISR = 0;

        /* Existing low-priority state machine */
        FOC_runLowPriorityStateMachine(&motorVars_M1);

        /* Custom 1 ms task */
        myCustom1msTask(&motorVars_M1, &systemVars);
    }
}

Option B — Add Inside FOC_runLowPriorityStateMachine()

For tasks that need access to the motor state machine context, add them inside FOC_runLowPriorityStateMachine() in application.c:

/* application.c */
void FOC_runLowPriorityStateMachine(MOTOR_Handle motorHandle)
{
    MOTOR_Vars_t *obj = (MOTOR_Vars_t *)motorHandle;

    LowPriority_handleMotorCheckFaults(motorHandle);
    LowPriority_handleMotorCheckStop(motorHandle);
    LowPriority_handleCheckInstaSpinEstimatorErrors(motorHandle);
    LowPriority_handleMotorIDAndTrajectory(motorHandle);
    runMotorMonitor(motorHandle);

    /* State-specific tasks */
    switch (obj->outVars.motorState)
    {
        /* ... existing cases ... */
    }

    /* Custom low-priority task — runs every ~1 ms */
    myCustomLowPriorityTask(motorHandle);
}

Example: Custom UART Status Report

/* Custom 1 ms task — send motor status over UART */
static void myCustom1msTask(MOTOR_Vars_t *motor, SYSTEM_Vars_t *sys)
{
    static uint16_t reportCounter = 0;

    reportCounter++;

    /* Send status every 100 ms (every 100 calls at 1 ms rate) */
    if (reportCounter >= 100U)
    {
        reportCounter = 0U;

        /* Read motor status */
        float32_t speed = motor->outVars.speed_Hz;
        uint16_t  state = (uint16_t)motor->outVars.motorState;
        uint16_t  fault = motor->outVars.faultMtrNow.all;

        /* Format and send (non-blocking) */
        /* myUART_sendStatus(speed, state, fault); */
    }
}

Example: Custom Slow Outer-Loop Control

/* Custom 10 ms outer-loop (runs every 10 calls at 1 ms rate) */
static void myCustomOuterLoop(MOTOR_Vars_t *motor)
{
    static uint16_t outerLoopCounter = 0;

    outerLoopCounter++;

    if (outerLoopCounter >= 10U)
    {
        outerLoopCounter = 0U;

        /* Read sensor or host command */
        float32_t targetSpeed = myReadSpeedCommand();

        /* Update speed reference — ISR reads this next cycle */
        motor->inputCtrl.speedRef_Hz = targetSpeed;
    }
}

Note

Writing to motor->inputCtrl.speedRef_Hz from the background loop is safe because the speed controller runs at a decimated rate (numCtrlTicksPerSpeedTick = 10 ISR ticks). The background loop runs every LOW_PRIORITY_WAIT_TIME_1ms ISR ticks (= 1000 / USER_M1_PWM_FREQ_kHz), which is much slower than the FOC ISR, so there is no race condition on this float variable on a single-core M33.


Summary

Approach

Rate

Where to Add

Use Case

New ISR

Custom (hardware event)

isr.c + SysConfig

Sensor read, protocol response

Synchronous

Every PWM cycle (USER_M1_PWM_FREQ_kHz)

application_run() in application.c

Custom observer, feedforward, data capture

Asynchronous (background)

Every LOW_PRIORITY_WAIT_TIME_1ms ISR ticks (~1 ms)

main() while-loop or FOC_runLowPriorityStateMachine()

UART, LED, host interface, slow outer loop

Warning

Never add blocking delays (while, for loops waiting on hardware) inside the FOC ISR or application_run(). Any blocking code will cause the ISR to overrun its execution budget (1000 / USER_M1_PWM_FREQ_kHz µs) and corrupt the FOC execution.