0

I have a Phidgets differential pressure sensor device connected to Python and used a template code to output the pressure. I've got it to work and it's outputting pressure values into the console. However, I'm looking to graph the output values and make a linear plot vs. time. Does anyone know how to do this? I've attached the code I'm using.

from Phidget22.Phidget import *
from Phidget22.Devices.VoltageRatioInput import *
import time

def onSensorChange(self, sensorValue, sensorUnit):
    print("SensorValue: " + str(sensorValue))

def main():
    voltageRatioInput4 = VoltageRatioInput()

    voltageRatioInput4.setChannel(4)

    voltageRatioInput4.setOnSensorChangeHandler(onSensorChange)

    voltageRatioInput4.openWaitForAttachment(5000)

    voltageRatioInput4.setSensorType(VoltageRatioSensorType.SENSOR_TYPE_1139)

    try:
        input("Press Enter to Stop\n")
    except (Exception, KeyboardInterrupt):
        pass

    voltageRatioInput4.close()

main()

It's outputting sensorValue!

SensorValue: 0.223

That's what I want. However, it's not saving it into some form of variable so that I can plot it against time. Any attempts to get the value results in

NameError: name 'sensorValue' is not defined

Does anyone know how to get the values from sensorValue into an array variable?

Always lurked around stackoverflow when I had MATLAB homework. Found my way back here needing help again for Python homework, hehe. Any help is appreciated!

  • I wanted to throw some advice here, but since I do not have a "complete" answer (with code) I'll stick to a Comment. Break this problem into two scripts: 1) recording the data, and 2) importing that data into a plotting system. For the first script, you can write out, OR aggregate it per unit of time (minute) - up to you. Once you do this, you can have some vary generic python code that reads from a file and plots that data. Keeping these domains apart will make for cleaner code and easier maintenance. – Scott Prive Mar 10 '20 at 17:04

1 Answers1

0

You should use some variable to keep the history. Since variables created inside function exsists only inside the function - you can use variable from outside, using global.

...

history = []

def onSensorChange(self, sensorValue, sensorUnit):
    global history
    history.append( sensorValue )
    print("SensorValue: " + str(sensorValue))
    print("History of values: ", history)

...

Look how history changes when onSensorChange function is called.

  • 1
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Mar 10 '20 at 09:49
  • Thanks! It looked like learning "global" and "append" were the key functions. – Christian Alarcon Mar 11 '20 at 16:10