Main Content

Use Enumerations to Control an LED Display

Enumerations in a MATLAB Function Block

这个例子展示了如何exch MATLAB函数块ange enumerated data with other Simulink® blocks. The model uses enumerations to represent the modes of a device that controls the colors of an LED display. The MATLAB Function block receives an enumerated input signal that represents the mode. The enumerated output signal represents the color that the LED displays.

In this model, theStepblock provides the source of the on/off signal. This block outputs an initial value of 0 (off) and, after 10 seconds, steps up to a value of 1 (on). A pair of Data Type Conversion blocks convert this signal, first from typedoubleto typeint32, and then fromint32to the enumerated typeswitchmode. The parameters in the second Data Type Conversion block have these settings:

  • Output minimum:[]

  • Output maximum:[]

  • Output data type:Enum:switchmode

The MATLAB Function blockcheckStateevaluates the enumerated inputstateto determine the value of the enumerated outputledval.stateinherits its enumerated typeswitchmodefrom the incoming Simulink signal, whileledvalhas the typeEnum:led. Finally, a Display block displays the value ofledval.

Enumeration Class Definitions

Theswitchmodeenumeration represents the allowed modes for the input to thecheckstateblock.

classdefswitchmode < Simulink.IntEnumTypeenumerationOFF(0) ON(1)endend

Theledenumeration represents the colors that thecheckstateblock can output.

classdefled < Simulink.IntEnumTypeenumerationGREEN(1), RED(8)endend
Both enumeration classes inherit from the built-in typeSimulink.IntEnumTypeand reside on the MATLAB®path.

MATLAB FunctionBlock Function

The functioncheckStateuses enumerations to activate an LED display, based on the state of a device. It lights a green LED display to indicate the ON state. It lights a red LED display to indicate the OFF state.

functionledval = checkState(state)%#codegenifstate == switchmode.ON ledval = led.GREEN;elseledval = led.RED;end

Simulation

When you simulate the model, theDisplayblock displays the state of the LED display. If you simulate the model for less than 10 seconds, the state is off. TheDisplayblock displaysRED. If you simulate the model for more than 10 seconds, the state is on. TheDisplayblock displaysGREEN.

相关话题