Utiliser les capteurs Phidgets avec JavaScript


4 août 2015 Jean-Philippe Côté
publié dans
Rate this post

Lors du développement d’un projet d’interactivité tangible, il est généralement nécessaire de récupérer des données provenant du monde réel. Par exemple, on peut vouloir obtenir la distance à laquelle se trouve un objet, la quantité de vibration, la position GPS, l’illumination de la pièce, la pression d’air, la force appliquée à un bouton, etc. Comment est-il possible de récupérer de telles informations dans un projet de physical computing développé en JavaScript ? Une des façons les plus simples, est d’utiliser un capteur de la compagnie Phidgets Inc. Ce tutoriel vous expliquera comment. Phidgets Inc. fabrique une variété de capteurs et ceux-ci peuvent tous être utilisés en JavaScript. Ces capteurs vous permettront de répondre à des questions telles que:

  • L’utilisateur a-t-il touché à l’interface ?
  • L’objet est-il dans la bonne orientation spatiale ?
  • Avec quelle force le bouton a-t-il été appuyé ?
  • À quelle distance est l’usager ?
  • À quel point l’interface a-t-elle été pliée ?
  • etc.

Les possibilités sont sans fin. De plus, ce qui est intéressant des capteurs Phidgets c’est qu’ils fonctionnent tous de la même façon. Une fois que vous savez en utilisez un, vous savez les utiliser tous. Dans ce tutoriel, nous allons créer une application native qui aura accès aux données provenant de n’importe quel capteur analogique Phidgets. Pour les fins de ce tutoriel, nous utiliserons un capteur de force. Ce capteur indique la force avec laquelle l’usager appuie dessus. Ceci dit, vous pouvez substituer un autre capteur dans la réalisation de ce tutoriel et ça fonctionnera tout aussi bien.

Caveat: as often on the TangibleJS site, this tutorial will show you how to bring in sensor inputs to a NW.js-based project. The instructions below will not work for a regular, sandboxed web page hosted on a web server. To know more about setting up a NW.js project, please check out my other tutorial titled: Creating a Native App with HTML, CSS and JavaScript.

All sensors are designed to hook up to an I/O board. This board will act as a bridge between the sensor(s) and the computer. There are various I/O boards, varying in form factor and number of inputs and outputs. To get started, a versatile board such as the PhidgetInterfaceKit 8/8/8 (CAD80$) is perfect. This is the one we will use in this tutorial. PhidgetInterfaceKit 8/8/8 The 8/8/8 can be used to gather the input of up to 8 analog sensors. It can also accomodate an additional 8 digital inputs (such as switches) and 8 CMOS outputs. While the I/O boards are not cheap (between 50$ and 125$), they make it up in simplicity.

Setting up the hardware and drivers

To get started, the first thing you need to do is install the drivers for the Phidgets. You can get them for Mac OS X, Linux and Windows on the Drivers page of the phidgets.com website. After installation, you will be able to access a control panel providing information about any connected I/O boards. On Mac, the control panel is accessible in the system preferences: mac-os-x-control-panel On Windows, you can access it by double-clicking its icon in the system tray: windows-control-panel

The Linux driver does not offer a graphical user interface. For OS-specific installation and configuration instructions, please check out the Phidgets Linux page.

Once this is done, plug the I/O board to the USB port of your computer. It should now show up in the control panel: Phidget Control Panel If you double-click the I/O board’s name, you will be taken to a screen for this specific device. On this screen, you can view the status of all inputs and outputs. For example, you can see below that an analog sensor has been connected to input #2 and that its current value is 416. Phidget Control Panel - Device detail

No matter what type of analog sensor you use, the reported value will always be between 0 (minimum) and 1000 (maximum).

Let’s now see if everything is working right. Using the supplied red, black and white cable, plug in your sensor to any of the 8 analog inputs (labeled 0 through 7). For example, here is a force sensor hooked up to input number 6: Connecting a Phidget to the I/O board If you play with the sensor, you should now see the value of the corresponding input change in the control panel window. The last thing we need to do is activate the Phidget Webservice. The Webservice will allow JavaScript to connect to the device via a network socket connection. Simply press Start to activate it. Phidget Webservice What is nice about this architecture is that you can control devices connected locally (the usual scenario) or devices connected to a remote computer anywhere on the internet. In this tutorial we will use a locally-connected device.

