A simple readout from the 1136 Diffrential Pressure Sensor

Supporting 2.7 and 3.2+
Post Reply
DarkLight
Phidgetsian
Posts: 12
Joined: Wed Dec 27, 2017 6:59 am
Contact:

A simple readout from the 1136 Diffrential Pressure Sensor

Post by DarkLight »

Hi,

I wish to read the differential pressure (in Pa) from the 1136_0 https://www.phidgets.com/?tier=3&catid= ... prodid=109

The example given is too generic and only gives the voltage output, after a long array of questions...

Code: Select all

import sys
import time
import traceback
from Phidget22.Devices.VoltageRatioInput import *
from Phidget22.PhidgetException import *
from Phidget22.Phidget import *
from Phidget22.Net import *

try:
    from PhidgetHelperFunctions import *
except ImportError:
    sys.stderr.write("\nCould not find PhidgetHelperFunctions. Either add PhdiegtHelperFunctions.py to your project folder "
                     "or remove the import from your project.")
    sys.stderr.write("\nPress ENTER to end program.")
    readin = sys.stdin.readline()
    sys.exit()

"""
* Configures the device's DataInterval and ChangeTrigger.
* Displays info about the attached phidget channel.
* Fired when a Phidget channel with onAttachHandler registered attaches
*
* @param self The Phidget channel that fired the attach event
"""
def onAttachHandler(self):



    ph = self
    try:
        #If you are unsure how to use more than one Phidget channel with this event, we recommend going to
        #www.phidgets.com/docs/Using_Multiple_Phidgets for information
        
        print("\nAttach Event:")
        
        """
        * Get device information and display it.
        """
        channelClassName = ph.getChannelClassName()
        serialNumber = ph.getDeviceSerialNumber()
        channel = ph.getChannel()
        if(ph.getDeviceClass() == DeviceClass.PHIDCLASS_VINT):
            hubPort = ph.getHubPort()
            print("\n\t-> Channel Class: " + channelClassName + "\n\t-> Serial Number: " + str(serialNumber) +
                "\n\t-> Hub Port: " + str(hubPort) + "\n\t-> Channel " + str(channel) + "\n")
        else:
            print("\n\t-> Channel Class: " + channelClassName + "\n\t-> Serial Number: " + str(serialNumber) +
                    "\n\t-> Channel " + str(channel) + "\n")
    
        """
        * Set the DataInterval inside of the attach handler to initialize the device with this value.
        * DataInterval defines the minimum time between VoltageRatioChange events.
        * DataInterval can be set to any value from MinDataInterval to MaxDataInterval.
        """
        print("\n\tSetting DataInterval to 1000ms")
        ph.setDataInterval(1000)

        """
        * Set the VoltageRatioChangeTrigger inside of the attach handler to initialize the device with this value.
        * VoltageRatioChangeTrigger will affect the frequency of VoltageRatioChange events, by limiting them to only occur when
        * the voltage ratio changes by at least the value set.
        """
        print("\tSetting Voltage Ratio ChangeTrigger to 0.0")
        ph.setVoltageRatioChangeTrigger(0.0)
        
        """
        * Set the SensorType inside of the attach handler to initialize the device with this value.
        * You can find the appropriate SensorType for your sensor in its User Guide and the VoltageRatioInput API
        * SensorType will apply the appropriate calculations to the voltage ratio reported by the device
        * to convert it to the sensor's units.
        * SensorType can only be set for Sensor Port voltage ratio inputs (VINT Ports and Analog Input Ports)
        """
        if(ph.getChannelSubclass() == ChannelSubclass.PHIDCHSUBCLASS_VOLTAGERATIOINPUT_SENSOR_PORT):
            print("\tSetting VoltageRatio SensorType")
            ph.setSensorType(VoltageRatioSensorType.SENSOR_TYPE_VOLTAGERATIO)
            
        
    except PhidgetException as e:
        print("\nError in Attach Event:")
        DisplayError(e)
        traceback.print_exc()
        return

