Main Content

Create a MATLAB Wrapper for Servo Read Library

The MATLAB® add-on wrapper class that defines your library must inherit from matlabshared.addon.LibraryBase (MATLAB Support Package for Arduino Hardware). The matlabshared.addon.LibraryBase class defines several constant properties that you must override in your MATLAB class. The class also contains internal utility functions that enable you to send and retrieve data from the server running on the Arduino® hardware.

  1. Create a MATLAB class ServoRead.m that inherits from matlabshared.addon.LibraryBase.

    classdef ServoRead < matlabshared.addon.LibraryBase 
    ...
    end           
    
  2. Define the command ID for each command that is sent to the server on the board.

    classdef ServoRead < matlabshared.addon.LibraryBase
        properties(Access = private, Constant = true)
            READ_COMMAND = hex2dec('01')
        end    
    ...        
    end
    
  3. Override constant properties in the class to specify the location of source header files.

    classdef ServoRead < matlabshared.addon.LibraryBase
        ...
        properties(Access = protected, Constant = true)
            LibraryName = 'ServoRead/ServoRead'
            DependentLibraries = {}
            LibraryHeaderFiles = {'Servo.h'}
            CppHeaderFile = fullfile(arduinoio.FilePath(mfilename('fullpath')), 'src', 'ServoRead.h')
            CppClassName = 'ServoRead'
        end
        ...
    end

    Define the class constructor, set the methods to call the class constructor, and set the parent properties.

    classdef ServoRead < matlabshared.addon.LibraryBase
       ...
        methods
            function obj = ServoRead(parentObj)
                obj.Parent = parentObj;
            end 
            ...
        end  
    end

    If the device or code does not occupy any arduino pins when in use, leave obj.Pins empty. Always assign the first input argument to obj.Parent.

    The support package auto-detects the class only if you have redefined all the properties. If you do not need a value, leave the field empty.

  4. Define the method to read the data back.

    classdef ServoRead < matlabshared.addon.LibraryBase
        ...
         methods
            ...
            function out = read(obj,pin)
                cmdID = obj.READ_COMMAND;
                inputs = pin;
                output = sendCommand(obj, obj.LibraryName, cmdID, inputs);
                out = char(output);
            end
        end
    end

For help on using MATLAB programming language, see Approaches to Writing MATLAB Programs.

In the next section, you will Register Servo Read Add-On.