Main Content

Generating C Code from Simulink Ladder

This example shows how to import a simple ladder diagram from an .L5X file (simpleController.L5X) into the Simulink® environment and then generate C code from the imported model. You must have Simulink Coder™ and necessary compilers to generate C code from the model. For more information, see Get Started with Simulink Coder (Simulink Coder).

The .L5X file was created using RSLogix™ 5000 IDE and contains contacts and coils representing switches and motor. This figure shows the ladder structure.

Use the plcladderimport function to import the ladder into Simulink.

[mdlName,mdlLib,busScript] = plcimportladder('simpleController.L5X','OpenModel','On')

The imported model contains a PLC Controller block named simpleController, followed by a Task block named MainTask, and finally a Ladder Diagram Program block named MainProgram. The model imported into Simulink has blocks that implement the functionality of the contacts and coils.

To generate C code for the subsystem simpleController/simpleController, you must first enable the 'FastSim' option for the Simulink Ladder Diagram model.

currentState = plcladderoption('simpleController/simpleController','FastSim','on');

Open the Configuration Parameters dialog box from the model editor by clicking Modeling > Model Settings.

Alternatively, type these commands at the MATLAB® command prompt:

cs = getActiveConfigSet(model);

Ensure that a valid Toolchain is selected.

In the model window, initiate code generation and the build process for the model by using any of the following options:

  • Click the Build Model button.

  • Press Ctrl+B.

  • In the Apps gallery, under Code Generation, click Embedded Coder. On the C Code tab, select Build> Build.

  • Invoke the slbuild command at the MATLAB command line.

See Also

| | | | | |

Related Topics