Create Delay with C-script

You should read the chapters “How PLECS works” and “Using C-Scripts” in the PLECS manual. I put some comments in the code (and made some additions) below to make it more understandable.

 
// We are not worried about integration and such, so only consider major steps
if(IsMajorStep)
{
   // Continuous task: Rising edge detection and start of delay
   if(IsSampleHit(0))
   {      
      // Detect edge of incoming signal
      if(Input_pre == 0 && InputSignal(0, 0) == 1)
      {
          // Calculate time or next execution of task 1
          double nextHit = CurrentTime + InputSignal(1, 0);
          if (nextHit > CurrentTime)
             NextSampleHit = CurrentTime + InputSignal(1, 0);
          else
             OutputSignal(0, 0) = 1; // no delay, output 1 immediately
      }
      // Detect falling edge
      if(Input_pre == 1 && InputSignal(0, 0) == 0)
      {
         // Cancel delay
         NextSampleHit = NEVER;
         // Output 0 immediately
         OutputSignal(0, 0) = 0;
      }
   }
   // Task 1: executed after specified delay after edge detection
   if(IsSampleHit(1))
   {
      // Safety measure: check if input signal is still 1
      if (InputSignal(0, 0) == 1)
         OutputSignal(0, 0) = 1; // turn-on delay over, turn on signal
   }
}


Kind regards,

Oliver