从零搭建一个状态机MATLAB → Stateflow → 生成 C 代码 → 跑起来关键词有限状态机FSM、MATLAB、Stateflow、Simulink Coder、代码生成环境MATLAB R2021b Simulink Stateflow Simulink Coder示例模型turnstile地铁闸机 / 十字转门本教程用一个大家都熟悉的例子——地铁闸机——把状态机从一段 MATLAB 脚本一路做到生成 C 代码并编译运行。你会看到状态机在代码里长什么样怎么用 Stateflow 图形化建模并自动保存成.slx从.slx一键生成 C 代码生成的 C 代码和状态机如何一一对应写一个main.c把生成代码真正跑起来几个容易踩的坑变步长、输入事件 vs 输入数据、首步不解锁、乱码、最小文件集0. 为什么用闸机做例子闸机只有两种状态规则也极简却包含了状态机的全部精髓状态Locked锁定/Unlocked放行事件coin投币/push推门转移规则当前状态事件结果Lockedcoin→ Unlocked投币开门Lockedpush保持 Locked没投币推不动Unlockedpush→ Locked通过后重新锁Unlockedcoin保持 Unlocked重复投币无效一句话只认先投币、再推门一张票过一个人。1. 先用纯 MATLAB 手写状态机最直观不用任何工具箱纯.m就能表达状态机。核心是三样东西一组状态、一个当前状态变量、一组转移规则。1.1 事件驱动版switch 实现% turnstile_statemachine.mfunctionturnstile_statemachine()stateLOCKED;fprintf(初始: %s\n,state);events{coin,push,coin,coin,push,push};fori1:numel(events)eevents{i};switchstatecaseLOCKEDifstrcmp(e,coin)stateUNLOCKED;fprintf(事件 %-6s - 投币成功闸机打开\n,e);elsefprintf(事件 %-6s - 门是锁的推不动\n,e);endcaseUNLOCKEDifstrcmp(e,push)stateLOCKED;fprintf(事件 %-6s - 通过闸机重新锁定\n,e);elsefprintf(事件 %-6s - 已打开重复投币无效\n,e);endendendend运行turnstile_statemachine1.2 能生成 C 代码版MATLAB Coder 友好上面的写法用了字符串状态、cell数组、strcmp不能直接生成 C 代码。要生成 C得用整数表示状态/事件且不能有动态字段名、不能有pause% turnstile_step.m%#codegenfunctionnextStateturnstile_step(currentState,event)LOCKED0;UNLOCKED1;COIN0;PUSH1;nextStatecurrentState;% 默认保持当前状态switchcurrentStatecaseLOCKEDifeventCOIN,nextStateUNLOCKED;endcaseUNLOCKEDifeventPUSH,nextStateLOCKED;endendend生成 C 代码需 MATLAB Codercodegen turnstile_step-args{0,0}-report这一版是手写状态机直接出 C的路线。但我们更想看的是Stateflow 图形化建模 → 生成 C所以下面走.slx路线。2. 用 Stateflow API 自动生成.slx模型不想手点鼠标画状态图可以用 Stateflow 的 API 写个脚本程序化建图并保存成.slx% generate_turnstile_slx.mfunctiongenerate_turnstile_slx()modelturnstile;ifbdIsLoaded(model),close_system(model,0);endifexist([model.slx],file),delete([model.slx]);endsfnew(model);open_system(model);% 新建带 Stateflow 图的模型rtsfroot;chartrt.find(-isa,Stateflow.Chart,-and,Path,[model/Chart]);% 输入数据 coin / pushboolean作为图块输入端口dCoinStateflow.Data(chart);dCoin.Namecoin;dCoin.ScopeInput;dCoin.DataTypeboolean;dPushStateflow.Data(chart);dPush.Namepush;dPush.ScopeInput;dPush.DataTypeboolean;% 两个状态lockStateflow.State(chart);lock.NameLocked;lock.Position[406012070];unlStateflow.State(chart);unl.NameUnlocked;unl.Position[2406012070];% 默认转移上电即 LockeddefTStateflow.Transition(chart);defT.Destinationlock;% 状态间转移用输入数据做守卫条件 [ ]t1Stateflow.Transition(chart);t1.Sourcelock;t1.Destinationunl;t1.LabelString[coin];t2Stateflow.Transition(chart);t2.Sourceunl;t2.Destinationlock;t2.LabelString[push];% 根部接 Inport让图能被驱动add_block(simulink/Sources/In1,[model/coin_in],Position,[2010050120]);add_block(simulink/Sources/In1,[model/push_in],Position,[2022050240]);add_line(model,coin_in/1,Chart/1);add_line(model,push_in/1,Chart/2);% 关键固定步长求解器 仅生成代码免 C 编译器set_param(model,SolverType,Fixed-step);set_param(model,Solver,FixedStepDiscrete);set_param(model,FixedStep,1);set_param(model,GenCodeOnly,on);save_system(model,[model.slx]);close_system(model,0);end运行generate_turnstile_slx即得到turnstile.slx。双击Chart就能看到图形化的Locked --[coin]-- Unlocked和Unlocked --[push]-- Locked。⚠️坑 1输入事件 vs 输入数据一开始我把coin/push设成输入事件Input Event结果生成的 C 代码里图被优化成空函数——因为没有东西去触发这些事件。改成输入数据 [ ]守卫并从根部 Inport 喂数据后状态机才真正进入生成代码。3. 从.slx生成 C 代码load_system(turnstile)slbuild(turnstile)% 等价于在模型里按 CtrlB⚠️坑 2变步长求解器报错sfnew建的模型默认是变步长而grt/ert代码生成要求固定步长否则报The specified code generation target ... cannot be used with a variable-step solver.解决脚本里已设SolverTypeFixed-stepSolverFixedStepDiscrete。生成成功后代码在turnstile_grt_rtw/下。重点文件turnstile.c/turnstile.h—— 模型步函数与接口状态机逻辑就内联在turnstile_step()里4. 生成的 C 代码和状态机怎么对应看turnstile.c里最关键的几段。4.1 状态名 → 整数常量#defineturnstile_IN_Locked((uint8_T)1U)#defineturnstile_IN_NO_ACTIVE_CHILD((uint8_T)0U)#defineturnstile_IN_Unlocked((uint8_T)2U)Stateflow 把图里的Locked/Unlocked字符串编成了整数枚举。4.2 当前状态 → 一个变量typedefstruct{uint8_T is_active_c3_turnstile;/* 图是否已激活 */uint8_T is_c3_turnstile;/* 当前状态存上面的 IN_ 常量*/}DW_turnstile_T;这就是 FSM 里的当前状态变量跨step调用一直保持。4.3 输入 → 一个结构体typedefstruct{boolean_T coin_in;/* 根 Inport: coin */boolean_T push_in;/* 根 Inport: push */}ExtU_turnstile_T;4.4 转移逻辑 →turnstile_step()voidturnstile_step(void){if(turnstile_DW.is_active_c3_turnstile0U){turnstile_DW.is_active_c3_turnstile1U;turnstile_DW.is_c3_turnstileturnstile_IN_Locked;// 默认转移 - Locked}elseif(turnstile_DW.is_c3_turnstileturnstile_IN_Locked){if(turnstile_U.coin_in){turnstile_DW.is_c3_turnstileturnstile_IN_Unlocked;// t1: [coin]}}elseif(turnstile_U.push_in){turnstile_DW.is_c3_turnstileturnstile_IN_Locked;// t2: [push]}}生成代码状态机含义第 1 个ifis_active0默认转移defT → Lockedelse if (is_c3Locked) { if(coin_in) ... }t1:Locked --[coin]-- Unlockedelse if (push_in)走到这必是 Unlockedt2:Unlocked --[push]-- Locked代码生成器把每个状态一个 if 块压成了if/else链语义和手写switch完全等价。5. 写main.c把生成代码跑起来生成代码不会自己运行需要一个宿主程序去喂输入、推步、读状态/* main.c */#includestdio.h#includeturnstile.h/* 与 turnstile.c 中的 #define 保持一致Stateflow 把状态编成整数*/#ifndefturnstile_IN_Locked#defineturnstile_IN_Locked((uint8_T)1U)#defineturnstile_IN_Unlocked((uint8_T)2U)#endifstaticconstchar*state_name(uint8_T s){if(sturnstile_IN_Locked)returnLocked;if(sturnstile_IN_Unlocked)returnUnlocked;returnNO_ACTIVE_CHILD;}intmain(void){constintcoin_seq[6]{1,0,1,1,0,0};constintpush_seq[6]{0,1,0,0,1,1};inti;turnstile_initialize();printf(initial state: %s\n,state_name(turnstile_DW.is_c3_turnstile));for(i0;i6;i){turnstile_U.coin_in(boolean_T)coin_seq[i];// 喂输入turnstile_U.push_in(boolean_T)push_seq[i];turnstile_step();// 推进一步printf(step %d: coin%d push%d - state: %s\n,i1,coin_seq[i],push_seq[i],state_name(turnstile_DW.is_c3_turnstile));}turnstile_terminate();return0;}5.1 用 MATLAB 自带的 LCC 编译编译命令关键标志已标出rem build_main.bat 自动探测 MATLAB 根目录 set LCC%MATLAB_ROOT%\sys\lcc64\lcc64\bin\lcc64.exe set LNK%MATLAB_ROOT%\sys\lcc64\lcc64\bin\lcclnk64.exe set LCCINC%MATLAB_ROOT%\sys\lcc64\lcc64\include64 set INC.\turnstile_grt_rtw set MATLABINC%MATLAB_ROOT%\extern\include set SIMINC%MATLAB_ROOT%\simulink\include set RTWSRC%MATLAB_ROOT%\rtw\c\src set LIB%MATLAB_ROOT%\sys\lcc64\lcc64\lib64 rem 编译注意 -noregistrylookup 关掉交互式询问 %LCC% -c -w -noregistrylookup -nodeclspec -I%LCCINC% -I%INC% -I%MATLABINC% -I%SIMINC% -I%RTWSRC% main.c -Fomain.obj %LCC% -c -w -noregistrylookup -nodeclspec -I%LCCINC% -I%INC% -I%MATLABINC% -I%SIMINC% -I%RTWSRC% %INC%\turnstile.c -Foturnstile.obj rem 链接用 -L 指定库路径不是 -libpath %LNK% -s -L%LIB% -o turnstile_demo.exe main.obj turnstile.obj⚠️坑 3LCC 的两个编译细节必须加-noregistrylookup否则 LCC 会弹窗交互式询问头文件路径链接用-Llib64指定库搜索路径不是-libpath。运行turnstile_demo.exeinitial state: NO_ACTIVE_CHILD step 1: coin1 push0 - state: Locked step 2: coin0 push1 - state: Locked step 3: coin1 push0 - state: Unlocked step 4: coin1 push0 - state: Unlocked step 5: coin0 push1 - state: Locked step 6: coin0 push1 - state: Locked行为完全正确Locked 下 coin 才解锁、push 无效Unlocked 下 push 才回锁、coin 无效。⚠️坑 4中文乱码若把输出写成中文源文件是 UTF-8而cmd默认用 GBK会乱码。最稳的做法是输出字符串用英文ASCII或在cmd里先chcp 65001再运行。6. 为什么 step 1 投了币却还是 Locked这是状态机的标准语义不是 bugturnstile_step()是if / else if链一步只走一个分支step 1is_active 0进入激活分支执行默认转移进入Locked。因为进了if后面的else if含coin判断这一步不执行coin1被吞掉。step 3图表早已激活且处于Locked才走coin分支 →Unlocked。即第一步是闸机通电、默认锁上事件从下一步才开始被处理。想要 step 1 就解锁只要在最前面加一个预热步coin0, push0即可。7. 生成代码里哪些文件才是必需的不用全用。对这个简单模型编译时只需要turnstile.cturnstile.h外加它们#include的一堆纯头文件不需要再编额外.c。文件需要turnstile.c✅ 必须编译turnstile.h及它包含的*.h类型定义✅ 留着纯头文件不编译rt_nonfinite.c/rtGetInf.c/rtGetNaN.c❌ 本模型没用到浮点 Inf/NaN 支持被省去*.mat/*.dmr/*.mk/*.rsp/rtw_proj.tmw❌ 生成元数据不参与编译实测turnstile.c只#include了turnstile.h和turnstile_private.h且完全没有调用任何rt_*函数——所以只编这一个.c就能出可执行文件。注意因为turnstile.h间接包含了 MATLAB 的几个头文件tmwtypes.h等若放到没装 MATLAB 的机器上编译需要把这些头文件一并复制过去都是纯头文件无害。8. 总结与延伸一路下来我们打通了手写 .m 状态机 → Stateflow 建 .slx 图 → slbuild 生成 C → main.c 驱动 → 编译运行三条路线对比路线工具适合手写.mMATLAB逻辑简单、想直接读代码.m MATLAB CoderMATLAB Coder从脚本直接出 C轻量.slx Simulink CoderStateflow / Simulink Coder图形化、复杂状态、要产品级代码可以继续玩的把state输出加回.slx让main.c直接打印 0/1用 Embedded Coderert.tlc生成产品级代码对比 GRT 的差异扩展状态机加投币后超时自动回锁、加子状态/并行状态把最小文件包整理出来放到没有 MATLAB 的嵌入式目标上编译示例代码均在turnstile_proj/目录下包含turnstile_statemachine.m、turnstile_step.m、generate_turnstile_slx.m、main.c、build_main.bat、turnstile.slx、turnstile_grt_rtw/。