Phidget Programming Basics: Difference between revisions

From Phidgets Support
No edit summary
 
(13 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Category:Programming]]
[[Category:Programming]]{{Recommended_Flow_Links|{{Flow Page Number|{{PAGENAME}} }} }}
__TOC__
<div class="ProgrammingBasicsIntro">
{|
|
==Welcome!==
Welcome to the Phidget Programming Basics guide!


It is important to understand what a Phidget is, and how the hardware and software relate to one another before writing software using the {{Phidget22API}}.  Please refer to [[What is a Phidget?]] for an introduction.
By following this guide, you will learn the important concepts behind how Phidgets are used in any software application.


==Before You Start==
We recommend having a few things set up before starting this guide on how to program with Phidgets:


The Phidget software library matches a Phidget device channel with a software channel that is created by a user.
'''1.''' You will need the Phidget22 libraries installed on your machine. To get the Phidgets libraries for your operating system, check out our page on [[Operating System Support]].
Software channels are each of a class, where that class defines a set of methods, properties, events and errors. Phidget devices are aware of the channel classes, and expose access to features of the device through the class interface.


To use a Phidget, you'll want to:
'''2.''' We recommend knowing which programming language you intend to use before starting this guide, so you can follow along. We provide a list of [[Programming Resources|programming languages]] we support, and instructions of how to set them up for use with Phidgets.
# '''[[#Creating a Channel|Create]]''' an instance of the channel class that provides access to the device you want to control.
# '''[[#Opening a Channel|Open]]''' the channel.
# Detect when the channel is '''[[#Attaching a Channel|attached]]''' to the Phidget.
# Use '''[[#Do Things with a Channel|methods and properties]]''' of the attached channel.
# '''[[#Close a Channel|Close]]''' the channel.


Small code snippets are provided for each step in the sections below. [[Language - Java|Java]] and [[Language - C|C]] were selected because Java is a high-level language and C is a low level language.  The best reference to the ''features'' each channel class is the {{Phidget22API}} for your specific language.  This page is intended to be a high-level introduction.
'''3.''' This guide will work best if you have a Phidget to work with, and have already tried it out using the '''Phidget22 Control Panel'''. If you haven't yet, navigate to the [[Product_Page_Links|product page]] for your Phidget and follow the instructions in the '''User Guide''' tab to try it out.
|
{|class="ProgrammingBasicsTOC" style="color: black; width: 100%; border-style: solid; border-width: 2px;" cellpadding="10"
|<font size=5>'''Table of Contents'''</font>
<font size=4>
#'''[[{{Flow Page Number Name| 1 }}]]'''
#'''[[{{Flow Page Number Name| 2 }}]]'''
#'''[[{{Flow Page Number Name| 3 }}]]'''
#'''[[{{Flow Page Number Name| 4 }}]]'''
#'''[[{{Flow Page Number Name| 5 }}]]'''
#'''[[{{Flow Page Number Name| 6 }}]]'''
#'''[[{{Flow Page Number Name| 7 }}]]'''
#'''[[{{Flow Page Number Name| 8 }}]]'''
#'''[[{{Flow Page Number Name| 9 }}]]'''
#'''[[{{Flow Page Number Name| 10 }}]]'''
#'''[[{{Flow Page Number Name| 11 }}]]'''
#'''[[{{Flow Page Number Name| 12 }}]]'''
#'''[[{{Flow Page Number Name| 13 }}]]'''
#'''[[{{Flow Page Number Name| 14 }}]]'''
#'''[[{{Flow Page Number Name| 15 }}]]'''
#'''[[{{Flow Page Number Name| 16 }}]]'''
</font>
|}
|}


== Creating a Channel ==
{|class="ProgrammingBasicsTOCsmall" style="color: black; width: 100%; border-style: solid; border-width: 2px;" cellpadding="10"
 
|<font size=5>'''Table of Contents'''</font>
A Phidget device exposes one or more device channels where each channel is an interface to a feature of the hardware.  A channel class defines an interface to control and query a channel of the Phidget device.  For example, a 1018 - Phidget InterfaceKit device includes support
<font size=4>
for digital input and digital out, and therefore exports <code>DigitalInput</code> and <code>DigitalOutput</code> channels.
#'''[[{{Flow Page Number Name| 1 }}]]'''
 
#'''[[{{Flow Page Number Name| 2 }}]]'''
Phidget devices are controlled by creating an instance of a Phidget channel class.  Each channel class has a function that allows you to '''create''' an instance, and a function to later '''delete''' the instance.
#'''[[{{Flow Page Number Name| 3 }}]]'''
 
#'''[[{{Flow Page Number Name| 4 }}]]'''
For example, in Java:
#'''[[{{Flow Page Number Name| 5 }}]]'''
 
#'''[[{{Flow Page Number Name| 6 }}]]'''
<syntaxhighlight lang=java>
#'''[[{{Flow Page Number Name| 7 }}]]'''
// Create a new Accelerometer channel
#'''[[{{Flow Page Number Name| 8 }}]]'''
Accelerometer accel = new Accelerometer();
#'''[[{{Flow Page Number Name| 9 }}]]'''
</syntaxhighlight>
#'''[[{{Flow Page Number Name| 10 }}]]'''
<syntaxhighlight lang=java>
#'''[[{{Flow Page Number Name| 11 }}]]'''
// Create a new RFID channel
#'''[[{{Flow Page Number Name| 12 }}]]'''
RFID rfid = new RFID();
#'''[[{{Flow Page Number Name| 13 }}]]'''
</syntaxhighlight>
#'''[[{{Flow Page Number Name| 14 }}]]'''
 
#'''[[{{Flow Page Number Name| 15 }}]]'''
Or in C:
#'''[[{{Flow Page Number Name| 16 }}]]'''
 
</font>
<syntaxhighlight lang=c>
|}
// Create a new Accelerometer channel
</div>
PhidgetAccelerometerHandle accel;
{{Flow_Navigation_Buttons|{{Flow Page Number|{{PAGENAME}} }} }}
PhidgetAccelerometer_create(&accel);
</syntaxhighlight>
<syntaxhighlight lang=c>
// Create a new RFID channel
PhidgetRFIDHandle rfid;
PhidgetRFID_create(&rfid);
</syntaxhighlight>
 
A channel class will have properties and methods specific to the feature they belong to. For example, the <code>VoltageInput</code> class has a <code>Voltage</code> property that lets you access the current voltage measured by the device, the <code>Accelerometer</code> class has properties to set the sensitivity on each axis and the <code>RFID</code> has a method that writes to a writable RFID tag.
 
== Opening a Channel ==
 
After you have created a [[#Creating a Channel| channel instance]], you can call the <code>open()</code> method to begin the process of matching the channel to a Phidget device channel.
 
For example, with the <code>Accelerometer</code> channel in Java:
 
<syntaxhighlight lang=java>
accel.open();
</syntaxhighlight>
 
Or in C:
 
<syntaxhighlight lang=c>
Phidget_open((PhidgetHandle) accel);
</syntaxhighlight>
 
To see how to use <code>open()</code> in other languages, please refer to the {{Phidget22API}}.
 
The <code>open()</code> function begins the process of matching the channel handle you created to a channel of a Phidget device, and does not actually ''open'' the Phidget itself.  An open channel may match a new Phidget device when it is plugged in if that channel has not already found a Phidget device channel that meets its criteria.
 
===Details for Open()===
 
Because <code>open()</code> simply enables the process of matching a channel to a Phidget device channel, <code>open()</code> returns immediately and does not wait for the channel to attach to a Phidget device channel. The channel changes state to ''open'', but is not necessarily ''attached''.  Until the channel actually becomes ''attached'' to a Phidget device channel, most of the channel class interface will not be available.
 
As long as the channel is open (and not ''attached''), the system will continue to try to match it with a
Phidget device channel that has not already been matched with a channel.  The channel can only be matched once, and the Phidget device channel can only be matched once.  For example, if you connected a single Phidget Accelerometer to a computer, and you created and opened two <code>Accelerometer</code> channels, only one of the channels would attach while the other would remain ''open'' but not ''attached''. If the ''attached'' channel were to be closed, the other channel would then attach to the Accelerometer.
 
When the channels is matched with a Phidget device channel, the channel state is changed to ''attached'' and an event is fired.
 
'''Note:''' Once a Phidget device channel is matched to a channel, it will not be available to match another channel until the first channel is closed.  The one exception is if the Phidget device channel is ''attached'' over the network through the [[Phidget Network Server]].  In that case, multiple channels are allowed to match and attach to the Phidget device channel. Some Phidgets, such as motor controllers will never match more than one channel at a time.
 
===Channel Matching===
 
The following video summarizes the basics of how to address the proper channel in your code:
 
 
<center>{{#ev:youtube|XKSenz9txKE}}</center>
 
 
<code>open()</code> can be used without specifying any matching properties.  In this case the system will match a channel with the first Phidget device channel that matches the channel class.  The channel class itself is an implied matching parameter.
 
If there is more than one Phidget connected to the computer that supports the channel class, the <code>DeviceSerialNumber</code> property must be set determine which Phidget will match.
 
If the Phidget connected to the computer has more than one channel of the same classes, the <code>Channel</code> property must be set to determine which Phidget device channel will match.
 
If the Phidget Network Server is enabled on the computer, the <code>IsRemote</code> and <code>IsLocal</code> properties can be used to determine if the channel will match the Phidget device channel or the network channel.
 
Please refer to the {{Phidget22API}}, and [[Best Phidgets Practices|Best Practices]] for more information on matching channels to Phidget device channels.
 
==== Opening a Channel on a USB Phidget ====
 
[[Image:channel-matching-1.jpg|link=|500px|center]]
 
In this example, a [{{SERVER}}/products.php?product_id=1018 1018 PhidgetInterfaceKit 8/8/8] is connected to a computer. A [{{SERVER}}/products.php?product_id=1108 1108 Magnetic Sensor] is connected to analog port 3 on the 1018. Here's how you would open the channel for the magnetic sensor in Java:
 
<syntaxhighlight lang=java>
VoltageRatioInput ch = new VoltageRatioInput();
ch.setDeviceSerialNumber(324781);
ch.setChannel(3);
ch.open();
</syntaxhighlight>
 
Or in C:
 
<syntaxhighlight lang=c>
PhidgetVoltageRatioInputHandle ch;
PhidgetVoltageRatioInput_create(&ch);
Phidget_setDeviceSerialNumber((PhidgetHandle)ch, 324781);
Phidget_setChannel((PhidgetHandle)ch, 3);
Phidget_open((PhidgetHandle)ch);
</syntaxhighlight>
 
If you wanted to open digital input 5 in the same example, it would look like this in Java:
 
<syntaxhighlight lang=java>
DigitalInput ch = new DigitalInput();
ch.setDeviceSerialNumber(324781);
ch.setChannel(5);
ch.open();
</syntaxhighlight>
 
Or in C:
 
<syntaxhighlight lang=c>
PhidgetDigitalInputHandle ch;
PhidgetDigitalInput_create(&ch);
Phidget_setDeviceSerialNumber((PhidgetHandle)ch, 324781);
Phidget_setChannel((PhidgetHandle)ch, 5);
Phidget_open((PhidgetHandle)ch);
</syntaxhighlight>
 
==== Opening a VINT Hub Port as a Channel ====
 
The ports on a [[What is VINT?|VINT]] Hub can be opened as Digital Inputs, Digital Outputs, Voltage Inputs, or Voltage Ratio Inputs. Suppose you had a [{{SERVER}}/products.php?product_id=HUB0000 HUB0000 VINT Hub] with a [{{SERVER}}/products.php?product_id=1133 1133 Sound Sensor] connected to its fourth port.
 
[[Image:channel-matching-2.jpg|link=|500px|center]]
 
Here's how you would open it in Java:
 
<syntaxhighlight lang=java>
VoltageInput ch = new VoltageInput();
ch.setDeviceSerialNumber(370181);
ch.setIsHubPortDevice(true);
ch.setHubPort(4);
ch.open();
</syntaxhighlight>
 
Or in C:
 
<syntaxhighlight lang=c>
PhidgetVoltageInputHandle ch;
PhidgetVoltageInput_create(&ch);
Phidget_setDeviceSerialNumber((PhidgetHandle)ch, 370181);
Phidget_setIsHubPortDevice((PhidgetHandle)ch, 1);
Phidget_setHubPort((PhidgetHandle)ch, 4);
Phidget_open((PhidgetHandle)ch);
</syntaxhighlight>
 
==== Opening a Channel on a VINT Device ====
 
In this example, we have a [{{SERVER}}/products.php?product_id=TMP1101 TMP1101 4x Thermocouple Phidget] and a [{{SERVER}}/products.php?product_id=HUB0000 HUB0000 VINT Hub].
 
[[Image:channel-matching-3.jpg|link=|500px|center]]
 
If we wanted to open both the thermocouple connected to port 0 and the integrated temperature sensor on the board, we first need to figure out which channels those are. Go to the [{{SERVER}}/products.php?product_id=TMP1101 product page for the TMP1101] and click on the API tab. From the table at the top of the tab, we can see that the integrated temperature sensor is TemperatureSensor channel 4. In Java, opening these channels would look like this:
 
<syntaxhighlight lang=java>
TemperatureSensor tc = new TemperatureSensor(); // Handle for the thermocouple
TemperatureSensor ic = new TemperatureSensor(); // Handle for the integrated temperature chip
 
tc.setDeviceSerialNumber();
ic.setDeviceSerialNumber();
tc.setHubPort(2);
ic.setHubPort(2);
tc.setChannel(0);
ic.setChannel(4);
 
tc.open();
ic.open();
</syntaxhighlight>
 
Or in C:
 
<syntaxhighlight lang=c>
PhidgetTemperatureSensorHandle tc; // Handle for the thermocouple
PhidgetTemperatureSensorHandle ic; // Handle for the integrated temperature chip
 
PhidgetTemperatureSensor_create(&ch);
PhidgetTemperatureSensor_create(&ch);
 
Phidget_setDeviceSerialNumber(tc, 370181);
Phidget_setDeviceSerialNumber(ic, 370181);
Phidget_setHubPort((PhidgetHandle)tc, 2);
Phidget_setHubPort((PhidgetHandle)ic, 2);
Phidget_setChannel((PhidgetHandle)tc, 0);
Phidget_setChannel((PhidgetHandle)ic, 4);
 
Phidget_open((PhidgetHandle)tc);
Phidget_open((PhidgetHandle)ic);
</syntaxhighlight>
 
==== Opening a Channel on a Remote Phidget ====
 
Suppose you wanted to open a locally connected Phidget remotely over the Network Service, so that you could have multiple programs connecting to it at the same time. In this example, we have a [{{SERVER}}/products.php?product_id=1024 1024 PhidgetRFID] connected to a computer that has the Phidget Network Server enabled.
 
[[Image:channel-matching-4.jpg|link=|600px|center]]
 
You could open the RFID reader channel remotely with the following code in Java:
 
<syntaxhighlight lang=java>
RFID ch = new RFID();
ch.setDeviceSerialNumber(388624);
ch.setIsRemote(true);
ch.open();
</syntaxhighlight>
 
Or in C:
 
<syntaxhighlight lang=c>
PhidgetRFIDHandle ch;
PhidgetRFID_create(&ch);
 
Phidget_setDeviceSerialNumber(ch, 388624);
Phidget_setIsRemote(ch, 1);
 
Phidget_open((PhidgetHandle)ch);
</syntaxhighlight>
 
== Attaching a Channel ==
 
When a channel is open (and not ''attached''), the system will continue to try to match it with a
Phidget device channel until either a match is found, or the channel is closed.  When the channels is matched with a Phidget device channel, the channel state is changed to ''attached'' and an event is fired.
 
An event handler can be registered to catch the ''attach event'' through the channel's <code>Attach</code> event.  Each channel also has a <code>Attached</code> property that can be read to determine if the class has
been matched to a Phidget device channel.
 
To set an event handler to detect the attach in Java:
 
<syntaxhighlight lang=java>
  //create a Phidget accelerometer channel:
  Accelerometer accel = new Accelerometer();
  accel.addAttachListener((AttachEvent ae) -> {
      Accelerometer accel = (Accelerometer) ae.getSource();
      // Do things after attachment (i.e. read data, control the device)
      }
  });
</syntaxhighlight>
 
Or in C:
 
<syntaxhighlight lang=c>
  // Define the attach handler function
  void CCONV
  onAttachedEventHandler(PhidgetHandle channel, void *userPtr) {
      printf("A channel has been attached\n");
      // Do things after attachment (i.e. read data, control the device)
  }
 
  int
  main(int argc, char **argv) {
    // .....Then, in the main code create the channel and set the attach handler:
    PhidgetAccelerometerHandle accel;
    PhidgetAccelerometer_create(&accel);
    Phidget_setOnAttachHandler((PhidgetHandle)accel, onAttachedEventHandler, NULL);
    // other stuff in main
  }
</syntaxhighlight>
 
The attach event handler should be set '''before''' the channel is opened; otherwise, the attach event could occur before the handler is set.
 
== Do Things with a Channel ==
 
After a channel has been ''opened'' and ''attached'', software can control the Phidget device via the channel class interface.
 
Like setting an event handler that executes [[#Attaching a Channel|when the channels is attached]], handlers can be set to receive events when a state change occurs, or sensor data is received.
 
A Voltage Input channel for example, like one supported by the  [{{SERVER}}/products.php?product_id=1018 1018 Phidget Interface Kit], can set an event handler that gets called as the voltage is processed.
 
In Java, this would look like:
 
<syntaxhighlight lang=java>
  // After creating and opening a VoltageInput channel called "sensorIn"
  sensorIn.addVoltageChangeListener((VoltageInputVoltageChangeEvent de) -> {
            System.out.println("Voltage: " + de.getVoltage());
  });
</syntaxhighlight>
 
Or in C:
 
<syntaxhighlight lang=c>
  void CCONV
  onVoltageChangeHandler(PhidgetVoltageInputHandle voltageInput, void *ctx, double voltage) {
printf("Voltage: %lf V\n", voltage);
  }
 
  // .....Then, in the main code:
  // After creating and opening a VoltageInput channel called "sensorIn"
  PhidgetVoltageInput_setOnVoltageChangeHandler(sensorIn, onVoltageChangeHandler, NULL);
</syntaxhighlight>
 
The voltage value delivered in the above snippets could also be accessed via the <code>Voltage</code> property of the channel.  Properties that have related events are automatically updated each time the event is received by the channel, and calls between events always return the value set by the last event.
 
<syntaxhighlight lang=java>
    double val = sensorIn.getVoltage();
</syntaxhighlight>
 
Or, in C:
 
<syntaxhighlight lang=c>
    double val;
    PhidgetVoltageInput_getVoltage(sensorIn, &val);
</syntaxhighlight>
 
===Sensors, Input, and Output===
 
Often, your Phidget will support more than one channel class.  For example a [{{SERVER}}/products.php?product_id=1018 1018 Phidget Interface Kit] has voltage inputs (black sensor ports), digital inputs and digital outputs (green terminal blocks). You can determine the channel classes supported by your Phidget from the product page and the {{Phidget22API}}.
 
For InterfaceKits like the 1018:
 
* To the voltage inputs, you can attach various sensors (temperature, humidity, light, sound) 
* To the digital inputs, you can attach various input devices (switches)
* To the digital outputs, you can attach simple indicators (LEDs, buzzers, relays)
 
The features and channels supported by each Phidget are many and varied, and we only include general concepts on this page. You can view the complete list of channels supported by a Phidget in the {{Phidget22API}}. Select a device at the top of the screen, select your preferred programming language, and then select which channel class you want to view the documentation for.
 
== Close a Channel ==
 
When you are finished with a channel, you should close and (in some languages) delete it.  Once closed, the Phidget device channel the channel was matched to will be released and made available for another channel to match.
 
For example, in Java:
 
<syntaxhighlight lang=java>
  device.close();
  device = null;
</syntaxhighlight>
 
Or, in C:
 
<syntaxhighlight lang=c>
Phidget_close((PhidgetHandle)channel);
Phidget_release((PhidgetHandle *)&channel); // will NULL the pointer
</syntaxhighlight>
 
When you close a channel, it will reset all of the properties of that channel. For example, a digital output will revert back to FALSE when it is closed. If you want to have persistent properties, you can keep the channel open in another process over the [[Phidget Network Server|Network Server]] and open it remotely with your main program. As long as the channel is opened in at least one program or process, its properties will persist.
 
== Further Reading ==
 
[[Data Interval/Change Trigger]] - Learn about these two properties that control how much data comes in from your sensors.
 
[[Using Multiple Phidgets]] - How to know you are attaching to the Phidget you want.
 
[[Polling vs. Events]] - Your program can gather data in either a polling-driven or event-driven manner. Learn the difference to determine which is best for your application.
 
[[Logging, Exceptions, and Errors]] - Learn about all the tools you can use to debug your program.
 
[[Phidget Network Server]] - Phidgets can be controlled and communicated with over your network- either wirelessly or over ethernet.
 
[[Best Phidgets Practices]] - Good programming habits that will save you from common problems when writing code for your Phidgets.

Latest revision as of 14:46, 8 August 2023

 Phidget Programming Basics: Phidget Programming BasicsTOC Icon.png Table of Contents

Nav Back Arrow Grey.pngGreenTab1.png WhiteTab2.png HoverTab2.jpg WhiteTab3.png HoverTab3.jpg WhiteTab4.png HoverTab4.jpg WhiteTab5.png HoverTab5.jpg WhiteTab6.png HoverTab6.jpg WhiteTab7.png HoverTab7.jpg WhiteTab8.png HoverTab8.jpg WhiteTab9.png HoverTab9.jpg WhiteTab10.png HoverTab10.jpg WhiteTab11.png HoverTab11.jpg WhiteTab12.png HoverTab12.jpg WhiteTab13.png HoverTab13.jpg WhiteTab14.png HoverTab14.jpg WhiteTab15.png HoverTab15.jpg WhiteTab16.png HoverTab16.jpg Nav Next Arrow.png Nav Next Hover.png


1 . Phidget Programming Basics

Welcome!

Welcome to the Phidget Programming Basics guide!

By following this guide, you will learn the important concepts behind how Phidgets are used in any software application.

Before You Start

We recommend having a few things set up before starting this guide on how to program with Phidgets:

1. You will need the Phidget22 libraries installed on your machine. To get the Phidgets libraries for your operating system, check out our page on Operating System Support.

2. We recommend knowing which programming language you intend to use before starting this guide, so you can follow along. We provide a list of programming languages we support, and instructions of how to set them up for use with Phidgets.

3. This guide will work best if you have a Phidget to work with, and have already tried it out using the Phidget22 Control Panel. If you haven't yet, navigate to the product page for your Phidget and follow the instructions in the User Guide tab to try it out.

Table of Contents

  1. Phidget Programming Basics
  2. Phidget Channels
  3. Phidget Program Outline
  4. Creating a Channel
  5. Addressing Phidgets
  6. Opening a Channel
  7. Attaching a Channel
  8. Do Things with the Channel
  9. Closing a Channel
  10. Using Events
  11. A Basic Phidget Program
  12. Using Multiple Phidgets
  13. Using the Phidget22 API
  14. Handling Errors and Logging
  15. Phidget Network Server
  16. Advanced Topics

Table of Contents

  1. Phidget Programming Basics
  2. Phidget Channels
  3. Phidget Program Outline
  4. Creating a Channel
  5. Addressing Phidgets
  6. Opening a Channel
  7. Attaching a Channel
  8. Do Things with the Channel
  9. Closing a Channel
  10. Using Events
  11. A Basic Phidget Program
  12. Using Multiple Phidgets
  13. Using the Phidget22 API
  14. Handling Errors and Logging
  15. Phidget Network Server
  16. Advanced Topics