Main Content

Write Hardware Specific C/C++ Code

In most cases, to integrate the device driver code into the Simulink® block, you need to write a wrapper function around the API provided by the hardware vendor. Follow these steps to develop the C/C++ code required to implement the color picker functionality.

  1. Create a new empty file in the MATLAB® editor.

  2. Copy the following C++ code into the file.

    #include "colorSensor.h" 
    #include "Adafruit_TCS34725.h"   
    /*Create object of the sensor with integration time of 50ms and gain of 4x*/
    Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_4X);    
    uint8_t init_f;
    extern "C" void colorSensor_Init(void)
        init_f = tcs.begin();   /* Initialize the sensor and store the status in init_f */ 
    extern "C" void colorSensor_Step(float *r,float *g,float *b) 
        if(init_f)              /* If sensor is initialized properly, then read the sensor else return 0 */
            tcs.getRGB(r, g, b); 
            *r = 0; 
            *g = 0; 
            *b = 0; 
    extern "C" void colorSensor_Terminate() 

    This code wraps the color sensor library API to read the RGB value from the TCS34725 color sensor.


    Although the C++ code shown here is specific to the Arduino hardware, the same principle can be extended to any hardware-specific C/C++ API.

  3. Save the file as colorSensor.cpp in the src folder.

  4. Create an empty header file and copy the following C++ code into the file.

    #ifndef _COLORSENSOR_H_
    #define _COLORSENSOR_H_
    #ifdef __cplusplus
    extern "C" {
        #if (defined(MATLAB_MEX_FILE) || defined(RSIM_PARAMETER_LOADING) ||  defined(RSIM_WITH_SL_SOLVER))
            /* This will be run in Rapid Accelerator Mode */
            #define colorSensor_Init()         (0)
            #define colorSensor_Step(a,b,c)    (0)
            #define colorSensor_Terminate()    (0)
            void colorSensor_Init(void);
            void colorSensor_Step(float*,float*,float*);
            void colorSensor_Terminate(void);
    #ifdef __cplusplus
  5. Save the file as colorSensor.h in the include folder.

    This header file defines the C prototypes of the functions implemented in the C++ file, colorSensor.cpp.

Many hardware devices either do not support or recommend using C++ compilers. For example, the Simulink Support Package for Arduino® Hardware uses a C compiler called avr-gcc. To compile and link C++ functions with a C compiler, you need to add the extern "C" identifier in each function declaration. This identifier tells the compiler not to mangle function names so that they can be used with the C linker.

In the next section, you will Select System Object Template and populate the methods.