"""
* Displays info about the detached phidget channel.
* Fired when a Phidget channel with onDetachHandler registered detaches
*
* @param self The Phidget channel that fired the attach event
"""
def onDetachHandler(self):

    ph = self

    try:
        #If you are unsure how to use more than one Phidget channel with this event, we recommend going to
        #www.phidgets.com/docs/Using_Multiple_Phidgets for information
        
        print("\nDetach Event:")
        
        """
        * Get device information and display it.
        """
        channelClassName = ph.getChannelClassName()
        serialNumber = ph.getDeviceSerialNumber()
        channel = ph.getChannel()
        if(ph.getDeviceClass() == DeviceClass.PHIDCLASS_VINT):
            hubPort = ph.getHubPort()
            print("\n\t-> Channel Class: " + channelClassName + "\n\t-> Serial Number: " + str(serialNumber) +
                "\n\t-> Hub Port: " + str(hubPort) + "\n\t-> Channel " + str(channel) + "\n")
        else:
            print("\n\t-> Channel Class: " + channelClassName + "\n\t-> Serial Number: " + str(serialNumber) +
                    "\n\t-> Channel " + str(channel) + "\n")
        
    except PhidgetException as e:
        print("\nError in Detach Event:")
        DisplayError(e)
        traceback.print_exc()
        return


"""
* Writes phidget error info to stderr.
* Fired when a Phidget channel with onErrorHandler registered encounters an error in the library
*
* @param self The Phidget channel that fired the attach event
* @param errorCode the code associated with the error of enum type ph.ErrorEventCode
* @param errorString string containing the description of the error fired
"""
def onErrorHandler(self, errorCode, errorString):

    sys.stderr.write("[Phidget Error Event] -> " + errorString + " (" + str(errorCode) + ")\n")

"""
* Outputs the VoltageRatioInput's most recently reported voltage ratio.
* Fired when a VoltageRatioInput channel with onVoltageRatioChangeHandler registered meets DataInterval and ChangeTrigger criteria
*
* @param self The VoltageRatioInput channel that fired the VoltageRatioChange event
* @param voltageRatio The reported voltage ratio from the VoltageRatioInput channel
"""
def onVoltageRatioChangeHandler(self, voltageRatio):

    #If you are unsure how to use more than one Phidget channel with this event, we recommend going to
    #www.phidgets.com/docs/Using_Multiple_Phidgets for information

    print("[VoltageRatio Event] -> Voltage Ratio: " + str(voltageRatio))

"""
* Outputs the VoltageRatioInput's most recently reported sensor value.
* Fired when a VoltageRatioInput channel with onSensorChangeHandler registered meets DataInterval and ChangeTrigger criteria
*
* @param self The VoltageRatioInput channel that fired the SensorChange event
* @param sensorValue The reported sensor value from the VoltageRatioInput channel
"""
def onSensorChangeHandler(self, sensorValue, sensorUnit):

    #If you are unsure how to use more than one Phidget channel with this event, we recommend going to
    #www.phidgets.com/docs/Using_Multiple_Phidgets for information

    print("[Sensor Event] -> Sensor Value: " + str(sensorValue) + sensorUnit.symbol)


"""
* Prints descriptions of how events related to this class work
"""
def PrintEventDescriptions():

    print("\n--------------------\n"
        "\n  | Voltage Ratio change events will call their associated function every time new voltage ratio data is received from the device.\n"
        "  | The rate of these events can be set by adjusting the DataInterval for the channel.\n")
        
    print(
        "\n  | Sensor change events contain the most recent sensor value received from the device.\n"
        "  | Sensor change events will occur instead of Voltage Ratio change events if the SensorType is changed from the default.\n"
        "  | Press ENTER once you have read this message.")
    readin = sys.stdin.readline(1)
    
    print("\n--------------------")
   