Setting up the project and libraries

Now that the we know the hardware is working, we need to hook it up into our project. As was stated earlier, we will use NW.js to create a native application from HTML, CSS and JavaScript. Using NW.js will grant us access to the DOM and, more importantly, to all Node.js functionalities. This is necessary since we will need a Node.js module to talk to the Phidget Webservice.

If you are not familiar with NW.js, I urge you to read my other tutorial called Creating a Native App with HTML, CSS and JavaScript before moving on.

First, let’s create a folder to put the project in. Inside that folder, create a package.json file to inform NW.js of the options we wish to use. Let’s keep its content super simple for now:

This gives the project a name (lowercase, no spaces) and tells NW.js to open index.html when the application starts. You should now add the aforementioned index.html file to the folder. A simple HTML file with a single div will do:

As you might have noticed, this HTML file loads a JavaScript file. Later on in this tutorial, we will put our code in this file. You can create script.js and leave it empty for now. Our file structure is now ready. The only thing we are missing is the phidgets Node module. There are two ways to install it.

  • If you are familiar with the Terminal (Mac, Linux) or the Command Prompt (Windows), this is the simplest way to install it.

    To do that, you will need to have Node.js installed. If that’s not the case, install it first.

    Simply cd to the project directory and issue : npm install phidgets. This will create a node_modules  subfolder and place the phidgets module inside it. Installing the module via the Terminal Do not worry about the warnings, the module has indeed been installed correctly.

  • If you are not familiar with the Terminal or do not wish to install Node.js, you can install the module manually. First, create a node_modules folder inside your project folder. Then create a phidgets  folder inside the node_modules  folder. Then download the phidgets module and unzip it. Take all the files inside  nodePhidgets-master  and move them to the phidgets  folder you just created.

In the end, your project folder should look something like this: Project structure We are now ready to edit the script.js  file.

Let’s write some code!

Fire up your favorite web editor and open the script.js file. Inside, paste the following code:

This code uses Node’s require()  function to fetch the library and to create a new instance of the PhidgetInterfaceKit object. It then adds a listener for the sensor event. The sensor  event is triggered each time the state of any sensor input changes. Data about the event (such as the input number and the value) is placed inside the data variable. Finally, it calls the open() function of the PhidgetInterfaceKit object to open a connection to the sensor. Let’s try to run it to see the messages appear in the console. If you have read Creating a Native App with HTML, CSS and JavaScript you know that you can run the code by placing the NW.js files in your project folder and double-clicking nw, nw.exe or nw.app(depending on your platform).

Another (simpler) way to run the code is to use the Terminal/Command Prompt. Simply call nw  while passing it the path to the folder containing the project. On my Mac, it looks like this:

Obviously, nwjs  has been added to my PATH system variable.

If you fiddle with your sensor, you should see messages appearing in the console. Obviously, you first need to open the console by clicking on the gear icon:Developer Tools on MacTo make things a little more visually appealing, let’s vary the width of the div according to the input from the sensor. To do that, let’s add a second line inside the listener function:

This new line modifies the width of the div using the value received from the sensor. Note that we have to divide the value by ten since sensor values are between 0 and 1000. Beware that the sensor event is triggered by all sensor inputs. So, if you had more than one sensors connected, the result might not be what you expect. That’s why we usually filter by using the input number:

In this case, the div ‘s width will only be altered if the sensor event happened on the sensor connected to input #6. Isn’t it cool? With just a few lines of code, you can have a real-life sensor sending data to your HTML/CSS/JavaScript-based native application! Obviously, changing the size of a div  is not particularly spectacular. However, once the data is available in JavaScript, you can do pretty much anything you want. For instance, you could use the sensor data to navigate a ThreeJS 3D scene or to dynamically generate sounds and effects using DSP.js.

Going further

If you want to go further with the phidgets Node.js module, you can check out the package’s Getting Started instructions and the full API documentation. The Phidgets website also contains valuable hardware-related information such as their Analog Input Primer.


Rédiger un commentaire

Votre adresse courriel ne sera pas publié.

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.