Main Content

Write the Hardware Specific C/C++ Code

In most cases, to integrate device driver code into a 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 digital read and write functionality:

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

  2. Copy the following C code into the file.

    #include <wiringPi.h>
    #include "digitalio_raspi.h" 
    static int initialized = false;
    void digitalIOSetup(uint8_T pin, boolean_T mode)
       // Perform one-time wiringPi initialization
       if (!initialized) { 
          initialized = 1;
       // mode = 0: Input 
       // mode = 1: Output
       if (mode) { 
          pinMode(pin, OUTPUT); 
          pinMode(pin, INPUT); 
    // Write a logic value to pin 
    void writeDigitalPin(uint8_T pin, boolean_T val) 
       digitalWrite(pin, val); 
    // Read a logic value from pin 
    boolean_T readDigitalPin(uint8_T pin) 
       return ((boolean_T)digitalRead(pin)); 

    This code wraps the Raspberry Pi® C API to write to a digital I/O pin on the Raspberry Pi hardware board.


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

  3. Save the file as digitalio_raspi.c into the source folder, src.

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

    #ifndef _DIGITALIO_RASPI_H_
    #define _DIGITALIO_RASPI_H_
    #include "rtwtypes.h"
    void digitalIOSetup(uint8_T pin, boolean_T mode);
    void writeDigitalPin(uint8_T pin, boolean_T val);
    boolean_T readDigitalPin(uint8_T pin);
    #endif //_DIGITALIO_RASPI_H_
  5. Save the file as digitalio_raspi.h into the include folder.

    This header file defines the C prototypes of the functions implemented in the C file, digitalio_raspi.c.

The digitalio_raspi.c function includes a wiringPi.h file that defines the pinMode and digitalRead functions. Simulink data types are used for pin and val variables. For this reason, the rtwtypes.h file is included in digitalio_raspi.h. You must include this file whenever you reference to Simulink data types. Because pin is a number between 0 and 53 we use the uint8_T data type to represent this variable.

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

See Also

| |