Main Content

Create a C++ Code for Servo Read Library

For this example, create a C++ header file named ServoRead.h, and save it in the +arduinoioaddons/+ServoRead/src folder. This file wraps methods to expose to the Arduino® library.

  1. Include header files, including Servo.h and any other third-party header file that the add-on library depends on.

    #include "Servo.h"
    
  2. Create an add-on class that inherits from the LibraryBase class, which defines all the necessary interfaces.

  3. In the constructor, define the library name, and register the library to the server.

    class ServoRead : public LibraryBase
    {
        public:
            Servo myServo;
        public:
            ServoRead(MWArduinoClass& a)
            {
                libName = "ServoRead/ServoRead";
                a.registerLibrary(this);
            }
    ...
    };

    The custom class and library names must have this format:

    shield(vendor)/device(library)
  4. Determine the command calls to issue from MATLAB®.

  5. Override the command handler, and create a switch case for each command that the add-on executes on the Arduino device:

    class ServoRead : public LibraryBase
    {
    ...
    public:
            void commandHandler(byte cmdID, byte* inputs, unsigned int payload_size)
            {
                switch (cmdID){
                    case 0x01:{ 
                        byte val;
                        if(!myServo.attached())
                            myServo.attach(inputs[0]);
                        val = myServo.read();
                        sendResponseMsg(cmdID, &val, 1);
                        break;
                    }
                    default:{
                        // Do nothing
                    }
                }
            }
    };

    The command IDs must match up with the operations that you add to the MATLAB add-on library. For more information, see Command Handler.

  6. (Optional) Use debugPrint to pass additional messages from the Arduino device to the MATLAB command line.

In the next section, you will Create a MATLAB Wrapper for Servo Read Library.