"""
* Creates, configures, and opens a VoltageRatioInput channel.
* Displays Voltage Ratio events for 10 seconds
* Closes out VoltageRatioInput channel
*
* @return 0 if the program exits successfully, 1 if it exits with errors.
"""
def main():
    try:
        """
        * Allocate a new Phidget Channel object
        """
        try:
            ch = VoltageRatioInput()
        except PhidgetException as e:
            sys.stderr.write("Runtime Error -> Creating VoltageRatioInput: \n\t")
            DisplayError(e)
            raise
        except RuntimeError as e:
            sys.stderr.write("Runtime Error -> Creating VoltageRatioInput: \n\t" + e)
            raise

        """
        * Set matching parameters to specify which channel to open
        """
        
        #You may remove this line and hard-code the addressing parameters to fit your application
        #channelInfo = AskForDeviceParameters(ch)
        
        ch.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch.setHubPort(channelInfo.hubPort)
        ch.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch.setChannel(channelInfo.channel)
        
        if(channelInfo.netInfo.isRemote):
            ch.setIsRemote(channelInfo.netInfo.isRemote)
            if(channelInfo.netInfo.serverDiscovery):
                try:
                    Net.enableServerDiscovery(PhidgetServerType.PHIDGETSERVER_DEVICEREMOTE)
                except PhidgetException as e:
                    PrintEnableServerDiscoveryErrorMessage(e)
                    raise EndProgramSignal("Program Terminated: EnableServerDiscovery Failed")
            else:
                Net.addServer("Server", channelInfo.netInfo.hostname,
                    channelInfo.netInfo.port, channelInfo.netInfo.password, 0)
        
        """
        * Add event handlers before calling open so that no events are missed.
        """
        print("\n--------------------------------------")
        print("\nSetting OnAttachHandler...")
        ch.setOnAttachHandler(onAttachHandler)
        
        print("Setting OnDetachHandler...")
        ch.setOnDetachHandler(onDetachHandler)
        
        print("Setting OnErrorHandler...")
        ch.setOnErrorHandler(onErrorHandler)
        
        #This call may be harmlessly removed
        PrintEventDescriptions()
        
        print("\nSetting OnVoltageRatioChangeHandler...")
        ch.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)
        
        print("\nSetting OnSensorChangeHandler...")
        ch.setOnSensorChangeHandler(onSensorChangeHandler)
        
        """
        * Open the channel with a timeout
        """
        
        print("\nOpening and Waiting for Attachment...")
        
        try:
            ch.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch)
            raise EndProgramSignal("Program Terminated: Open Failed")
        
        print("Sampling data for 10 seconds...")
        
        print("You can do stuff with your Phidgets here and/or in the event handlers.")
        
        time.sleep(10)
        
        """
        * Perform clean up and exit
        """

        #clear the VoltageRatioChange event handler 
        ch.setOnVoltageRatioChangeHandler(None)  
        #clear the SensorChange event handler
        ch.setOnSensorChangeHandler(None)
        
        print("\nDone Sampling...")

        print("Cleaning up...")
        ch.close()
        print("\nExiting...")
        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        traceback.print_exc()
        print("Cleaning up...")
        ch.setOnVoltageRatioChangeHandler(None)
        ch.setOnSensorChangeHandler(None)
        ch.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        ch.setOnVoltageRatioChangeHandler(None)
        ch.setOnSensorChangeHandler(None)
        ch.close()
        return 1
    finally:
        print("Press ENTER to end program.")
        readin = sys.stdin.readline()

main()

Any ideas?
DarkLight
Phidgetsian
Posts: 12
Joined: Wed Dec 27, 2017 6:59 am
Contact:

Re: A simple readout from the 1136 Diffrential Pressure Sensor

Post by DarkLight »

I did not find a simple, single read solution.
yet, the following was good enough - aggregate a few seconds of results, calculate PA, min, max, mean - done.

Please notice - this solution is based on a single vint hub. The 1136_0 is connected to port 1. Unlike "smarter" sensors, this one cannot be auto-detected - one must hardcode the port number.

Code: Select all

from time import sleep
import sys
from Phidget22.Devices.VoltageRatioInput import *

PresArray = []

def VoltageRatioChangeHandler(e, voltageRatio):
    # print("VoltageRatio: %f" % voltageRatio)
    # print("SensorValue: %f" % cp.getSensorValue())

    pressure = 1000 * ((5 * cp.getSensorValue()) - 2.5)
    PresArray.append(pressure)
    # print ("Pressure in PA: %f" % pressure)



cp = VoltageRatioInput()
cp.setDeviceSerialNumber(-1)
cp.setHubPort(1)
cp.setIsHubPortDevice(1)
cp.setChannel(0)

