Notice: This page contains information for the legacy Phidget21 Library. Phidget21 does not support VINT Phidgets, and will not support any new Phidgets. Phidget21 will be maintained until 2020. 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.


Language - Objective C

From Phidgets Legacy Support
Revision as of 19:29, 22 May 2012 by Cora (Talk | contribs)

Jump to: navigation, search
Cocoa is Apple's native object-oriented application programming interface (API) for the Mac OS X operating system.


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 Cocoa specifically.

Cocoa is capable of using the complete Phidget API, including events. We also provide example code in Cocoa for all Phidget devices.

Cocoa can be developed with XCode on OS X.

You can compare Cocoa with our other supported languages.

Quick Downloads

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


Example Code

Libraries and Drivers

Getting started with Cocoa

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

We offer support for developing Cocoa on OS X.


The Phidget examples were written in Objective-C and Xcode 3.2.4, and this tutorial assumes their use. Other versions of Xcode should work as well and would be set up in a similar manner.

Description of Files

Any files we think are worth knowing about specifically, or at the minimum a note that the OS X install puts things in their proper place.


Use Our Examples

Write Your Own Code

  • Generate a new Cocoa project with a descriptive name such as PhidgetTest.
  • Add the Phidget21 Framework(Groups & Files -> Frameworks -> Other Frameworks).
  • Create a new Objective-C class with a descriptive name. For the purpose of this guide, the class name will be PhidgetInterfaceKit.

A header file(.h) as well as an implementation file(.m) will automatically be created.

  • Open the header file for editing
  • Add a reference to phidget21.h:
  #import <Phidget21/phidget21.h>
  • A text field will be used for the purpose of capturing output. Add a text field outlet in the header file. For example,
  @interface PhidgetInterfaceKit : NSObject{
    IBOutlet NSTextField *sensorValueTxt;
  • In Groups & Files -> Resources, open up MainMenu.nib to bring up the Interface Builder. Drag a text field from the Library to the Window.
  • Now, an instance of the PhidgetInterfaceKit class will need to be created. In the Library, drag an object to the MainMenu.nib Window.

Open up the Identity tab of the Inspector for this object and add the PhidgetInterfaceKit class.

  • Connect the PhidgetInterfaceKit class instance to the text field.

The project now has access to Phidgets and we are ready to begin coding.

Follow The Examples

Code Snippets

Step One: Initialize and Open

A Phidget object will need to be declared. Make sure you have given your program access to Phidgets as described in the Write Your Own Code section. For example, we can declare a PhidgetInterfaceKit in the .m implementation file with:

  CPhidgetInterfaceKitHandle ifkit

The object name for any type of Phidget is listed in the API manual. Every type of Phidget also inherits functionality from the Phidget base class.

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

Next, the Phidget object needs to be initialized and the program needs to try and connect to the Phidget through a call to open(). Open will tell the program to continuously try to connect to a Phidget, based on the parameters given, even trying to reconnect if it gets disconnected. This means that simply calling open does not guarantee you can use the Phidget immediately. We can handle this by using event driven programming and tracking the AttachEvents and DetachEvents, or by calling waitForAttachment. WaitForAttachment will block indefinitely until a connection is made to the Phidget, or an optional timeout is exceeded. For example, we can connect to a PhidgetInterfaceKit in the .m implementation file with:

  @implementation PhidgetInterfaceKit
  - (void)awakeFromNib
    CPhidget_open((CPhidgetHandle)ifkit, -1);

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. One important thing to remember is that when working with Phidgets, a local connection will reserve the device until closed. This prevents any other instances from retrieving data from the Phidget, including other programs. The one connection per device limit does not apply when exclusively using the Phidget Webservice.

Step Three: Do Things with the Phidget

We recommend the use of event driven programming when working with Phidgets. We can hook an event handler at loading with the following code:

  CPhidgetInterfaceKit_set_OnSensorChange_Handler(ifkit, gotSensorChange, self);

Next, the callback method needs to be set up before it can be used. For example,

int gotSensorChange(CPhidgetInterfaceKitHandle phid, void *context, int ind, int val)
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [(id)context performSelectorOnMainThread:@selector(SensorChange:)
    withObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:ind], [NSNumber
    numberWithInt:val], nil] waitUntilDone:NO];
    [pool release];
    return 0;

Above, the SensorChange method is invoked on the main thread. Event data is stored in a NSArray, which in turn is sent as a single argument to the SensorChange method. The NSAutoreleasePool object is created to clean up released objects on the event thread, and is released at the end of the method.

The SensorChange method is defined as follows:

  - (void)SensorChange:(NSArray *)sensorChangeData
    int sensorIndex, sensorValue;
    sensorIndex = [[sensorChangeData objectAtIndex:0] intValue];
    sensorValue = [[sensorChangeData objectAtIndex:1] intValue];
    [sensorValueTxt setStringValue:[NSString stringWithFormat:@"Sensor: %d, Value: 
    %d", sensorIndex, sensorValue]];

With this function, the code inside SensorChange will get executed every time the PhidgetInterfaceKit reports a change on one of its analog inputs. Some events such as Attach and Detach belong to the base Phidget object and thus are common to all types of Phidgets. Please refer to the API manual and the Cocoa examples for a list of events and their usage.

Some values can be read and sent directly to the Phidget, simply use the C API functions such as CPhidgetInterfaceKit_getSensorValue() for PhidgetInterfaceKits.

  int sensorValue;
  CPhidgetInterfaceKit_getSensorValue(ifkit, 0, &sensorValue);
  [sensorValueTxt setintValue: sensorValue];

These functions can be used inside a polling loop as an alternative to event driven programming.

Step Four: Close and Delete

At the end of your program, don’t forget to call close to free any locks on the Phidget.


More How-To's

The General Phidget Programming page gives more information about:

Common Problems and Solutions/Workarounds

None at this time.