Main Content

Tank Control Simulation and Code Generation by Using Ladder Logic

This example shows how to simulate ladder logic and generate code from the ladder tank controller model.

Import, Simulate,and Generate Code

1. Create a folder with write permission and copy the files plcdemo_ladder_tankcontrol_template.slx and TankControl.L5X into that folder.

2. Change the current folder to the newly created folder and rename plcdemo_ladder_tankcontrol_template.slx to plcdemo_ladder_tankcontrol.slx.

3. In MATLAB, run the plcimportladder command. for more information, see plcimportladder command:

plcimportladder('TankControl','TopAOI','TankControl');

4. Open the generated model TankControl_runner.slx and select and copy the TankControl_runner block. Open plcdemo_ladder_tankcontrol.slx, and replace Controller/TankControl_runner with the copied block.

5. To start the simulation, click Run. Open the Tank HMI block and use the Control Command rotary switch to set controller command input.

Set the Control Command Input

  • Set the Control Command switch to the 'Fill' position to fill the tank.

  • Set the Control Command switch to the 'Hold' position to hold the current tank state.

  • Set the Control Command switch to the 'Empty' position to empty the tank.

  • Set the Control Command switch to the 'Stir' position to activate the tank stir state.

The tank enters the Stir state only when the fluid level is full. Otherwise the Stir command has no effect. If the tank is in the Stir state, the Stir indicator lamp is on. Otherwise, it is off. The numeric value of the tank command is:

  • Fill -- 0

  • Hold -- 1

  • Empty -- 2

  • Stir -- 3

The tank animation UI shows the tank status as the simulation runs.

The completed simulink model should resemble:

open_system('plcdemo_ladder_tankcontrol_complete');

6. To generate code for the subsystem, use plcgeneratecode. for more information, see plcgeneratecode:

generatedfiles = plcgeneratecode('plcdemo_ladder_tankcontrol/Controller/TankControl_runner')

7. To generate a testbench, open the ladder tank control testbench model:

open_system('plcdemo_ladder_tankcontrol_tb');