Main Content

Do While 循环

此示例说明如何使用 Simulink® 模块和 Stateflow® 图实现 do while 循环构造。

C 构造

num_iter = 1;
do {
   flag = func();
   num_iter++;
   }
while (flag && num_iter <= 100)

Do While 循环的建模模式:While Iterator Subsystem 模块

创建 do while 循环的一种方法是使用 Simulink > 端口和子系统库中的 While Iterator Subsystem 模块。

1.打开示例模型 ex_do_while_loop_SL

该模型包含一个 While Iterator Subsystem 模块,该模块在仿真时间步期间重复执行子系统的内容。

观察 While Iterator Subsystem 中的以下设置:

  • func 子系统模块的输出 flag01,具体取决于 func( ) 中的算法结果。func()func 子系统中的函数名称

  • 对于 While Iterator 模块,最大迭代次数100

  • 对于 While Iterator 模块,While 循环类型do-while

2.要编译模型并生成代码,请按 Ctrl+B

实现 do while 循环的代码位于 ex_do_while_loop_SL.c 中的 ex_do_while_loop_SL_step 函数中:

/* Model step function */
void ex_do_while_loop_SL_step(void)
{
  int32_T s1_iter;

  /* Outputs for Iterator SubSystem: '<Root>/While Iterator Subsystem' incorporates:
   *  WhileIterator: '<S1>/While Iterator'
   */
  s1_iter = 1;

  /* SystemReset for Atomic SubSystem: '<S1>/func' */
  func_Reset();

  /* End of SystemReset for SubSystem: '<S1>/func' */
  /* End of Outputs for SubSystem: '<Root>/While Iterator Subsystem' */
  do {
    func();
    s1_iter++;
  } while (flag && (s1_iter <= 100));
}

Do While 循环的建模模式:Stateflow 图

1.打开示例模型 ex_do_while_loop_SF

在该模型中,ex_do_while_loop_SF/Chart 执行 do while 循环。

该图包含 While 循环决策模式,您可以通过选择 > 在图中添加构型 > 循环 > While 来添加该模式。

2.要编译模型并生成代码,请按 Ctrl+B

实现 do while 循环的代码位于 ex_do_while_loop_SF.c 中的 ex_do_while_loop_SF_step 函数中:

/* Model step function */
void ex_do_while_loop_SF_step(void)
{
  int32_T num_iter;

  /* Chart: '<Root>/Chart' */
  num_iter = 1;
  do {
    func();
    num_iter++;
  } while (flag && (num_iter <= 100));
}

另请参阅

相关主题