MATLAB Examples

# Overrun Actions for Fixed Rate Execution

The Rate object uses the OverrunAction property to decide how to handle code that takes longer than the desired period to operate. The options are 'slip' (default) or 'drop'. This example shows how the OverrunAction affects code execution.

Setup desired rate and loop time. slowFrames is an array of times when the loop should be stalled longer than the desired rate.

```desiredRate = 1; loopTime = 20; slowFrames = [3 7 12 18]; ```

Create the Rate object and specify the OverrunAction property. 'slip' indicates that the waitfor function will return immediately if the time for LastPeriod is greater than the DesiredRate property.

```rate = robotics.Rate(desiredRate); rate.OverrunAction = 'slip'; ```

Reset Rate object and begin loop. This loop will execute at the desired rate until the loop time is reached. When the TotalElapsedTime reaches a slow frame time, it will stall for longer than the desired period.

```reset(rate); while rate.TotalElapsedTime < loopTime if ~isempty(find(slowFrames == floor(rate.TotalElapsedTime))) pause(desiredRate + 0.1) end waitfor(rate); end ```

View statistics on the Rate object. Notice the number of periods.

```stats = statistics(rate) ```
```stats = struct with fields: Periods: [1x20 double] NumPeriods: 20 AveragePeriod: 1.0208 StandardDeviation: 0.0425 NumOverruns: 4 ```

Change the OverrunAction to 'drop'. 'drop' indicates that the waitfor function will return at the next time step, even if the LastPeriod is greater than the DesiredRate property. This effectively drops the iteration that was missed by the slower code execution.

```rate.OverrunAction = 'drop'; ```

Reset Rate object and begin loop.

```reset(rate); while rate.TotalElapsedTime < loopTime if ~isempty(find(slowFrames == floor(rate.TotalElapsedTime))) pause(1.1) end waitfor(rate); end stats2 = statistics(rate) ```
```stats2 = struct with fields: Periods: [1x16 double] NumPeriods: 16 AveragePeriod: 1.2502 StandardDeviation: 0.4470 NumOverruns: 4 ```

Using the 'drop' over run action resulted in 16 periods when the 'slip' resulted in 20 periods. This difference is because the 'slip' did not wait until the next interval based on the desired rate. Essentially, using 'slip' tries to keep the AveragePeriod property as close to the desired rate. Using 'drop' ensures the code will execute at an even interval relative to DesiredRate with some iterations being skipped.