Alert.png

Notice: This page contains information for the legacy Phidget21 Library.

Phidget21 is out of support. Bugfixes may be considered on a case by case basis.

Phidget21 does not support VINT Phidgets, or new USB Phidgets released after 2020. We maintain a selection of legacy devices for sale that are supported in Phidget21.

We recommend that new projects be developed against the Phidget22 Library.


Click on the 2phidget22.jpg button in the menu bar to go to the Phidget22 version of this page.

Alert.png

Language - MATLAB: Difference between revisions

From Phidgets Legacy Support
 
(131 intermediate revisions by 7 users not shown)
Line 1: Line 1:
[[Category:Language]]
{{OSLang|[[File:Icon-Matlab.png|64x64px]]|MATLAB is a scientific and numerical analysis oriented language, with many graphical libraries and a wide user base.}}
__TOC__
__TOC__


==Support==
==Introduction==


{{LanguageSupport|MATLAB|the non-[[General Phidget Programming#Event Driven Code|event driven]] part of the Phidget API|AdvancedServo, Encoder, InterfaceKit, Servo and Stepper.|any operating system that can run MATLAB code}}
{{LanguageSupport|MATLAB|the non-[[General Phidget Programming#Event Driven Code|event driven]] part of the Phidget API|AdvancedServo, Encoder, InterfaceKit, Servo and Stepper.|any operating system that can run MATLAB code|}}
 
As a result of MATLAB's lack of event support there are some things that cannot be done in MATLAB.  The most prominent of which is sample at the full rate possible for certain boards.  For example, in order to achieve the full 1000 samples/s specified by the analog inputs on an interface kit you need to set the datarate to 1ms.  This will queue up events on the interface kit and send all 8 of them at 8ms intervals.  Since MATLAB cannot use events, it must poll the device for data.  You cannot poll faster than 8ms however and thus MATLAB is limited to 125 samples/s (8ms) rather than 1000 samples/s (1ms).  There are similar effects on other boards with datarates higher than 125 samples/s.
 
If you want to use the events provided by the Phidget library (for, say, collecting sensor data as it changes) then consider using Python as a wrapper.  Python has many libraries which can provide MATLAB-like functionality, such as:
* MatplotLib (plotting functions very similar to MATLAB)
* NumPy (array functions similar to MATLAB)
* SciPy (scientific functions similar to MATLAB libraries)
 
For Windows and Mac users who do not want to manage individual packages, there is [http://www.enthought.com/products/epd.php Enthought] which includes all of the above in addition to wxPython for graphing and other GUI-type programming.  For Linux users, matplotlib may be downloaded from [http://matplotlib.sourceforge.net/ its website], and the other packages are in the Debian package and other package repositories.
 
There is also Pytave, which interfaces with Octave, which can read .m files.  Using the list of libraries above would '''mimic''' MATLAB abilities in Python.  Using Pytave would allow you to open most MATLAB code directly, as long as it works on Octave.  In both of these cases, you would use the [[Language - Python | Python Phidget libraries]], and Python as your main Phidget programming language, not MATLAB.  Python has excellent [http://python.org/ web documentation], and we even have an application guide to use [[Live Data Graphing|Python graphics instead of MATLAB graphics]].
 
We do not support Octave.  Phidgets in MATLAB depend on the <code>calllib()</code> function, which Octave does not have.  For workarounds, see our [[#Common Problems and Solutions|common problems]] section.  Also, the {{Code|calllib}} library uses our C libraries, so programming in MATLAB for Phidgets uses the C API.


==Quick Downloads==
==Quick Downloads==
{{QuickDownloads|MATLAB|
{{APIQuickDownloads|{{SERVER}}/documentation/Phidget21_C_Doc.zip}}
{{ExtraAPIQuickDownloads|{{SERVER}}/documentation/web/cdoc/index.html|HTML Version of}}|
{{ExampleQuickDownloads|{{SERVER}}/downloads/phidget21/examples/c/Matlab.zip MATLAB|}}|
{{WindowsQuickDownloads}}
{{MacQuickDownloads}}
{{LinuxQuickDownloads}}}}


Just need the MATLAB drivers, libraries, and examples?  Here they are. 
==Getting Started with MATLAB==


* [http://www.phidgets.com/downloads/examples/Matlab_2.1.8.20110615.zip MATLAB Sample Code], including the '''<code>phidget21Matlab.h</code>''' library file, needed for any MATLAB project.
If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:
 
{{ExampleCodeReasons}}
MATLAB depends on the C/C++ libraries, and all MATLAB calls essentially call functions in the C library.  So. you need the C/C++ drivers and libraries, and you may also find the C/C++ API reference handy:
*[http://www.phidgets.com/documentation/Phidget21_C_Doc.zip C/C++ API Manual Download] or [http://www.phidgets.com/documentation/web/cdoc/index.html (HTML online version)]
*[[General API]] (more help on functions common to all Phidgets)
*[[Device List | Device Specific APIs]] (more help on functions specific to your Phidget)


Libraries and Drivers which MATLAB depends on:
Instructions are divided up by operating system. Choose:
*[http://www.phidgets.com/downloads/libraries/phidget21-x86_2.1.8.20110615.zip 32 bit Windows (drivers, with libraries)]
*[[#Windows(2000/XP/Vista/7)|Windows 2000 / XP / Vista / 7]]
*[http://www.phidgets.com/downloads/libraries/phidget21-x64_2.1.8.20110615.zip 64 bit Windows (drivers, with libraries)]
*[[#OS X |OS X]]
*[http://www.phidgets.com/downloads/libraries/libphidget_2.1.8.20111028.tar.gz General Linux Libraries] ([[OS - Linux | Linux Library Setup Instructions]])
*[[#Linux | Linux]]
*[http://www.phidgets.com/downloads/libraries/Phidget_2.1.8.20111103.dmg General Mac OSX Libraries] ([[OS - Mac OSX | Mac OSX Library Setup Instructions]])


==Getting Started==
==Windows XP/Vista/7/8==


===Run The Examples===
===Use Our Examples===


One good way to start developing your application is to run and modify existing examples.  You can find the MATLAB example code here:
Start by using and modifying existing examples.  You can find the MATLAB example code here:


*[http://www.phidgets.com/downloads/examples/Matlab_2.1.8.20111028.zip MATLAB Examples]
*[{{SERVER}}/downloads/phidget21/examples/c/Matlab.zip MATLAB Examples]
*[http://www.phidgets.com/documentation/Phidget21_C_Doc.zip C/C++ API, the basis for MATLAB calls]


Copy phidget21Matlab.h from the examples folder to your project directory where you will also put the .m file you want to run.
To run the example code, you'll need to unpack the download and find the source code ''for your specific device'' within the example package.  The file you need will be named something similar to your device name.  Once you have found the file that runs your device, copy that .m source file '''and''' phidget21Matlab.h from the examples folder to your project directory.  Then, run the code within MATLAB as you would any .m file.  For example, from the MATLAB command line, to run the example that reads the analog input at index X from a Phidget Interface Kit:


To run the example code, you'll need to find the source code ''for your specific device'' within the example package.  If your device does not have an example written for it, try the '''HelloWorld.m''' example.  Then, run the code within MATLAB as you would any .m file.  This will allow you to:
<div class="source">
{{ExampleCodeReasons}}
<syntaxhighlight lang=matlab>


===Follow The Examples===
  >>analogin(X)


{{ExamplePseudocodeLogic}}
</syntaxhighlight>
</div>


==Write Your Own Code==
This will allow you to:
{{ExampleCodeReasons}}


===General Library Setup===
If you receive an error regarding that the selected compiler cannot be found.


Before you can use the Phidget, you must include a reference to the library in the code in the main body of code.  
[[File:MATLAB Win Compiler Error.png|link=|alt=Compile cannot be found]]
Copy phidget21Matlab.h to your project directory and then in MATLAB:


You will have to to configure your compiler for MATLAB by entering the following command in the MATLAB command window:
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<font size="3">
<source lang=matlab>
<source lang=matlab>
  mex -setup
</source>
</font>
</div>
[[File:MATLAB Win Mex Setup.png|link=|alt=Mex Setup]]
Next, select {{Code|y}} to view all installed compilers.
[[File:MATLAB Win Choose Your Compiler.png|link=|alt=Choose your Compiler]]
Finally, select the compiler you wish MATLAB to use.
[[File:MATLAB Win Mex Setup Output.png|link=|alt=Mex Setup Output]]
===Write Your Own Code===
You can write your MATLAB code the same way you usually do, whether within a text editor or within MATLAB itself.  However, to use Phidget calls within your code, you must include a reference to the Phidget library in your main body of code, before any Phidget calls:
<div class="source">
<syntaxhighlight lang=matlab>


   function phidgettest(n)
   function phidgettest(n)
    loadlibrary phidget21 phidget21Matlab.h;
      loadphidget21;
       % More code goes here
       % More code goes here
   end
   end


</source>
</syntaxhighlight>
</font>
</div>
 
loadphidget21 is a .m file we have included that will check your OS and reference the proper phidget21Matlab.h file (there is a different one for each OS).  Also, before running your code, remember to '''copy Phidget header files and loadphidget21.m to your project directory'''.
 
==Mac OS==
 
If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:
{{ExampleCodeReasons}}
 
===Use Our Examples===
The phidget21matlab_unix.h file as well as the loadphidget21.m file should be either in the current project directory, or in a MATLAB path (type {{Code|path}} in MATLAB to see the current setup).  If you prefer to use parentheses and quotations for aliasing (to keep your formatting strict), you can read about the various syntax options for the {{Code|loadlibrary}} function on the [http://www.mathworks.com/help/techdoc/ref/loadlibrary.html MathWorks website].
 
To run an example make sure the .m file is in your working directory in MATLAB, and type the name into the MATLAB command window.  For example to run the example that reads the analog input of index X from a Phidget Interface kit:
 
<div class="source">
<syntaxhighlight lang=matlab>
 
  >>analogin(X)
 
</syntaxhighlight>
</div>
 
This will allow you to:
{{ExampleCodeReasons}}
 
===Write Your Own Code===
 
You can write your MATLAB code the same way you usually do, whether within a text editor or within MATLAB itself.  However, to use Phidget calls within your code, you must include a reference to the Phidget library in your main body of code, before any Phidget calls:
 
<div class="source">
<syntaxhighlight lang=matlab>
 
  function phidgettest(n)
      loadphidget21;
      % More code goes here
  end
 
</syntaxhighlight>
</div>
 
loadphidget21 is a .m file we have included that will check your OS and reference the proper phidget21Matlab.h file (there is a different one for each OS).  Also, before running your code, remember to '''copy Phidget header files and loadphidget21.m to your project directory'''.
 
==Linux==
 
If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:
{{ExampleCodeReasons}}
 
===Use our Examples===
Download the and unzip the [{{SERVER}}/downloads/phidget21/examples/c/Matlab.zip Phidget examples for MATLAB].  Put the {{Code|phidget21Matlab.h}} header file that you just compiled into the unzipped example directory.
 
The {{Code|phidget21Matlab.h}} file as well as the {{Code|loadphidget21.m}} should be either in the current project directory, or in a MATLAB path (type {{Code|path}} in MATLAB to see the current setup).  If you prefer to use parentheses and quotations for aliasing (to keep your formatting strict), you can read about the various syntax options for the {{Code|loadlibrary}} function on the [http://www.mathworks.com/help/techdoc/ref/loadlibrary.html MathWorks website].
 
Then just put the {{Code|*.m}} example into your current directory in Matlab, and type the example name.
 
For instance, to use the {{Code|analogin.m}} example to read analog in data from index X of a Phidget Interface Kit, you can just type it on the MATLAB command line:
 
<div class="source">
<syntaxhighlight lang=text>
>> analogin(X)
</syntaxhighlight>
</div>
 
===Write Your Own Code===
 
You can write your MATLAB code the same way you usually do, whether within a text editor or within MATLAB itself.  However, to use Phidget calls within your code, you must include a reference to the Phidget library in your main body of code, before any Phidget calls.
 
And on Linux:
 
<div class="source">
<syntaxhighlight lang=matlab>
 
  function phidgettest(n)
    loadlibrary /usr/lib/libphidget21.so phidget21Matlab.h alias phidget21
      % More code goes here
  end
 
</syntaxhighlight>
</div>
</div>


===Create and Build Your Project===
Also, before running your code, remember to '''copy phidget21Matlab.h to your project directory'''.
 
==Follow The Examples==
 
By following the instructions above, you probably now have a working example and want to understand it better so you can change it to do what you want. This section has resources for you to learn from the examples and write your own.
 
Programming with Phidgets in MATLAB makes extensive use of the '''calllib()''' function to the C/C++ library, so your main reference for coding will be the C/C++ API reference:


Programming with Phidgets makes extensive use of the '''calllib()''' function to the C/C++ library, so the C/C++ API reference will be helpful:
{{UsingAPhidgetInCodeGeneral|although you can only use the logic code type design in MATLAB|[{{SERVER}}/documentation/Phidget21_C_Doc.zip C/C++ API]}}


{{UsingAPhidgetInCodeGeneral|although you can only use the logic code type design in MATLAB|[http://www.phidgets.com/documentation/Phidget21_C_Doc.zip C/C++ API]}}
If you find yourself wanting to use event functions in the API (which are not available in MATLAB), try using Python as described in the [[#Support | support]] section at the top of this page.


Specific calls in MATLAB will differ in syntax from those on the [[General Phidget Programming]] page, but the concepts stay the same.  For example, if we were using a [[Product - 1018 - PhidgetInterfaceKit 8/8/8 | Phidget Interface Kit]] as our device, the general calls would look like this:
===Code Snippets===
 
Specific calls in MATLAB will differ in syntax from those on the [[General Phidget Programming]] page, but the concepts stay the same.   
 
It may help to have the [[General Phidget Programming]] page and this section open at the same time, because they parallel each other and you can refer to the MATLAB syntax.  However, many additional concepts are covered on the General Phidget Programming page on a high level, such as using multiple Phidgets, handling errors, and different styles of programming.
 
For example, if we were using a [{{SERVER}}/products.php?product_id=1018 Phidget Interface Kit] as our device, the general calls would look like this:


====Step One: Initialize and Open====
====Step One: Initialize and Open====


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<div class="source">
<font size="3">
<syntaxhighlight lang=matlab>
<source lang=matlab>


   devicePointer = libpointer('int32Ptr',0);
   phid = libpointer('int32Ptr');
   calllib('phidget21', 'CPhidgetInterfaceKit_create', devicePointer);
   calllib('phidget21', 'CPhidgetInterfaceKit_create', phid);
   device = get(devicePointer, 'Value');
   calllib('phidget21', 'CPhidget_open', phid, -1);


</source>
</syntaxhighlight>
</font>
</div>
</div>


The devicePointer is converted to the handle '''device''' as a handle for the Phidget.  This example is ''specific to the Interface Kit'' because the call CPhidgetInterfaceKit_create is used.  For another device, use the correspondingly named call in the C/C++ API.  
The phid is created as a handle for the Phidget.  This example is ''specific to the Interface Kit'' because the call CPhidgetInterfaceKit_create is used.  For another device, use the correspondingly named call in the C/C++ API.  


The handle '''device''' is then used for all the C function calls where CPhidgetHandle phid is used in the C/C++ API.  Every type of Phidget also inherits functionality from the Phidget base class.
The handle '''phid''' is then used for all the C function calls where CPhidgetHandle phid is used in the C/C++ API.  Every type of Phidget also inherits functionality from the Phidget base class.


Note that open() opens the software object, but not hardware.  So, it is not a guarantee you can use the Phidget immediately.
Note that open() opens the software object, but not hardware.  So, it is not a guarantee you can use the Phidget immediately.


The different types of open can be used with parameters to try and get the first device it can find, open based on its serial number, or even open across the network. The API manual lists all of the available modes that open provides.  
The different types of open can be used with parameters to try and get the first device it can find, open based on its serial number, or even open across the network. The API manual lists all of the available modes that open provides.


====Step Two: Wait for Attachment (plugging in) of the Phidget====  
====Step Two: Wait for Attachment (plugging in) of the Phidget====  
Line 94: Line 221:
To use the Phidget, it must be plugged in (attached).  We can handle this by calling waitForAttachment. This function works for any Phidget. WaitForAttachment will block indefinitely until a connection is made to the Phidget, or an optional timeout is exceeded:
To use the Phidget, it must be plugged in (attached).  We can handle this by calling waitForAttachment. This function works for any Phidget. WaitForAttachment will block indefinitely until a connection is made to the Phidget, or an optional timeout is exceeded:


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<div class="source">
<font size="3">
<syntaxhighlight lang=matlab>
<source lang=matlab>


  calllib('phidget21', 'CPhidget_open', device, -1);
   if calllib('phidget21', 'CPhidget_waitForAttachment', phid, 500) == 0
   if calllib('phidget21', 'CPhidget_waitForAttachment', device, 2500) == 0
     % Insert your code here
     % Insert your code here
   end
   end


</source>
</syntaxhighlight>
</font>
</div>
</div>


Line 111: Line 235:
MATLAB does not support event handling, so all data must be read and sent directly.  
MATLAB does not support event handling, so all data must be read and sent directly.  


The most common thing you might want to do is read data from sensors.  For example, in the code below, we might want to read data from a sensor on the [[Product - 1018 - PhidgetInterfaceKit 8/8/8 | Phidget Interface Kit]].
The most common thing you might want to do is read data from sensors.  For example, in the code below, we might want to read data from a sensor on the [{{SERVER}}/products.php?product_id=1018 Phidget Interface Kit].


Simply use the C API functions such as CPhidgetInterfaceKit_getSensorValue() or CPhidgetInterfaceKit_setOutState() for Interface Kits.  The following reads and displays data from a sensor ten times as quickly as the while loop can execute:  
Simply use the C API functions such as {{Code|CPhidgetInterfaceKit_getSensorValue()}} or {{Code|CPhidgetInterfaceKit_setOutState()}} for Interface Kits.  The following reads and displays data from a sensor ten times as quickly as the while loop can execute:  


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<div class="source">
<font size="3">
<syntaxhighlight lang=matlab>
<source lang=matlab>


   while n<10
   while n<10
     dataPointer = libpointer('int32Ptr',0);
     dataptr = libpointer('int32Ptr', 0);
     calllib('phidget21', 'CPhidgetInterfaceKit_getSensorValue', device, 0, dataPointer)
     if calllib('phidget21', 'CPhidgetInterfaceKit_getSensorValue', phid, n, dataptr) == 0
     disp(get(dataPointer, 'Value'));
     sensorvalue = dataptr.Value;
     n=n+1;
     n=n+1;
   end
   end


</source>
</syntaxhighlight>
</font>
</div>
</div>


====Step Four: Close and Delete====
====Step Four: Close and Delete====


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<div class="source">
<font size="3">
<syntaxhighlight lang=matlab>
<source lang=matlab>


   calllib('phidget21', 'CPhidget_close', ikhandle);
   calllib('phidget21', 'CPhidget_close', phid);
   calllib('phidget21', 'CPhidget_delete', ikhandle);
   calllib('phidget21', 'CPhidget_delete', phid);


</source>
</syntaxhighlight>
</font>
</div>
</div>


At the end of your program, don’t forget to call close to free any locks on the Phidget that the open() call put in place!
At the end of your program, don’t forget to call close to free any locks on the Phidget that the open() call put in place!


The ''complete'' set of functions you have available for all Phidgets can be found in the [http://www.phidgets.com/documentation/Phidget21_C_Doc.zip C/C++ API].  Note, however, MATLAB does not make use of the event functions in the C/C++ API
{{MoreHowTos}}
 
The ''complete'' set of functions you have available for all Phidgets can be found in the [{{SERVER}}/documentation/Phidget21_C_Doc.zip C/C++ API].  Note, however, MATLAB does not make use of the event functions in the C/C++ API. You can also find more description on any device-specific function in the Device API page for your specific Phidget, which can be found in its [[:Category:UserGuide|user guide]].
 
==Using the MATLAB Engine from a C program==
It is possible to use events while still having a MATLAB like environment by using the MATLAB engine library in C.  In MathWorks' own words: "The MATLAB® engine library contains routines that allow you to call MATLAB software from your own programs, thereby employing MATLAB as a computation engine..."[http://www.mathworks.com/help/matlab/matlab_external/using-matlab-engine.html]  This allows you to write a C program that uses normal C syntax structure but calls MATLAB to take care of the complex math algorithms that you do not want to implement in C.  To get the MATLAB engine set up just follow these steps (note that these steps are for a Windows system with Visual Studio installed, you can download a free version of VS from Microsoft under the Express name)
 
*Create a new Visual Studio empty project.
*Add a new CPP source file be sure to include the following header files:
**<nowiki>#include <windows.h></nowiki>
**<nowiki>#include <stdlib.h></nowiki>
**<nowiki>#include <stdio.h></nowiki>
**<nowiki>#include <string.h></nowiki>
**<nowiki>#include <engine.h></nowiki>
*Under Project Properties:
**Add <code>/<Matlab install directory>/extern/include</code> to "Additional include directories"
**Make sure that precompiled headers are disabled
**In the "Linker" section add <code>/<Matlab install directory>/extern/lib/win32(or 64)/microsoft</code> to "Additional library dependencies".
**Under "Linker->Input" add <code>libmx.lib libmat.lib libeng.lib</code> to "Additional dependendcies". 
*Now open a cmd terminal and navigate to <code>/<Matlab install directory>/bin/win32(or 64)</code> and enter in the following command:
**<code>matlab /regserver</code>
*Close the MATLAB window that opens. 
*Next, make sure that <code>/<Matlab install directory>/bin/win32(or 64)</code> is included in your PATH environment variable. 
*Finally, restart Visual Studio.  Your project should now be configured to be able to use the MATLAB engine.


If you are looking for more information about a particular function, we provide that as well. You can find more description on any function either in:
Here is a modified version of Spatial-simple.c which uses the MATLAB engine to pass the spatial data through a high-pass filter to monitor for sudden changes in acceleration such as if a car were running off road or a structure was experiencing unexpected vibrations (an earthquake say):
# Our [[General API|API Overview]] which describes the set of calls common to all Phidgets, or
*[{{SERVER}}/docs21/images/e/ef/Main.cpp Main]
# The [[Device List|Device API]] page for calls available only on your specific Phidget.
*[{{SERVER}}/docs21/images/e/ee/Spatialfilter.h Header]


==Common Problems and Solutions/Workarounds==
The full API and documentation package for the MATLAB engine can be found on MathWorks' website.
{{ProblemSolution|Octave Problem|The function calls loadlibrary() and callib() are not supported in Octave}}
 
A number of things can be tweaked in this example, such as the filter parameters and type of filter used, the threshold at which we take note of the vibrations etc...  If we look at the unaltered data vs the filtered data we can see that the filtering operation was a success:
 
[[File:Filtereddata.png|800px|center|link=]]
 
==Common Problems and Solutions==
 
===Octave Problem: The function calls loadlibrary() and callib() are not supported in Octave===


Likely Fix: As use of Phidgets in MATLAB requires these calls, the best is probably to choose a programming language that is not MATLAB.  You can choose [[Software Overview#Language Support|from many languages]] that we support.
Likely Fix: As use of Phidgets in MATLAB requires these calls, the best is probably to choose a programming language that is not MATLAB.  You can choose [[Software Overview#Language Support|from many languages]] that we support.
Line 160: Line 310:
* If you are using a version of Octave that Pytave does not support, write your program in Python as above.  Then, you can try reading your matlab code through R, and using RPy to interface with Python.
* If you are using a version of Octave that Pytave does not support, write your program in Python as above.  Then, you can try reading your matlab code through R, and using RPy to interface with Python.
* External foreign linking libraries (Swig, FFCall) might be made to work...
* External foreign linking libraries (Swig, FFCall) might be made to work...
===All Operating Systems: You get a warning "The library class 'libphidget21' already exists.  Use a classname alias."===
Note that the {{Code|phidget21}} library is not unloaded at the end of our example {{Code|.m}} files.  This is because rapidly unloading the library just after linking it can cause problems in short programs.
So, when you run the program again within the same MATLAB session, you will get this warning. Your code will still work, it is just that running the same code again loads the library again without closing it first.
===OS X: The examples do not run with Rosetta under OS X.===
The example programs uses the MATLAB {{Code|timer()}} call, which relies on the Java Virtual Machine. Since Rosetta does not support Java, the examples will not operate as expected.
===There are no compilers listed under the mex -setup menu===
64-bit versions of Matlab do not have a C compiler included with them.  You will need to use another compiler such as the Visual Studio compiler.  If you do not have Visual Studio then you can install a free version from Microsoft's website which has a compiler with it or you download another free C compiler of which there are many.

Latest revision as of 21:08, 6 June 2017

Icon-Matlab.png MATLAB is a scientific and numerical analysis oriented language, with many graphical libraries and a wide user base.

Introduction

If this is your first time working with a Phidget, we suggest starting with the Getting Started page for your specific device. This can be found in the user guide for your device. That page will walk you through installing drivers and libraries for your operating system, and will then bring you back here to use MATLAB specifically.

MATLAB is capable of using the non-event driven part of the Phidget API. We also provide example code in MATLAB for AdvancedServo, Encoder, InterfaceKit, Servo and Stepper.

MATLAB can be developed with any operating system that can run MATLAB code.

You can compare MATLAB with our other supported languages.

As a result of MATLAB's lack of event support there are some things that cannot be done in MATLAB. The most prominent of which is sample at the full rate possible for certain boards. For example, in order to achieve the full 1000 samples/s specified by the analog inputs on an interface kit you need to set the datarate to 1ms. This will queue up events on the interface kit and send all 8 of them at 8ms intervals. Since MATLAB cannot use events, it must poll the device for data. You cannot poll faster than 8ms however and thus MATLAB is limited to 125 samples/s (8ms) rather than 1000 samples/s (1ms). There are similar effects on other boards with datarates higher than 125 samples/s.

If you want to use the events provided by the Phidget library (for, say, collecting sensor data as it changes) then consider using Python as a wrapper. Python has many libraries which can provide MATLAB-like functionality, such as:

  • MatplotLib (plotting functions very similar to MATLAB)
  • NumPy (array functions similar to MATLAB)
  • SciPy (scientific functions similar to MATLAB libraries)

For Windows and Mac users who do not want to manage individual packages, there is Enthought which includes all of the above in addition to wxPython for graphing and other GUI-type programming. For Linux users, matplotlib may be downloaded from its website, and the other packages are in the Debian package and other package repositories.

There is also Pytave, which interfaces with Octave, which can read .m files. Using the list of libraries above would mimic MATLAB abilities in Python. Using Pytave would allow you to open most MATLAB code directly, as long as it works on Octave. In both of these cases, you would use the Python Phidget libraries, and Python as your main Phidget programming language, not MATLAB. Python has excellent web documentation, and we even have an application guide to use Python graphics instead of MATLAB graphics.

We do not support Octave. Phidgets in MATLAB depend on the calllib() function, which Octave does not have. For workarounds, see our common problems section. Also, the calllib library uses our C libraries, so programming in MATLAB for Phidgets uses the C API.

Quick Downloads

Just need the MATLAB documentation, drivers, libraries, and examples? Here they are:

Documentation

Example Code

Libraries and Drivers

Getting Started with MATLAB

If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:

  • Make sure your libraries are properly linked
  • Go from source code to a test application as quickly as possible
  • Ensure your Phidget is hooked up properly

Instructions are divided up by operating system. Choose:

Windows XP/Vista/7/8

Use Our Examples

Start by using and modifying existing examples. You can find the MATLAB example code here:

To run the example code, you'll need to unpack the download and find the source code for your specific device within the example package. The file you need will be named something similar to your device name. Once you have found the file that runs your device, copy that .m source file and phidget21Matlab.h from the examples folder to your project directory. Then, run the code within MATLAB as you would any .m file. For example, from the MATLAB command line, to run the example that reads the analog input at index X from a Phidget Interface Kit:

  >>analogin(X)

This will allow you to:

  • Make sure your libraries are properly linked
  • Go from source code to a test application as quickly as possible
  • Ensure your Phidget is hooked up properly

If you receive an error regarding that the selected compiler cannot be found.

Compile cannot be found

You will have to to configure your compiler for MATLAB by entering the following command in the MATLAB command window:

  mex -setup

Mex Setup

Next, select y to view all installed compilers.

Choose your Compiler

Finally, select the compiler you wish MATLAB to use.

Mex Setup Output

Write Your Own Code

You can write your MATLAB code the same way you usually do, whether within a text editor or within MATLAB itself. However, to use Phidget calls within your code, you must include a reference to the Phidget library in your main body of code, before any Phidget calls:

  function phidgettest(n)
      loadphidget21;
      % More code goes here
  end

loadphidget21 is a .m file we have included that will check your OS and reference the proper phidget21Matlab.h file (there is a different one for each OS). Also, before running your code, remember to copy Phidget header files and loadphidget21.m to your project directory.

Mac OS

If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:

  • Make sure your libraries are properly linked
  • Go from source code to a test application as quickly as possible
  • Ensure your Phidget is hooked up properly

Use Our Examples

The phidget21matlab_unix.h file as well as the loadphidget21.m file should be either in the current project directory, or in a MATLAB path (type path in MATLAB to see the current setup). If you prefer to use parentheses and quotations for aliasing (to keep your formatting strict), you can read about the various syntax options for the loadlibrary function on the MathWorks website.

To run an example make sure the .m file is in your working directory in MATLAB, and type the name into the MATLAB command window. For example to run the example that reads the analog input of index X from a Phidget Interface kit:

  >>analogin(X)

This will allow you to:

  • Make sure your libraries are properly linked
  • Go from source code to a test application as quickly as possible
  • Ensure your Phidget is hooked up properly

Write Your Own Code

You can write your MATLAB code the same way you usually do, whether within a text editor or within MATLAB itself. However, to use Phidget calls within your code, you must include a reference to the Phidget library in your main body of code, before any Phidget calls:

  function phidgettest(n)
      loadphidget21;
      % More code goes here
  end

loadphidget21 is a .m file we have included that will check your OS and reference the proper phidget21Matlab.h file (there is a different one for each OS). Also, before running your code, remember to copy Phidget header files and loadphidget21.m to your project directory.

Linux

If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:

  • Make sure your libraries are properly linked
  • Go from source code to a test application as quickly as possible
  • Ensure your Phidget is hooked up properly

Use our Examples

Download the and unzip the Phidget examples for MATLAB. Put the phidget21Matlab.h header file that you just compiled into the unzipped example directory.

The phidget21Matlab.h file as well as the loadphidget21.m should be either in the current project directory, or in a MATLAB path (type path in MATLAB to see the current setup). If you prefer to use parentheses and quotations for aliasing (to keep your formatting strict), you can read about the various syntax options for the loadlibrary function on the MathWorks website.

Then just put the *.m example into your current directory in Matlab, and type the example name.

For instance, to use the analogin.m example to read analog in data from index X of a Phidget Interface Kit, you can just type it on the MATLAB command line:

>> analogin(X)

Write Your Own Code

You can write your MATLAB code the same way you usually do, whether within a text editor or within MATLAB itself. However, to use Phidget calls within your code, you must include a reference to the Phidget library in your main body of code, before any Phidget calls.

And on Linux:

  function phidgettest(n)
     loadlibrary /usr/lib/libphidget21.so phidget21Matlab.h alias phidget21
      % More code goes here
  end

Also, before running your code, remember to copy phidget21Matlab.h to your project directory.

Follow The Examples

By following the instructions above, you probably now have a working example and want to understand it better so you can change it to do what you want. This section has resources for you to learn from the examples and write your own.

Programming with Phidgets in MATLAB makes extensive use of the calllib() function to the C/C++ library, so your main reference for coding will be the C/C++ API reference:

  • C/C++ API (This is the complete set of functions you have available for all Phidgets)
  • Device Specific APIs - The one for your Phidget can be found in its user guide.

To learn the details behind opening, configuring, using, and closing your Phidget, try the General Phidget Programming page. That page also describes using the Phidget in an event-driven manner and in a traditional manner, although you can only use the logic code type design in MATLAB.

If you find yourself wanting to use event functions in the API (which are not available in MATLAB), try using Python as described in the support section at the top of this page.

Code Snippets

Specific calls in MATLAB will differ in syntax from those on the General Phidget Programming page, but the concepts stay the same.

It may help to have the General Phidget Programming page and this section open at the same time, because they parallel each other and you can refer to the MATLAB syntax. However, many additional concepts are covered on the General Phidget Programming page on a high level, such as using multiple Phidgets, handling errors, and different styles of programming.

For example, if we were using a Phidget Interface Kit as our device, the general calls would look like this:

Step One: Initialize and Open

  phid = libpointer('int32Ptr');
  calllib('phidget21', 'CPhidgetInterfaceKit_create', phid);
  calllib('phidget21', 'CPhidget_open', phid, -1);

The phid is created as a handle for the Phidget. This example is specific to the Interface Kit because the call CPhidgetInterfaceKit_create is used. For another device, use the correspondingly named call in the C/C++ API.

The handle phid is then used for all the C function calls where CPhidgetHandle phid is used in the C/C++ API. Every type of Phidget also inherits functionality from the Phidget base class.

Note that open() opens the software object, but not hardware. So, it is not a guarantee you can use the Phidget immediately.

The different types of open can be used with parameters to try and get the first device it can find, open based on its serial number, or even open across the network. The API manual lists all of the available modes that open provides.

Step Two: Wait for Attachment (plugging in) of the Phidget

To use the Phidget, it must be plugged in (attached). We can handle this by calling waitForAttachment. This function works for any Phidget. WaitForAttachment will block indefinitely until a connection is made to the Phidget, or an optional timeout is exceeded:

  if calllib('phidget21', 'CPhidget_waitForAttachment', phid, 500) == 0
     % Insert your code here
  end

Step Three: Do Things with the Phidget

MATLAB does not support event handling, so all data must be read and sent directly.

The most common thing you might want to do is read data from sensors. For example, in the code below, we might want to read data from a sensor on the Phidget Interface Kit.

Simply use the C API functions such as CPhidgetInterfaceKit_getSensorValue() or CPhidgetInterfaceKit_setOutState() for Interface Kits. The following reads and displays data from a sensor ten times as quickly as the while loop can execute:

  while n<10
    dataptr = libpointer('int32Ptr', 0);
    if calllib('phidget21', 'CPhidgetInterfaceKit_getSensorValue', phid, n, dataptr) == 0
    sensorvalue = dataptr.Value;
    n=n+1;
  end

Step Four: Close and Delete

  calllib('phidget21', 'CPhidget_close', phid);
  calllib('phidget21', 'CPhidget_delete', phid);

At the end of your program, don’t forget to call close to free any locks on the Phidget that the open() call put in place!

More How-To's

The General Phidget Programming page gives more information about:

The complete set of functions you have available for all Phidgets can be found in the C/C++ API. Note, however, MATLAB does not make use of the event functions in the C/C++ API. You can also find more description on any device-specific function in the Device API page for your specific Phidget, which can be found in its user guide.

Using the MATLAB Engine from a C program

It is possible to use events while still having a MATLAB like environment by using the MATLAB engine library in C. In MathWorks' own words: "The MATLAB® engine library contains routines that allow you to call MATLAB software from your own programs, thereby employing MATLAB as a computation engine..."[1] This allows you to write a C program that uses normal C syntax structure but calls MATLAB to take care of the complex math algorithms that you do not want to implement in C. To get the MATLAB engine set up just follow these steps (note that these steps are for a Windows system with Visual Studio installed, you can download a free version of VS from Microsoft under the Express name)

  • Create a new Visual Studio empty project.
  • Add a new CPP source file be sure to include the following header files:
    • #include <windows.h>
    • #include <stdlib.h>
    • #include <stdio.h>
    • #include <string.h>
    • #include <engine.h>
  • Under Project Properties:
    • Add /<Matlab install directory>/extern/include to "Additional include directories"
    • Make sure that precompiled headers are disabled
    • In the "Linker" section add /<Matlab install directory>/extern/lib/win32(or 64)/microsoft to "Additional library dependencies".
    • Under "Linker->Input" add libmx.lib libmat.lib libeng.lib to "Additional dependendcies".
  • Now open a cmd terminal and navigate to /<Matlab install directory>/bin/win32(or 64) and enter in the following command:
    • matlab /regserver
  • Close the MATLAB window that opens.
  • Next, make sure that /<Matlab install directory>/bin/win32(or 64) is included in your PATH environment variable.
  • Finally, restart Visual Studio. Your project should now be configured to be able to use the MATLAB engine.

Here is a modified version of Spatial-simple.c which uses the MATLAB engine to pass the spatial data through a high-pass filter to monitor for sudden changes in acceleration such as if a car were running off road or a structure was experiencing unexpected vibrations (an earthquake say):

The full API and documentation package for the MATLAB engine can be found on MathWorks' website.

A number of things can be tweaked in this example, such as the filter parameters and type of filter used, the threshold at which we take note of the vibrations etc... If we look at the unaltered data vs the filtered data we can see that the filtering operation was a success:

Filtereddata.png

Common Problems and Solutions

Octave Problem: The function calls loadlibrary() and callib() are not supported in Octave

Likely Fix: As use of Phidgets in MATLAB requires these calls, the best is probably to choose a programming language that is not MATLAB. You can choose from many languages that we support.

However, this may not be possible if, for example, you already have a lot of external code written in MATLAB that you would like to interface your Phidget with. Here are a few suggestions to help you find a way to use your existing MATLAB code:

  • Write your overall program in Python. Python natively controls Phidgets, and you can use Pytave to interface between the Python Phidget code and your Octave code.
  • If you are using a version of Octave that Pytave does not support, write your program in Python as above. Then, you can try reading your matlab code through R, and using RPy to interface with Python.
  • External foreign linking libraries (Swig, FFCall) might be made to work...

All Operating Systems: You get a warning "The library class 'libphidget21' already exists. Use a classname alias."

Note that the phidget21 library is not unloaded at the end of our example .m files. This is because rapidly unloading the library just after linking it can cause problems in short programs.

So, when you run the program again within the same MATLAB session, you will get this warning. Your code will still work, it is just that running the same code again loads the library again without closing it first.

OS X: The examples do not run with Rosetta under OS X.

The example programs uses the MATLAB timer() call, which relies on the Java Virtual Machine. Since Rosetta does not support Java, the examples will not operate as expected.

There are no compilers listed under the mex -setup menu

64-bit versions of Matlab do not have a C compiler included with them. You will need to use another compiler such as the Visual Studio compiler. If you do not have Visual Studio then you can install a free version from Microsoft's website which has a compiler with it or you download another free C compiler of which there are many.