Main Content

Generate Code for an Elapsed Time Counter

This example shows a model that includes a triggered subsystem, Amplifier, consisting of a Discrete-Time Integrator block that uses an elapsed time counter. The model ex_elapseTime is in the folder matlab/help/toolbox/rtw/examples.

ex_elapseTime Model

Amplifier Subsystem

Code in the generated header file ex_elapseTime.h for the model uses 64 bits to implement the timer for the base rate (clockTick0 and clockTickH0).

/*
 * Timing:
 * The following substructure contains information regarding
 * the timing information for the model.
 */
struct {
  time_T taskTime0;
  uint32_T clockTick0;
  uint32_T clockTickH0;
  time_T stepSize0;
  time_T tFinal;
  boolean_T stopRequestedFlag;
} Timing;

The code generator allocates storage for the previous-time value and elapsed-time value of the Amplifier subsystem (Amplifier_PREV_T) in the D_Work(states) structure in ex_elapsedTime.h.

/* Block states (auto storage) for system '<Root>' */
typedef struct { 
  real_T DiscreteTimeIntegrator_DSTATE;
    /* '<S1>/Discrete-Time Integrator' */
  int32_T clockTickCounter;            
    /* '<Root>/Pulse Generator' */
  uint32_T Amplifier_ELAPS_T[2];       
    /* '<Root>/Amplifier' */
  uint32_T Amplifier_PREV_T[2];        
    /* '<Root>/Amplifier' */
	} DW_ex_elapseTime_T;

The elapsed time computation is performed as follows within the ex_elapseTime_step function:

/* ---
   Outputs for Triggered SubSystem:
      '<Root>/Amplifier' incorporates:
         TriggerPort: '<S1>/Trigger'
 --- */
 zcEvent = rt_ZCFcn(RISING_ZERO_CROSSING,
        &ex_elapseTime_PrevZCX.Amplifier_Trig_ZCE,           
        ((real_T)rtb_PulseGenerator));
	if (zcEvent != NO_ZCEVENT) {
   elapseT_H = ex_elapseTime_M->Timing.clockTickH0 -
	    ex_elapseTime_DW.Amplifier_PREV_T[1];
	  if (ex_elapseTime_DW.Amplifier_PREV_T[0] >
       ex_elapseTime_M->Timing.clockTick0) {
     elapseT_H--;
	  }

   ex_elapseTime_DW.Amplifier_ELAPS_T[0] = 
      ex_elapseTime_M->Timing.clockTick0 
      - ex_elapseTime_DW.Amplifier_PREV_T[0];
   ex_elapseTime_DW.Amplifier_PREV_T[0] = 
      ex_elapseTime_M->Timing.clockTick0;
   ex_elapseTime_DW.Amplifier_ELAPS_T[1] = 
      elapseT_H;
   ex_elapseTime_DW.Amplifier_PREV_T[1] = 
      ex_elapseTime_M->Timing.clockTickH0;

As shown above, the elapsed time is maintained as a state of the triggered subsystem. The Discrete-Time Integrator block finally performs its output and update computations using the elapsed time.

/* ---
DiscreteIntegrator: '<S1>/Discrete-Time Integrator' 
--- */
OUTPUT = ex_elapseTime_DW.DiscreteTimeIntegrator_DSTATE;

/* --- 
Update for DiscreteIntegrator: 
   '<S1>/Discrete-Time Integrator' incorporates:
      Constant: '<Root>/Constant'
--- */
   ex_elapseTime_DW.DiscreteTimeIntegrator_DSTATE += 0.3 * (real_T)
     ex_elapseTime_DW.Amplifier_ELAPS_T[0] * 1.5;

Related Topics