Main Content

Specify Initialization, Output, and Termination Behavior

The setupImpl and stepImpl methods hook the C functions to the System object™. You need to initialize the color sensor only once at model initialization. Hence, the colorSensor_Init function is called in the setupImpl method. This function is declared in the colorSensor.h file. To read the RGB values of the color sensor, the colorSensor_Step function is called in the setupImpl method. Nothing needs to be done at termination. The stepImpl method for the colorSensor system object defines the red, green, and blue output. Follow these steps to update the initial, output, and terminal code sections of the colorSensor System object that you created in Select System Object Template.

  1. In the MATLAB® editor, open the colorSensor.m file.

  2. Update the setupImpl method using the following code.

    methods (Access = protected)
        function setupImpl(obj) %#ok<MANU>
            if coder.target('Rtw')
                coder.cinclude('colorSensor.h');
                coder.ceval('colorSensor_Init');
            else
                % Place simulation setup code here
            end
        end
        ...
    end
    

    The coder.ceval function executes calls to the C wrapper functions in  digitalio_arduino.h function. The second and third arguments of coder.ceval are the Arduino® hardware pin number and value, respectively.

  3. Update the stepImpl method with the following code.

    methods(Access = protected) 
        ... 
        function [red,green,blue] = stepImpl(obj)   %#ok<MANU>
                red=double(0);
                green =double(0);
                blue=double(0);
                if coder.target('Rtw')
                    % Call C-function implementing device output
                    coder.cinclude('colorSensor.h');
                    coder.ceval('colorSensor_Step',coder.wref(red),coder.wref(green),coder.wref(blue));
                else
                    % Place simulation output code here
                    red=0;
                    green=0;
                    blue=0;
                end
        end
        ...
    end

  4. Update the releaseImpl method with the following code.

    methods(Access = protected) 
        ... 
        function releaseImpl(obj) %#ok<MANU>
            if coder.target('Rtw')
                % Call C-function implementing device termination
                % No termination code for Arduino
            else
                % Place simulation termination code here
            end
        end
        ... 
    end 
    
  5. Save the changes to colorSensor.m.

In the next section, you will Update Paths for Source and Header Files.

See Also

| | |