Вы находитесь на странице: 1из 2

How to integrate Arduino Libraries with Matlab Simulink?

This manual shows you in details how to integrate Arduino libraries with Matlab
Simulink on the example of AFMotor library.

Requirements:
1. Arduino Mega and Arduino IDE
2. Adafruit Motor Shield
3. AFMotor library
4. DC Motor
5. Matlab (at least 2012b)
6. Arduino Support from Simulink

Step by step configuration:

1. Copy necessary libraries from Arduino folder (AFMotor.h and AFMotor.cpp). You
will find these files in ArduinoDirectory\arduino-1.0.1-windows\arduino-
1.0.1\libraries\AFmotor

2. Paste these files in your project's folder.

3. Open Matlab and Simulink Library. Create new Model.

4. Add S-Function Builder from User-Defined Functions. Open S-Function Builder.

5. Write down a name of new S-Function – sfAFMotor

6. Open Data Properties panel


a. Remove default input x0
b. Add first input DIR - responsible for the direction of DC Motor
c. Add second input PWM - responsible for the speed of DC Motor

7. Open Outputs ports tab


a. Remove default output y0

8. Open Data types attributes tab


a. Change type of both inputs to uint8

9. Open Libraries panel


a. Add this code (compare it with code from Arduino IDE; motor – it is an object
that represents your DC Motor):

#ifndef MATLAB_MEX_FILE
#define ARDUINO 100
#include <Arduino.h>
#include "AFMotor.h"
#include "AFMotor.cpp"
AF_DCMotor motor(1);
#endif
10. Open Outputs panel
a. Add this code (compare it with code from Arduino IDE):

#ifndef MATLAB_MEX_FILE

// turn on motor
motor.setSpeed(PWM[0]);
motor.run(DIR[0]);

#endif

motor.setSpeed(PWM[0]) - responsible for the speed


motor.run(DIR[0]) - controls the direction

Remember that both inputs PWM and DIR are pointers! Therefore you
call theses input using [0].

11. Add necessary Constant sources that will control DC Motor. Remember that both
inputs must be uint8 type!

12. Find file sfAFMotor_wrapper.c in your project’s folder and change its type to .cpp

13. Open it and find function sfAFMotor_Outputs_wrapper. Add extern "C" before the
name of this function. It should look like this:

extern "C" void sfAFMotor_Outputs_wrapper(const uint8_T *DIR,


const uint8_T *PWM)

14. Choose Tools  Run on Target Hardware  Prepare To Run...


a. Open Run on Target Hardware tab, select Arduino Mega 2560 and click Apply
b. Check Enable External mode

15. Select External mode and write inf as Time Simulation


16. Choose Tools  Run on Target Hardware  Run
17. Now the simulation is in External Mode
18. Check different values of sources PWM and DIR. PWM - speed: [0..255], DIR -
direction: 1 - left, 2 - right, 3 - brake, 4 – release

References:

1. http://www.mathworks.se/hardware-support/arduino-simulink.html
2. http://www.minseg.com/arduino-downloads

Вам также может понравиться