C++ block question

Hello Mike, EMRod,

I am now experimenting similar hybrid simulation where the discrete time control algorithm
is embedded into the continuous time environment. I have tried before similar with Ltspice
but is was uncomfortable and limited (e.g. state machine) but the C++ block in QSPICE is
a really great feature.

I did similar what Mike suggested (the code is in an if statement) and the result is quite good.
You can see testOut variable is incremented only once so the algorithm runs once in each
control period and the time between executions.

This is a little awkward because I bound the the algorithm execution to the simulation time
propably the result will be better (the time between executions will be more equidistant) in
case of using external clock as you intended. So propably this is not the best way to do
similar simulation but I hope it gives idea to do it better.

WinterMime

extern "C" __declspec(dllexport) void untitled_x1(void **opaque, double t, union uData *data)
{
   double  IN    = data[0].d; // input
   double &OUT   = data[1].d; // output
   double &tdiff = data[2].d; // output

   static double tprev = 0;
   static double lastTick = -1;
   static int testOut = 0;
   //static int timerPeriod = 1000; // 1 kHz control (1ms period)
   static int timerPeriod = 8000; // 8 kHz control (125us period)
   static double timeDiff = 125E-6;

   if ((int)(t*timerPeriod) != lastTick)
   {
      lastTick = (int)(t*timerPeriod);
      if (lastTick > 0) timeDiff = t - tprev;
      tprev = t;

      // Control algorithm goes here...

      // Check executions.
      testOut++;
   }

   OUT = testOut;
   tdiff = timeDiff;
}