Language - Python: Difference between revisions

From Phidgets Support
mNo edit summary
No edit summary
Line 339: Line 339:


==Write Code==
==Write Code==
By following the instructions for your operating system and compiler 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 [[#Edit the Examples|teaching section]] has resources for you to learn from the examples and write your own.
{{WriteCode_Intro}}
Your main reference for writing Python code will be the {{Phidget22API}}.


=== Code Snippets ===
=== Step One: Initialize and Open ===
You will need to declare your Phidget object in your code. For example, we can declare a digital input object like this:
<syntaxhighlight lang=python>
ch = DigitalInput()
</syntaxhighlight>


The following code snippets describe how to do various general tasks with Phidgets. You should be able to find places in the examples where these snippets exist, and modify them to suit your requirements.


==== Step One: Initialize and Open ====
Next, we can open the Phidget object like this:
<syntaxhighlight lang=python>
ch.open()
</syntaxhighlight>


Before using a Phidget, it must first be created and opened.


Although we are not including it on this page, you should handle the return values of all Phidget functions. Here is an example of the previous code with error handling:
<syntaxhighlight lang=python>
<syntaxhighlight lang=python>
# Create
try:
try:
   device = DigitalInput()
   ch = DigitalInput()
except RuntimeError as e:
except RuntimeError as e:
   print("Runtime Error: %s" % e.message)
   print("Runtime Error: %s" % e.message)  
# Open
try:
try:
   device.open()
   ch.open()
except PhidgetException as e:
except PhidgetException as e:
   print (“Phidget Exception %i: %s” % (e.code, e.details))
   print (“Phidget Exception %i: %s” % (e.code, e.details))
  exit(1)
</syntaxhighlight>
</syntaxhighlight>


The variable device is now a handle for the Phidget. This example is ''specific to the Digital Input'' because the call DigitalInput() is used. For another device, use the correspondingly named call in the Python API.
The handle '''device''' is then used for all the Python function calls using the Phidget for its device-specific functions - in this case, Digital Input specific functions. 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.


Also note that you can catch exceptions thrown by the Phidget library as we did above when using the open() call. In other words, this should probably be present around most of your Phidget calls, especially when you are learning how to use the Phidget and debugging your code:
=== Step Two: Wait for Attachment (plugging in) of the Phidget ===
Simply calling open does not guarantee you can use the Phidget immediately. To use a Phidget, it must be plugged in (attached). We can handle this by using event driven programming and tracking the attach events. Alternatively, we can modify our code so we wait for an attachment:


<syntaxhighlight lang=python>
<syntaxhighlight lang=python>
try:
ch = DigitalInput()
  # Your code goes here
ch.openWaitForAttachment(5000)
except PhidgetException as e:
  print (“Phidget Exception %i: %s” % (e.code, e.details))
  exit(1)
</syntaxhighlight>
</syntaxhighlight>
Waiting for attachment will block indefinitely until a connection is made, or until the timeout value is exceeded


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


To use the Phidget, it must be plugged in (attached). We can handle this simply by calling openWaitForAttachment in place of the basic open. This function works for any Phidget. openWaitForAttachment will block until a connection is made to the Phidget, or the specified timeout is exceeded:


To use events to handle attachments, we have to modify our code slightly:
<syntaxhighlight lang=python>
<syntaxhighlight lang=python>
device.openWaitForAttachment(5000)
ch = DigitalInput()
print ("%d attached!" % (device.getDeviceSerialNumber()))
ch.setOnAttachHandler(onAttachHandler)
ch.open()
</syntaxhighlight>
</syntaxhighlight>


Sometimes, it makes more sense to handle the attachment via an event. This would be in instances where the Phidget is being plugged and unplugged, and you want to handle these incidents. Or, when you want to use event-driven programming because you have a GUI-driven program. In these cases, an event-driven code snippet to handle the attachment might look something like this:
Next, we have to declare the function that will be called when an attach event is fired - in this case the function ''OnAttachedHandler'' will be called:
 
<syntaxhighlight lang=python>
<syntaxhighlight lang=python>
def AttachHandler(e):
def onAttachHandler(e):
    attachedDevice = e
     print("Phidget attached!")
    serialNumber = attachedDevice.getSerialNum()
    deviceName = attachedDevice.getDeviceName()
     print("Hello to Device " + str(deviceName) + ", Serial Number: " + str(serialNumber))
# Insert code for -creating- device here....
try:
    device.setOnAttachHandler(AttachHandler)
except PhidgetException as e:
    # Insert code for handling any exceptions
    # A common exception will occur if you do not create the device properly above
# Insert code for -opening- device here....
</syntaxhighlight>
</syntaxhighlight>


==== Step Three: Do Things with the Phidget ====
=== Step Three: Do Things with the Phidget ===
 
We recommend the use of event driven programming when working with Phidgets. In a similar way to handling an attach event as described above, we can also add an event handler for a state change event:
You can read data and interact with your Phidget both by polling it for its current state (or to set a state), or by catching events that trigger when the data changes.
 
For a Phidget Digital Input or Output, the polling method of getting the input state or setting an output state looks something like this:
 
<syntaxhighlight lang=python>
<syntaxhighlight lang=python>
#Get the state from a digital input
ch = DigitalInput()
digitalInputDevice.getState()
ch.setOnAttachHandler(onAttachHandler)
 
ch.setOnStateChangeHandler(onStateChangeHandler)
#Set the duty cycle for a digital output
ch.open()
digitalOutputDevice.setDutyCycle(0)
</syntaxhighlight>
</syntaxhighlight>


To catch data changes via events, you would use something like this:
This code will connect a function and an event. In this case, the ''onStateChangeHandler'' function will be called when there has been a change to the devices input. Next, we need to create the ''onStateChangeHandler'' function:
 
<syntaxhighlight lang=python>
<syntaxhighlight lang=python>
def StateChangeHandler(e, state):
def onStateChangeHandler(e, state):
     print("State %f" % state)
     print("State %f" % state)
     return 0
     return 0
# Insert code to create an Digital Input called 'device'
# Hook our function above into the device object
    device.setOnStateChangeHandler(StateChangeHandler)
# Insert code to open 'device'
</syntaxhighlight>
</syntaxhighlight>


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


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!
If events do not suit your needs, you can also poll the device directly for data using code like this:
<syntaxhighlight lang=python>
state = ch.getState()
print("State %f" % state)
</syntaxhighlight>


=== Step Four: Close and Delete ===
At the end of your program, be sure to close and delete your device:
<syntaxhighlight lang=python>
<syntaxhighlight lang=python>
device.close()
ch.close()
</syntaxhighlight>
</syntaxhighlight>



Revision as of 21:41, 9 June 2017


Quick Downloads

Documentation

Example Code

Libraries

Getting Started with Python

Welcome to using Phidgets with Python! By using Python, you will have access to the complete Phidget22 API, including events. We also provide example code in Python for all Phidget devices.

If you are developing for Windows, keep reading. Otherwise, select your operating system to jump ahead:

Windows

If you haven't already, please visit the Windows page before you continue reading. There you will be instructed on how to properly set up your Windows machine so you can follow the guides below!

Install Phidget Python module for Windows

Before getting started with the guides below, ensure you have Python installed on your machine (both 2.7 and 3.6 are compatible with Phidgets). You will also need to download the Phidget Python module.

After unpacking the Phidget Python module, open the command prompt at folder location and enter the following command:

python setup.py install

This will build the module and install the Python module files into your site-packages directory.

Python install.png

Command line

Use our examples

One of the best ways to start programming with Phidgets is to use our example code as a guide. Before we get started, make sure you have read how to install the Phidget Python module section above.


Now that you have Python and the Phidget Python module installed, select an example that will work with your Phidget:


Open the command prompt at the location of the example and enter the following command:

python example.py


Python command run.png


You should now have the example up and running for your device. Play around with the device and experiment with some of the functionality. When you are ready, the next step is configuring your project and writing your own code!

Configure your project

When you are building a project from scratch, or adding Phidget functionality to an existing project, you'll need to configure your development environment to properly link the Phidget Java library.


To include the Phidget Python library, add the following line to your code:

from Phidget22.PhidgetException import *
from Phidget22.Phidget import *

Then, you will also have to add a reference to your particular Phidget. For example, you would include the following line for a DigitalInput:

from Phidget22.Devices.DigitalInput import *

You can now compile the file as shown in the previous section.


The project now has access to Phidgets. Next, view the write your own code section located below.

IDLE

Use our examples

One of the best ways to start programming with Phidgets is to use our example code as a guide. Before we get started, make sure you have read how to install the Phidget Python module section above.


Now that you have Python and the Phidget Python module installed, select an example that will work with your Phidget:


Right-click on the example and open it in IDLE:

Python idle open.png


To run the example, simply click on Run and select Run Module:

Python idle run.png


You should now have the example up and running for your device. Play around with the device and experiment with some of the functionality. When you are ready, the next step is configuring your project and writing your own code!

Configure your project

When you are building a project from scratch, or adding Phidget functionality to an existing project, you'll need to configure your development environment to properly link the Phidget Java library.


To include the Phidget Python library, add the following line to your code:

from Phidget22.PhidgetException import *
from Phidget22.Phidget import *

Then, you will also have to add a reference to your particular Phidget. For example, you would include the following line for a DigitalInput:

from Phidget22.Devices.DigitalInput import *

You can now compile the file as shown in the previous section.


The project now has access to Phidgets. Next, view the write your own code section located below.

Visual Studio

Use our examples

One of the best ways to start programming with Phidgets is to use our example code as a guide. Before we get started, make sure you have read how to install the Phidget Python module section above. You will also need to download Microsoft Visual Studio if you have not already.

Now that you have Python and the Phidget Python module installed, as well as Visual Studio, select an example that will work with your Phidget:


Next, create a new Python project:

Python vs newproject.PNG


Delete the Python file that was generated with the project:

Python vs delete.png


Add the example you just downloaded by right-clicking on the project and adding an existing item:

Python vs addexisting.png


Select the example as the startup file:

Python vs startupproject.png


Ensure that your Python environment is the same as the version you have installed. Enter the following command to view your Python version if you are unsure:

python -V
Python version.PNG


You can view/edit your Python environment under the Python Environments tab:

Python vs environment.png


You should now have the example up and running for your device. Play around with the device and experiment with some of the functionality. When you are ready, the next step is configuring your project and writing your own code!

Configure your project

When you are building a project from scratch, or adding Phidget functionality to an existing project, you'll need to configure your development environment to properly link the Phidget Java library.


To include the Phidget Python library, add the following line to your code:

from Phidget22.PhidgetException import *
from Phidget22.Phidget import *

Then, you will also have to add a reference to your particular Phidget. For example, you would include the following line for a DigitalInput:

from Phidget22.Devices.DigitalInput import *

You can now create your project as shown in the previous section.


The project now has access to Phidgets. Next, view the write your own code section located below.

LiClipse

Use our examples

One of the best ways to start programming with Phidgets is to use our example code as a guide. Before we get started, make sure you have read how to install the Phidget Python module section above. You will also need to download LiClipse if you have not already.

Now that you have Python and the Phidget Python module installed, as well as LiClipse, select an example that will work with your Phidget:


Next, create a new Python project:

Python liclipse newproject.PNG


Add the example you just downloaded by dragging it into the project:

Python liclipse import.png


Finally, run the project:

Python liclipse run.png


You should now have the example up and running for your device. Play around with the device and experiment with some of the functionality. When you are ready, the next step is configuring your project and writing your own code!

Configure your project

When you are building a project from scratch, or adding Phidget functionality to an existing project, you'll need to configure your development environment to properly link the Phidget Java library.


To include the Phidget Python library, add the following line to your code:

from Phidget22.PhidgetException import *
from Phidget22.Phidget import *

Then, you will also have to add a reference to your particular Phidget. For example, you would include the following line for a DigitalInput:

from Phidget22.Devices.DigitalInput import *

You can now create your project as shown in the previous section.


The project now has access to Phidgets. Next, view the write your own code section located below.

macOS

If you haven't already, please visit the macOS page before you continue reading. There you will be instructed on how to properly set up your macOS machine so you can follow the guides below!

Install Phidget Python module for macOS

Before getting started with the guides below, ensure you have Python installed on your machine (both 2.7 and 3.6 are compatible with Phidgets). You will also need to download the Phidget Python module.

After unpacking the Phidget Python module, open the terminal at folder location and enter the following command:

python setup.py install

This will build the module and install the Python module files into your site-packages directory.

Python mac install.png

Terminal

Use our examples

One of the best ways to start programming with Phidgets is to use our example code as a guide. Before we get started, make sure you have read how to install the Phidget Python module section above.


Now that you have Python and the Phidget Python module installed, select an example that will work with your Phidget:


Open the terminal at the location of the example and enter the following command:

python example.py


Python mac terminal run.png


You should now have the example up and running for your device. Play around with the device and experiment with some of the functionality. When you are ready, the next step is configuring your project and writing your own code!

When you are building a project from scratch, or adding Phidget functionality to an existing project, you'll need to configure your development environment to properly link the Phidget Java library.


To include the Phidget Python library, add the following line to your code:

from Phidget22.PhidgetException import *
from Phidget22.Phidget import *

Then, you will also have to add a reference to your particular Phidget. For example, you would include the following line for a DigitalInput:

from Phidget22.Devices.DigitalInput import *

You can now compile the file as shown in the previous section.


The project now has access to Phidgets. Next, view the write your own code section located below.

Linux

If you haven't already, please visit the Linux page before you continue reading. There you will be instructed on how to properly set up your Linux machine so you can follow the guides below!

Install Phidget Python module for Linux

Before getting started with the guides below, ensure you have Python installed on your machine (both 2.7 and 3.6 are compatible with Phidgets).

You will also need to download the Phidget Python module.

After unpacking the Phidget Python module, open the terminal at folder location and enter the following command:

python setup.py install

This will build the module and install the Python module files into your site-packages directory.

Python linux install.PNG

Terminal

Use our examples

One of the best ways to start programming with Phidgets is to use our example code as a guide. Before we get started, make sure you have read how to install the Phidget Python module section above.


Now that you have Python and the Phidget Python module installed, select an example that will work with your Phidget:


Open the terminal at the location of the example and enter the following command:

python example.py


Python linux terminal run.png


You should now have the example up and running for your device. Play around with the device and experiment with some of the functionality. When you are ready, the next step is configuring your project and writing your own code!

Configure your project

When you are building a project from scratch, or adding Phidget functionality to an existing project, you'll need to configure your development environment to properly link the Phidget Java library.


To include the Phidget Python library, add the following line to your code:

from Phidget22.PhidgetException import *
from Phidget22.Phidget import *

Then, you will also have to add a reference to your particular Phidget. For example, you would include the following line for a DigitalInput:

from Phidget22.Devices.DigitalInput import *

You can now create your project as shown in the previous section.


The project now has access to Phidgets. Next, view the write your own code section located below.

Write Code

By following the instructions for your operating system and compiler above, you now have working examples and a project that is configured. This teaching section will help you understand how the examples were written so you can start writing your own code.


Remember: your main reference for writing {{{1}}} code will be the Phidget22 API Manual and the example code.

Step One: Initialize and Open

You will need to declare your Phidget object in your code. For example, we can declare a digital input object like this:

ch = DigitalInput()


Next, we can open the Phidget object like this:

ch.open()


Although we are not including it on this page, you should handle the return values of all Phidget functions. Here is an example of the previous code with error handling:

try:
  ch = DigitalInput()	
except RuntimeError as e:
  print("Runtime Error: %s" % e.message) 
try:
  ch.open()
except PhidgetException as e:
  print (Phidget Exception %i: %s % (e.code, e.details))


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

Simply calling open does not guarantee you can use the Phidget immediately. To use a Phidget, it must be plugged in (attached). We can handle this by using event driven programming and tracking the attach events. Alternatively, we can modify our code so we wait for an attachment:

ch = DigitalInput()	
ch.openWaitForAttachment(5000)

Waiting for attachment will block indefinitely until a connection is made, or until the timeout value is exceeded


To use events to handle attachments, we have to modify our code slightly:

ch = DigitalInput()	
ch.setOnAttachHandler(onAttachHandler)
ch.open()

Next, we have to declare the function that will be called when an attach event is fired - in this case the function OnAttachedHandler will be called:

def onAttachHandler(e):
    print("Phidget attached!")

Step Three: Do Things with the Phidget

We recommend the use of event driven programming when working with Phidgets. In a similar way to handling an attach event as described above, we can also add an event handler for a state change event:

ch = DigitalInput()	
ch.setOnAttachHandler(onAttachHandler)
ch.setOnStateChangeHandler(onStateChangeHandler)
ch.open()

This code will connect a function and an event. In this case, the onStateChangeHandler function will be called when there has been a change to the devices input. Next, we need to create the onStateChangeHandler function:

def onStateChangeHandler(e, state):
    print("State %f" % state)
    return 0


If events do not suit your needs, you can also poll the device directly for data using code like this:

state = ch.getState()
print("State %f" % state)

Step Four: Close and Delete

At the end of your program, be sure to close and delete your device:

ch.close()

Further Reading

Phidget Programming Basics - Here you can find the basic concepts to help you get started with making your own programs that use Phidgets.

Data Interval/Change Trigger - Learn about these two properties that control how much data comes in from your sensors.

Using Multiple Phidgets - It can be difficult to figure out how to use more than one Phidget in your program. This page will guide you through the steps.

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.