cp.setOnVoltageRatioChangeHandler(VoltageRatioChangeHandler)
cp.openWaitForAttachment(5000)
cp.setDataInterval(100)

"""
* set the sleep time (e.g. 2 seconds) and/or the data interval (e.g. 100 msec) to change the aggrgated list of readings
* change the pressure formula (for PA it's 1000 * ((5 * cp.getSensorValue()) - 2.5) for psi it's (psi)=(0.725 * cp.getSensorValue())−0.3625
"""

sleep(2)

print ("Max PA: %f" % max(PresArray))
print ("Avg PA: %f" % (sum(PresArray)/len(PresArray)))
print ("Min PA: %f" % min(PresArray))

cp.close()
fraser
Engineering
Posts: 138
Joined: Thu Nov 19, 2009 4:41 pm
Contact:

Re: A simple readout from the 1136 Diffrential Pressure Sensor

Post by fraser »

For this product you can also use setOnSensorChangeHandler instead of VoltageRatioHandler. Then by using setSensorType(SENSOR_TYPE_1136), it will perform the calculation for you and give it directly to the SensorChangeHandler
jdecoux
Labview Developer
Posts: 179
Joined: Mon Nov 13, 2017 10:20 am
Contact:

Re: A simple readout from the 1136 Diffrential Pressure Sensor

Post by jdecoux »

To read the value from the sensor once you can call getVoltageRatio() or getSensorValue() to get the latest reported values from the sensor. You will need to wait for a short period of time after opening the sensor until the first data is available from the sensor.

And more specifically to Python, to set up your program to automatically calculate the sensor value, you can call:

Code: Select all

setSensorType(VoltageRatioSensorType.SENSOR_TYPE_1136)
To see a full list of functionality available to your device, you can check the Phidget API and select your programming language and device from the drop down menus.
DarkLight
Phidgetsian
Posts: 12
Joined: Wed Dec 27, 2017 6:59 am
Contact:

Re: A simple readout from the 1136 Diffrential Pressure Sensor

Post by DarkLight »

Dear fraser,jdecoux

can you, please, send the code of your above mentioned examples?
It may seem obvious to you, but less experienced users (ahm, i.e. me) sometimes miss stupid pitfalls...
jdecoux
Labview Developer
Posts: 179
Joined: Mon Nov 13, 2017 10:20 am
Contact:

Re: A simple readout from the 1136 Diffrential Pressure Sensor

Post by jdecoux »

The following code will get a single sensor value from an 1136 Diffrential Pressure Sensor in kPa.

Code: Select all

import sys
import time
import traceback
from Phidget22.Devices.VoltageRatioInput import *
from Phidget22.PhidgetException import *
from Phidget22.Phidget import *

   
def main():
    try:
        ch = VoltageRatioInput()

        #Address the sensor
        ch.setHubPort(0)
        ch.setIsHubPortDevice(True)
    
        #Open the sensor and wait until it's attached
        ch.openWaitForAttachment(5000)
                
        #Set the sensor type. This could also be done in an onAttachedHandler.
        ch.setSensorType(VoltageRatioSensorType.SENSOR_TYPE_1136)
        
        #wait for the first data to become available
        #there are more elegant ways of doing this, but this is the simplest
        time.sleep(0.5)
        
        #Get the sensor data
        sensorValue = ch.getSensorValue()
        sensorUnit = ch.getSensorUnit()
        
        print("Sensor Value: " + str(sensorValue) + sensorUnit.symbol)
        
        #close and clean up
        ch.close()
        print("\nExiting...")
        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        sys.stderr.write(e.details + "\n")
        traceback.print_exc()
        print("Cleaning up...")
        ch.close()
        return 1
    finally:
        print("Press ENTER to end program.")
        readin = sys.stdin.readline()

main()

If the sleep solution isn't good enough, you can add an onSensorChangeHandler, and use it to set a flag indicating that data has been received from the sensor. You can then have your main code wait until that flag has been set before reading the sensor value.
DarkLight
Phidgetsian
Posts: 12
Joined: Wed Dec 27, 2017 6:59 am
Contact:

Re: A simple readout from the 1136 Diffrential Pressure Sensor

Post by DarkLight »

Thank you!
Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests