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#include"digitalio_arduino.h"extern"C"voiddigitalIOSetup(uint8_T pin, boolean_T mode) {// mode = 0: Input/ /模式= 1:输出if(mode) { pinMode(pin, OUTPUT); }else{ pinMode(pin, INPUT); } }// Write a logic value to pinextern"C"voidwriteDigitalPin(uint8_T pin, boolean_T val) { digitalWrite(pin, val); }// Read a logic value from pinextern"C"boolean_TreadDigitalPin(uint8_T pin) {returndigitalRead(pin); }

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

    Note

    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 asdigitalio_arduino.cppinto the source folder,src

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

    #ifndef_DIGITALIO_ARDUINO_H_#define_DIGITALIO_ARDUINO_H_#include"rtwtypes.h"#ifdef__cplusplusextern"C"{#endifvoiddigitalIOSetup(uint8_T pin, boolean_T mode);voidwriteDigitalPin(uint8_T pin, boolean_T val); boolean_T readDigitalPin(uint8_T pin);#ifdef__cplusplus }#endif#endif//_DIGITALIO_ARDUINO_H_
  5. Save the file asdigitalio_arduino.hinto theincludefolder.

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

Many hardware devices either do not support or recommend using C++ compilers. For example, theSimulink Support Package for Arduino Hardwareuses a C compiler calledavr-gcc。要与C编译器编译和链接C ++功能,您需要添加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.

Thedigitalio_arduino.cppfunction includes anArduino.hfile that defines thepinModeandDigitalwritefunctions. Simulink data types are used forpinandvalvariables. For this reason, thertwtypes.hfile is included indigitalio_arduino.h。You must include this file whenever you reference to Simulink data types. Becausepinis a number between 0 and 53, theuint8_Tdata type is used to represent this variable. Thevalvariable is the value to be written to the digital output pin and is represented byboolean_Tdata type.

In the next section, you will选择系统对象模板and begin the populate the methods.

See Also

||