Language - Python: Difference between revisions

From Phidgets Support
No edit summary
 
(213 intermediate revisions by 10 users not shown)
Line 1: Line 1:
Preamble about the language and its general strengths and weaknesses.
{{#seo:|description=Learn how to use Phidget USB devices with Python.}}
[[Category:Language]]


==Assessment for use with Phidgets==
==Get Started==
Our honest opinion on how well this language is suited to controlling Phidgets. If it is a poor choice, suggest and link similar (better) languages.
With the Phidget22 Python library, it's easy to create Python applications that work with Phidget devices.


==Support==
==Python Libraries==
Python has a complete API and sample code for all Phidgets devices.
===pip Package===
The Phidget22 Python library is available as a [https://pypi.org/project/phidget22/ pip package]. Most development environments provide built-in tools to manage packages. View the [[#Development Environment Configuration | Development Environment Configuration]] section below for examples.  


For a complete list of our supported languages and their support status, [[Levels of Support|click here]].
====macOS Considerations====
Phidget devices running a HID USB stack require the installation of the macOS libraries or the standalone Phidget Control Panel ([{{SERVER}}/docs/OS_-_macOS download here]).


==Restrictions==
To determine what USB stack your Phidget device is on, navigate to the product page and then to the specification tab, and look for the ''USB Stack'' specification. If you are using a VINT device, navigate to the product page for the VINT Hub you are using.
In this section, list any restrictions or limitations that this particular language may impose. For example, incompatibility with certain operating systems.


==Development Environments and Compilers==
[[Image:Javascript_networkserver_webusb_spec.png|center|600px|link=https://cdn.phidgets.com/docs/images/8/80/Javascript_networkserver_webusb_spec.png]]


Describe each major compiler and notable differences or important information. (eg. framework versions) If there are known issues/workarounds mention them and link to the corresponding issue at the bottom of the page.  
====Linux Considerations====
Linux restricts access to USB devices to the root user. To run your Python application as a regular user, you'll need to [{{SERVER}}/docs/OS_-_Linux#Setting_Udev_Rules set up udev rules] on your system.


==Drivers, Libraries and Resources==
===Source Files===
Before you can run your program, you need to set up the proper environment and get the necessary files off the Phidgets website.
The Phidget22 Python library source files are available [https://cdn.phidgets.com/downloads/phidget22/libraries/any/Phidget22Python.zip here].
Visit the drivers section at www.phidgets.com and get the latest:
* [http://www.phidgets.com/drivers.php Phidget Framework]
* [http://www.phidgets.com/downloads/libraries/PhidgetsPython_2.1.8.20110804.zip Phidgets Python Module]
You will need the Phidget Framework to use and to program with Phidgets. We also recommend that you download the following reference materials:
* [http://www.phidgets.com/documentation/PythonDoc.zip API Manual]
* [http://www.phidgets.com/documentation/web/PythonDoc/Phidgets.html API Reference]
* [http://www.phidgets.com/downloads/examples/Python_2.1.8.20110804.zip Python Sample Code]
* You can find a high level discussion about programming with Phidgets in general on the [[General API]] page.
* The [[Device Functionality]] page explains the general operational information for your device.  


You may want to have these pages open while working through these instructions.
==Development Environment Configuration==
Most development environments provide built-in tools to manage Python interpreters, packages, and virtual environments. See the examples below for more information.
===Installing a Python Interpreter===
If you don't already have a Python interpreter installed, you can download and install one from [https://www.python.org/downloads/ python.org] or through package managers like [https://brew.sh/ Homebrew].


==Getting Started==
===Visual Studio Code===
{| style="margin:auto;" class="table-no-border mw-collapsible mw-collapsed"
|+ '''Instructions'''
| Install the [https://marketplace.visualstudio.com/items?itemName=ms-python.python Python extension for Visual Studio Code].|| [[Image:Language_python_vscode_install.png|center|350px|link=https://cdn.phidgets.com/docs/images/f/f9/Language_python_vscode_install.png]]
|-
| Next, create a directory and open it in Visual Studio Code. You can do this by opening Visual Studio Code and selecting '''File > Open Folder...''' || [[Image:Language_python_vscode_newfolder.png|center|350px|link=https://cdn.phidgets.com/docs/images/f/f8/Language_python_vscode_newfolder.png]]
|-
| Open the Command Palette (Ctrl + Shift + P), type '''Python: Create Environment''', and press Enter. Select '''Venv''' when prompted. || [[Image:Language_python_vscode_newvenv.png|center|350px|link=https://cdn.phidgets.com/docs/images/a/a6/Language_python_vscode_newvenv.png]]
|-
| Next, select your preferred Python interpreter from the list. You may need to browse to find it. || [[Image:Language_python_vscode_selectinterpreter.png|center|350px|link=https://cdn.phidgets.com/docs/images/2/20/Language_python_vscode_selectinterpreter.png]]
|-
| Open a new terminal. You can do this through the Command Palette again (Ctrl + Shift + P), by typing '''Terminal: Create New Terminal'''. Install the Phidget22 pip package:
<syntaxhighlight lang=bash>
#Windows
py -m pip install phidget22


The Phidget examples were written in Python 3.0 and this tutorial assumes its use. 
#macOS
However, they should still be compatible with Python 2.6. 
python3 -m pip install phidget22
To run the examples using Python 2.5, you will need to modify the example code in the exception handling to read “except RuntimeError, e:”, instead of “except RuntimeError as e:”.
Please ensure you have extracted the “Phidgets” directory from the Python Module into your project directory or into the lib\site-packages\ directory in your python install.


===Coding For Your Phidget===
#Linux (Debian)
python3 -m pip install phidget22
</syntaxhighlight>
|| [[Image:Language_python_vscode_installpackage.png|center|350px|link=https://cdn.phidgets.com/docs/images/a/a8/Language_python_vscode_installpackage.png]]
|-
| Finally, add your Python file and run it using the button in the top right corner.|| [[Image:Language_python_vscode_runcode.png|center|350px|link=https://cdn.phidgets.com/docs/images/9/96/Language_python_vscode_runcode.png]]
|-
|}


Before you can use the Phidget, you must include a reference in the code to the library. In Python:
===PyCharm===
{| style="margin:auto;" class="table-no-border mw-collapsible mw-collapsed"
|+ '''Instructions'''
| Create your PyCharm project and navigate to '''Settings''': || [[Image:Windows_pycharm_settings.jpg|center|350px|link=https://cdn.phidgets.com/docs/images/7/75/Windows_pycharm_settings.jpg]]
|-
| Next, navigate to '''Project > Project Interpreter''' and click on the '''+''' symbol: || [[Image:Windows_pycharm_addpackage.jpg|center|350px|link=https://cdn.phidgets.com/docs/images/6/6f/Windows_pycharm_addpackage.jpg]]
|-
| Search for '''phidget22''' and install the package: || [[Image:Windows_pycharm_installpackage.jpg|center|350px|link=https://cdn.phidgets.com/docs/images/a/ad/Windows_pycharm_installpackage.jpg]]
|-
| Finally, add your Python file and run it using the button at the top of the screen: || [[Image:Windows_pycharm_run.png|center|350px|link=https://cdn.phidgets.com/docs/images/0/0a/Windows_pycharm_run.png]]
|}


==Example Code==
Navigate to our [https://www.phidgets.com/?view=code_samples&lang=Python Code Sample Generator] to view and download code samples that are tailored to your specific device.


[[Image:Language_python_codesample.png|center|600px|link=https://cdn.phidgets.com/docs/images/2/2d/Language_python_codesample.png]]


from Phidgets.PhidgetException import *
===Phidget Programming Basics===
from Phidgets.Events.Events import *
{{PhidgetProgrammingBasicsLink}}
from Phidgets.Devices.InterfaceKit import *


 
==API==
 
[{{SERVER}}/?view=api&lang=Python Phidget22 API]
Afterwards, the Phidget object will need to be declared and then initialized.
For example, we can declare a PhidgetInterfaceKit with:
 
 
 
try:
  interfaceKit = InterfaceKit()
except RuntimeError as e:
print("Runtime Error: %s" % e.message)
 
 
 
The initialization of the Phidget as well as calls using the Phidget object should be surrounded by a try catch block to handle any errors thrown by the library.
Calls to the Phidget object will throw a PhidgetException on an error.
 
 
 
try:
  #Your program Code here
except PhidgetException as e:
      print (“Phidget Exception %i: %s” % (e.code, e.detail))
      exit(1)
 
 
 
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.
 
===Connecting to the Phidget===
 
The program can try to connect to the Phidget through an open call.
Open will 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 checking isAttached().
 
 
 
interfaceKit.openPhidget()
    interfaceKit.waitForAttach(10000)
    print (“%d attached!” % (interfaceKit.getSerialNum()))
 
 
 
The parameters can be used to open the first Phidget of a type 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.
At the end of your program, don’t forget to call close to free any locks on the Phidget.
 
interfaceKit.closePhidget()
 
===Event Driven Programming===
 
We recommend the use of event driven programming when working with Phidgets.
In Python, we hook an event handler by defining the callback function and then calling a set handler function on it. 
 
 
 
def interfaceKitSensorChanged(e):
      print (“Sensor %i: %i” % (e.index, e.value))
return 0
interfaceKit.setOnSensorChangeHandler(interfaceKitSensorChanged)
 
 
 
With this, the code inside interfaceKitSensorChanged will get executed every time the PhidgetInterfaceKit reports a change on one of its analog inputs.
The values from the report can be accessed from the PhidgetDataEvent object properties.
 
Certain 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 for a full list of events and their usage.
 
===Working directly with the Phidget===
 
Some values can be directly read and set on the Phidget and used as an alternative to event driven programming.
Simply use the instance properties or call member functions such as getSensorValue(index) or setOutputState(index, state) for PhidgetInterfaceKits.
 
 
 
interfaceKit.setOutputState(0, 1)
 
 
 
===Working with multiple Phidgets===
 
Multiple Phidgets of the same type can easily be run inside the same program.
In our case, it requires another instance of a PhidgetInterfaceKit to be defined and initialized.
The new instance can then be set up, opened and used in the same process as the previous one.
If the application needs to distinguish between the devices, open can be called with the serial number of a specific Phidget.
 
===Other Phidgets===
 
The design given in this document can also be followed for almost all Phidgets.
For example, if you were using a PhidgetRFID instead of a PhidgetInterfacekit, you would declare an RFID instead of an InterfaceKit.
The functions and events available would change but they can be accessed in a similar manner.
 
==Building your Project==
Describe the different ways a project could be built using this language.
 
==Common Problems and Solutions/Workarounds==
Here you can put various frequent problems and our recommended solutions.

Latest revision as of 18:51, 11 June 2025


Get Started

With the Phidget22 Python library, it's easy to create Python applications that work with Phidget devices.

Python Libraries

pip Package

The Phidget22 Python library is available as a pip package. Most development environments provide built-in tools to manage packages. View the Development Environment Configuration section below for examples.

macOS Considerations

Phidget devices running a HID USB stack require the installation of the macOS libraries or the standalone Phidget Control Panel (download here).

To determine what USB stack your Phidget device is on, navigate to the product page and then to the specification tab, and look for the USB Stack specification. If you are using a VINT device, navigate to the product page for the VINT Hub you are using.

Javascript networkserver webusb spec.png

Linux Considerations

Linux restricts access to USB devices to the root user. To run your Python application as a regular user, you'll need to set up udev rules on your system.

Source Files

The Phidget22 Python library source files are available here.

Development Environment Configuration

Most development environments provide built-in tools to manage Python interpreters, packages, and virtual environments. See the examples below for more information.

Installing a Python Interpreter

If you don't already have a Python interpreter installed, you can download and install one from python.org or through package managers like Homebrew.

Visual Studio Code

Instructions
Install the Python extension for Visual Studio Code.
Language python vscode install.png
Next, create a directory and open it in Visual Studio Code. You can do this by opening Visual Studio Code and selecting File > Open Folder...
Language python vscode newfolder.png
Open the Command Palette (Ctrl + Shift + P), type Python: Create Environment, and press Enter. Select Venv when prompted.
Language python vscode newvenv.png
Next, select your preferred Python interpreter from the list. You may need to browse to find it.
Language python vscode selectinterpreter.png
Open a new terminal. You can do this through the Command Palette again (Ctrl + Shift + P), by typing Terminal: Create New Terminal. Install the Phidget22 pip package:
#Windows
py -m pip install phidget22 

#macOS
python3 -m pip install phidget22 

#Linux (Debian)
python3 -m pip install phidget22
Language python vscode installpackage.png
Finally, add your Python file and run it using the button in the top right corner.
Language python vscode runcode.png

PyCharm

Instructions
Create your PyCharm project and navigate to Settings:
Windows pycharm settings.jpg
Next, navigate to Project > Project Interpreter and click on the + symbol:
Windows pycharm addpackage.jpg
Search for phidget22 and install the package:
Windows pycharm installpackage.jpg
Finally, add your Python file and run it using the button at the top of the screen:
Windows pycharm run.png

Example Code

Navigate to our Code Sample Generator to view and download code samples that are tailored to your specific device.

Language python codesample.png

Phidget Programming Basics

To learn more about the structure of the example code, visit our Phidget Programming Basics guide.

API

Phidget22 API