Beispiel #1
0
class StrainSensor(Sensor):
    '''Class used to handle load cell type sensors. Extends Sensor class '''
    def __init__(self,
                 deviceSN,
                 channelNo,
                 dataInterval,
                 refreshPeriod,
                 sensorName=None):
        '''
        Constructor for strain sensor phidgets. Takes standard Sensor arguments
        '''
        self.channelNo = channelNo
        self.sensorUnits = "Kg"
        self.useCallibration = False
        self.gradient = 1
        self.intercept = 0
        Sensor.__init__(self, deviceSN, dataInterval, refreshPeriod,
                        sensorName)

    def attachSensor(self):
        '''
        Connects the strain sensor to the application
        '''
        self.channel = VoltageRatioInput()
        self.channel.setDeviceSerialNumber(self.deviceSN)
        self.channel.setChannel(self.channelNo)
        self.channel.openWaitForAttachment(100)
        print("\n***** {} Sensor Attached *****".format(self.sensorName))
        self.attached = True
        self.channel.setDataInterval(self.dataInterval)
        self.channel.setBridgeGain(0x8)

    def activateDataListener(self):
        '''
        Sets up the event which triggers when the sensor updates its utput values
        '''
        self.startTime = time.time()

        def onSensorValueChange(channelObject, voltageRatio):
            rawTime = time.time()
            deltaTime = rawTime - self.startTime
            if self.useCallibration:
                voltageRatio = voltageRatio * self.gradient + self.intercept
            self.dataQ.put([voltageRatio, deltaTime, rawTime])

        self.channel.setOnVoltageRatioChangeHandler(onSensorValueChange)

    def setCallibration(self, gradient, intercept):
        '''
        Used to give the sensor callibration values.
        '''
        self.gradient = gradient
        self.intercept = intercept
        self.useCallibration = True
Beispiel #2
0
class VoltageRatioSensor(Sensor):
    '''Class used to handle any sensor which uses a ratiometric voltage input '''
    def __init__(self,
                 deviceSN,
                 channelNo,
                 dataInterval,
                 refreshPeriod,
                 sensorType,
                 sensorName=None):
        '''
        Connects the sensor to the application
        '''
        self.channelNo = channelNo
        self.sensorType = sensorType
        self.sensorUnits = None
        Sensor.__init__(self, deviceSN, dataInterval, refreshPeriod,
                        sensorName)

    def attachSensor(self):
        '''
        Connects the sensor to the application
        '''
        self.channel = VoltageRatioInput()
        self.channel.setDeviceSerialNumber(self.deviceSN)
        self.channel.setChannel(self.channelNo)
        self.channel.openWaitForAttachment(100)
        print("\n***** {} Sensor Attached *****".format(self.sensorName))
        self.attached = True
        self.channel.setSensorType(self.sensorType)
        self.channel.setDataInterval(self.dataInterval)
        self.sensorUnits = self.channel.getSensorUnit().symbol

    def activateDataListener(self):
        '''
        Sets up the event which triggers when the sensor updates its outputs
        '''
        self.startTime = time.time()

        def onSensorValueChange(channelObject, sensorVlue, sensorUnit):
            rawTime = time.time()
            deltaTime = rawTime - self.startTime
            self.dataQ.put(
                [channelObject.getSensorValue(), deltaTime, rawTime])

        self.channel.setOnSensorChangeHandler(onSensorValueChange)
def aids():
    voltageRatioInput0 = VoltageRatioInput()
    voltageRatioInput1 = VoltageRatioInput()

    voltageRatioInput0.setChannel(0)
    voltageRatioInput1.setChannel(1)

    voltageRatioInput0.setOnVoltageRatioChangeHandler(onVoltageRatioChange)
    voltageRatioInput1.setOnVoltageRatioChangeHandler(onVoltageRatioChange)

    voltageRatioInput0.openWaitForAttachment(5000000)
    voltageRatioInput1.openWaitForAttachment(5000000)

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

    voltageRatioInput0.close()
    voltageRatioInput1.close()
Beispiel #4
0
def main():
    ir_reflective_sensor = VoltageRatioInput()
    ir_reflective_sensor.setChannel(5)
    ir_reflective_sensor.setOnSensorChangeHandler(on_ir_change)
    ir_reflective_sensor.openWaitForAttachment(5000)
    ir_reflective_sensor.setSensorType(VoltageRatioSensorType.SENSOR_TYPE_1103)

    sharp_distance_sensor_left = VoltageRatioInput()
    sharp_distance_sensor_left.setChannel(6)
    sharp_distance_sensor_left.setOnSensorChangeHandler(on_sharp_change)
    sharp_distance_sensor_left.openWaitForAttachment(5000)
    sharp_distance_sensor_left.setSensorType(
        VoltageRatioSensorType.SENSOR_TYPE_1101_SHARP_2Y0A21)

    sharp_distance_sensor_right = VoltageRatioInput()
    sharp_distance_sensor_right.setChannel(7)
    sharp_distance_sensor_right.setOnSensorChangeHandler(on_sharp_change)
    sharp_distance_sensor_right.openWaitForAttachment(5000)
    sharp_distance_sensor_right.setSensorType(
        VoltageRatioSensorType.SENSOR_TYPE_1101_SHARP_2Y0A21)

    while True:
        pass

    ir_reflective_sensor.close()
    sharp_distance_sensor_left.close()
    sharp_distance_sensor_right.close()
Beispiel #5
0
class jigCurrent(object):
    '''current sensor'''

    def __init__(self, provider, channel):
        self.ai = VoltageRatioInput()
        self.ai.setDeviceSerialNumber(provider)
        self.ai.setChannel(channel)
        self.ai.setOnAttachHandler(self._attached)
        self.ai.openWaitForAttachment(1000)

    def _attached(self, event):
        self.ai.setSensorType(VoltageRatioSensorType.SENSOR_TYPE_1122_DC)
        self.ai.setDataInterval(100)
        self.ai.setVoltageRatioChangeTrigger(0)

    @property
    def current(self):
        return self.ai.getSensorValue()

    @property
    def unitInfo(self):
        return self.ai.getSensorUnit()
Beispiel #6
0
pan.openWaitForAttachment(1000)
pan.setAcceleration(ACCEL)

#Setup Pnematics
pressure_ctrl = VoltageOutput()
pressure_ctrl.setDeviceSerialNumber(540047)
pressure_ctrl.setIsHubPortDevice(False)
pressure_ctrl.setHubPort(3)
pressure_ctrl.setChannel(0)
pressure_ctrl.openWaitForAttachment(5000)

pressure_reading = VoltageRatioInput()
pressure_reading.setDeviceSerialNumber(540047)
pressure_reading.setIsHubPortDevice(False)
pressure_reading.setHubPort(0)
pressure_reading.setChannel(0)
pressure_reading.openWaitForAttachment(5000)

solenoid = DigitalOutput()
solenoid.setDeviceSerialNumber(540047)
solenoid.setIsHubPortDevice(False)
solenoid.setHubPort(4)
solenoid.setChannel(3)
solenoid.openWaitForAttachment(5000)

root = Tk()

pressure = IntVar()

power_btn = Button(root, text="PWR", font="Courier, 12", command=toggle_power)
near = Button(root, text="NEAR", font="Courier, 12", width=7)
Beispiel #7
0
class PneumaticFrame2:
    def __init__(self, master, initial_name, top_name, color, sol, reg_pwr,
                 reg_set, reg_get, PSI):
        self.frame = Frame(master, borderwidth=2, relief=SUNKEN, bg=color)
        self.frame.pack()
        self.master = master
        self.frame_name = StringVar()
        self.frame_name.set(initial_name)
        self.state = 0
        self.fontType = "Comic Sans"
        self.activeColor = 'SpringGreen4'
        self.frameColor = color

        self.pressure = IntVar()
        self.lock_flag = IntVar()
        self.pressure.set("")

        self.power = Button(self.frame,
                            text="PWR",
                            activebackground=self.activeColor,
                            command=lambda: self.toggle_pwr())
        self.set_label = Button(self.frame,
                                text="SET LABEL",
                                font=(self.fontType, 7),
                                command=lambda: self.get_label_input())
        self.observed_pressure = Entry(self.frame,
                                       width=5,
                                       state="readonly",
                                       textvariable=self.pressure)
        if self.frame_name.get() == "Hydro":
            self.set_pressure_scale = Scale(self.frame,
                                            orient=HORIZONTAL,
                                            from_=0,
                                            to=92,
                                            resolution=0.5,
                                            bg=color,
                                            label="Set Pressure (PSI)",
                                            highlightthickness=0,
                                            command=self.set_pressure)
        else:
            self.set_pressure_scale = Scale(self.frame,
                                            orient=HORIZONTAL,
                                            from_=0,
                                            to=50,
                                            resolution=0.5,
                                            bg=color,
                                            label="Set Pressure (PSI)",
                                            highlightthickness=0,
                                            command=self.set_pressure)
        self.custom_label = Label(self.frame,
                                  textvariable=self.frame_name,
                                  font=(self.fontType, 14),
                                  bg=color)
        self.label = Label(self.frame, text=initial_name, bg=color)
        self.lock = Checkbutton(self.frame,
                                text="LOCK",
                                bg=color,
                                variable=self.lock_flag,
                                command=self.lock)
        self.frame_name.set(top_name)

        # Init the pressure scale to the default value.
        self.set_pressure_scale.set(PSI)
        # Lock hydo at startup
        if initial_name == "Hydro":
            self.lock.select()
            self.set_pressure_scale.config(state="disabled")
            self.power.config(state="disable")

        self.frame.rowconfigure(0, minsize=30)
        self.custom_label.grid(row=0, column=0, columnspan=2, sticky=S)
        self.set_label.grid(column=0, row=1, columnspan=2)
        self.frame.rowconfigure(2, minsize=50)
        self.power.grid(column=0, row=2)
        self.observed_pressure.grid(column=1, row=2)
        self.set_pressure_scale.grid(column=0, row=3, columnspan=2, padx=20)
        self.frame.rowconfigure(4, minsize=5)
        self.label.grid(column=0, row=5)
        self.lock.grid(column=1, row=5)

        # Connect to Phidget Solid State Relay for solinoid control
        if self.frame_name.get() == "Hydro":
            self.solenoid_switch = DigitalOutput()
            self.solenoid_switch.setDeviceSerialNumber(sol[0])
            self.solenoid_switch.setIsHubPortDevice(False)
            self.solenoid_switch.setHubPort(sol[1])
            self.solenoid_switch.setChannel(sol[2])
            self.solenoid_switch.openWaitForAttachment(5000)

        #Connect to Phidget Solid State Relay for regulator power control
        self.reg_switch = DigitalOutput()
        self.reg_switch.setDeviceSerialNumber(reg_pwr[0])
        self.reg_switch.setIsHubPortDevice(False)
        self.reg_switch.setHubPort(reg_pwr[1])
        self.reg_switch.setChannel(reg_pwr[2])
        self.reg_switch.openWaitForAttachment(5000)

        #Connect to Phidget Voltage Ouptut for pressure control
        self.pressure_ctrl = VoltageOutput()
        self.pressure_ctrl.setDeviceSerialNumber(reg_set[0])
        self.pressure_ctrl.setIsHubPortDevice(False)
        self.pressure_ctrl.setHubPort(reg_set[1])
        self.pressure_ctrl.setChannel(reg_set[2])
        self.pressure_ctrl.openWaitForAttachment(5000)

        #Connect to Phidget Analog Input for pressure reading
        self.pressure_reading = VoltageRatioInput()
        self.pressure_reading.setDeviceSerialNumber(reg_get[0])

        #One of the VINT Hubs on the SBC is used and needs special configuration
        if reg_get[0] == SBCH:
            self.pressure_reading.setIsHubPortDevice(True)
            self.pressure_reading.setHubPort(0)

        self.pressure_reading.setChannel(reg_get[1])
        self.pressure_reading.openWaitForAttachment(5000)

    def toggle_pwr(self):
        #Turn on air channel
        if self.state == 0:
            #Turn on power to regulator and show active button color
            self.power.config(bg=self.activeColor)
            self.reg_switch.setState(True)
            if self.frame_name.get() == "Hydro":
                self.solenoid_switch.setState(True)

            #Start monitoring air pressure
            self.update_pressure()

            #Change state of air channel
            self.state = 1

        #Turn off air channel
        elif self.state == 1:
            remember_state = self.set_pressure_scale.get()
            if self.frame_name.get() != "Hydro":
                messagebox.showinfo(
                    self.frame_name.get() + " Warning",
                    "Pressure will be set to zero. Acknowledge that " +
                    self.frame_name.get() + " is in a safe configuration")

            # Change pressure to zero
            self.set_pressure_scale.set(0)
            self.set_pressure(0)
            time.sleep(0.5)
            self.frame.update()
            self.reg_switch.setState(False)
            time.sleep(0.5)
            self.set_pressure_scale.set(remember_state)
            if self.frame_name.get() == "Hydro":
                self.solenoid_switch.setState(False)
                self.lock.select()
                self.set_pressure_scale.config(state="disabled")
                self.power.config(state="disable")

            #Turn off power to reguluator and remove active button color
            self.power.config(bg="SystemButtonFace")

            #Update air channel state
            self.state = 0

    def get_label_input(self):
        self.window = popupWindow(self.master)
        self.set_label.config(state=DISABLED)
        self.master.wait_window(self.window.top)
        self.set_label.config(state=NORMAL)

        #If the user does not enter a value exception will be produced
        try:
            if len(self.window.value) > 12:
                self.frame_name.set("SET ERROR")
            else:
                self.frame_name.set(self.window.value)
        except:
            self.frame_name.set("SET ERROR")

    def set_pressure(self, val):
        # Pressure Range
        range = MAXPR - MINPR
        # Calculate volts/PSI
        ratio = 5 / range
        self.pressure_ctrl.setVoltage(float(val) * ratio)

    def update_pressure(self):
        if self.reg_switch.getState():
            try:
                val = float(self.pressure_reading.getSensorValue())
                PSI = val * 165.63 - 30.855
                PSI = round(PSI, 2)
                self.pressure.set(PSI)
                #Low pressure check
                if PSI < (self.set_pressure_scale.get() - 3):
                    if self.frame.cget('bg') == "Red":
                        self.frame.config(bg=self.frameColor)
                        self.set_pressure_scale.config(bg=self.frameColor)
                        self.custom_label.config(bg=self.frameColor)
                        self.label.config(bg=self.frameColor)
                        self.lock.config(bg=self.frameColor)
                    else:
                        self.frame.config(bg='Red')
                        self.set_pressure_scale.config(bg="Red")
                        self.custom_label.config(bg="Red")
                        self.label.config(bg="Red")
                        self.lock.config(bg="Red")
                if PSI > (self.set_pressure_scale.get() - 3):
                    if self.frame.cget('bg') == "Red":
                        self.frame.config(bg=self.frameColor)
                        self.set_pressure_scale.config(bg=self.frameColor)
                        self.custom_label.config(bg=self.frameColor)
                        self.label.config(bg=self.frameColor)
                        self.lock.config(bg=self.frameColor)
            except:
                print("Init Air Pressure")
            root.after(200, self.update_pressure)
        else:
            self.pressure.set("")

    def lock(self):
        if self.lock_flag.get() == True:
            self.set_pressure_scale.config(state="disabled")
            self.power.config(state="disable")
        elif self.lock_flag.get() == False:
            self.set_pressure_scale.config(state="normal")
            self.power.config(state="normal")
Beispiel #8
0
from Phidget22.Phidget import *
from Phidget22.Devices.VoltageRatioInput import *

print("testing")
ch1 = VoltageRatioInput()
ch1.setChannel(1)
ch1.openWaitForAttachment(1000)

ch2=VoltageRatioInput()
ch2.setChannel(2)
ch2.openWaitForAttachment(1000)

ch3 = VoltageRatioInput()
ch3.setChannel(0)
ch3.openWaitForAttachment(1000)


excitationvoltage=-10000 / 0.0459


while True:
    voltageRatio1 = excitationvoltage*ch1.getVoltageRatio() +1.3
    voltageRatio2 = excitationvoltage*ch2.getVoltageRatio() +1.3
    voltageRatio3 = excitationvoltage*ch3.getVoltageRatio() +1.3 + 2.5
    bucket1=voltageRatio1+voltageRatio2+voltageRatio3


    print(bucket1)


ch1.close()
Beispiel #9
0
def main():
    try:
        """
        * Allocate a new Phidget Channel object
        """
        ch = VoltageRatioInput()
        """
        * 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
        """
        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.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        ch.close()
        return 1
    except RuntimeError as e:
        sys.stderr.write("Runtime Error: \n\t" + e)
        traceback.print_exc()
        return 1
    finally:
        print("Press ENTER to end program.")
        readin = sys.stdin.readline()
class HardwareManager:

    cmdbuffer = stack(max=64)

    #true -> on
    #false -> off
    states = {
        "pressurize_tanks": False,
        "lox_vent": False,
        "kerosene_vent": False,
        "lox_dump": False,
        "kerosene_dump": False,
        "shutdown": False,
        "emergency_shutdown": False
    }
    current_pressures = {"p1": 0, "p2": 0, "p3": 0, "p4": 0}

    def init_load_cell(self, cfg):
        self.lc = VoltageRatioInput()
        self.lc.setDeviceSerialNumber(cfg["serialnumber"])
        self.lc.setChannel(cfg["channel"])

    def __init__(self, cfg, net: Net):
        self.hcfg = cfg["rpi"]["GPIO"]
        self.net = net
        self.logger = logging.getLogger("Hardware")
        #init gpio
        for valve in self.hcfg["valves"].keys():
            GPIO.setup(self.hcfg[valve]["v"], GPIO.OUT, initial=GPIO.LOW)
        for sensor in self.hcfg["pressure"].keys():
            pass
        self.init_load_cell(self.hcfg["loadcell"])
        self.logger.info("Hardware Initialized")

    def report_states(self):
        return self.states

    def report_data(self) -> dict:
        pass

    async def collect_data(self):
        while 1:
            pass

    def cmd(self, cmd):
        self.cmdbuffer.put_nowait(cmd)

    def exec(self, cmd: str):
        """
        executes necessary hardware changes to cause system change
        :param cmd: string for selected hardware sequence
        :return: nothing
        """
        if cmd == "lox_vent":
            self.states["lox_vent"] = True
        elif cmd == "kerosene_vent":
            self.states["kerosene_vent"] = True
        elif cmd == "ignition":
            self.states["kerosene_dump"] = True
            self.states["lox_dump"] = True
        elif cmd == "kerosene_dump":
            self.states["kerosene_dump"] = True
        elif cmd == "lox_dump":
            self.states["lox_dump"] = True
        elif cmd == "pressurize":
            self.states["pressurize"] = True
        elif cmd == "shutdown":
            pass
Beispiel #11
0
class WeightSensor:
    def __init__(self):
        self.weight_value = -1
        self.has_ended = False
        self.try_weight_sensor()

    def try_weight_sensor(self):
        print("Try Weight Sensor")
        try:
            # Allocate a new Phidget Channel object
            self.ch = VoltageRatioInput()
            self.do = DigitalOutput()

            self.ch.setChannel(0)
            self.do.setChannel(6)

            self.ch.setOnAttachHandler(onAttachHandler)
            self.ch.setOnDetachHandler(onDetachHandler)
            self.ch.setOnErrorHandler(onErrorHandler)
            self.ch.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)
            self.ch.setOnSensorChangeHandler(onSensorChangeHandler)
            # Open the channel with a timeout
            try:
                self.ch.openWaitForAttachment(5000)
                self.do.openWaitForAttachment(5000)
            except PhidgetException as e:
                # PrintOpenErrorMessage(e, self.ch)
                raise EndProgramSignal("Program Terminated: Open Failed")

            print("THREAD STARTING")

            weight_thread = threading.Thread(
                target=self.start_getting_weight_value)
            weight_thread.daemon = True
            weight_thread.start()

        except Exception as e:
            self.ch.close()
            self.try_conneting_again()

    def start_getting_weight_value(self):
        while not self.has_ended:
            try:
                self.weight_value = self.ch.getVoltageRatio()
            except:
                self.ch.close()
                break
            time.sleep(0.25)
        self.try_conneting_again()

    def try_conneting_again(self):
        self.has_ended = True
        print(
            "Weight sensor failed! Trying to connect to the weight sensor again in 3 2 1..."
        )
        time.sleep(3)
        self.ch = None
        self.do = None
        self.has_ended = False
        self.weight_value = -1
        self.try_weight_sensor()

    def get_weight_value(self):
        return self.weight_value
Beispiel #12
0
def main():
    """
    * Define how long the program runs for
    """
    runtime = int(input("Measure for long long: "))  # seconds
    """
    * Allocate a new Phidget Channel object
    """

    ch = VoltageRatioInput()
    ch2 = VoltageRatioInput()
    ch3 = VoltageRatioInput()
    ch4 = VoltageRatioInput()
    """
    * Set matching parameters to specify which channel to open
    """
    ch.setDeviceSerialNumber(533379)
    ch.setIsHubPortDevice(False)
    ch.setChannel(0)

    ch2.setDeviceSerialNumber(533379)
    ch2.setIsHubPortDevice(False)
    ch2.setChannel(1)

    ch3.setDeviceSerialNumber(533379)
    ch3.setIsHubPortDevice(False)
    ch3.setChannel(2)

    ch4.setDeviceSerialNumber(533379)
    ch4.setIsHubPortDevice(False)
    ch4.setChannel(3)
    """
    * Add event handlers before calling open so that no events are missed.
    """
    print("\n--------------------------------------")
    ch.setOnAttachHandler(onAttachHandler)
    ch2.setOnAttachHandler(onAttachHandler)
    ch3.setOnAttachHandler(onAttachHandler)
    ch4.setOnAttachHandler(onAttachHandler)

    ch.setOnDetachHandler(onDetachHandler)
    ch2.setOnDetachHandler(onDetachHandler)
    ch3.setOnDetachHandler(onDetachHandler)
    ch4.setOnDetachHandler(onDetachHandler)

    ch.setOnErrorHandler(onErrorHandler)
    ch2.setOnErrorHandler(onErrorHandler)
    ch3.setOnErrorHandler(onErrorHandler)
    ch4.setOnErrorHandler(onErrorHandler)

    ch.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)
    ch2.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler2)
    ch3.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler3)
    ch4.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler4)
    """
    * Open the channel with a timeout
    """

    print("\nOpening and Waiting for Attachment...")

    ch.openWaitForAttachment(5000)
    ch2.openWaitForAttachment(5000)
    ch3.openWaitForAttachment(5000)
    ch4.openWaitForAttachment(5000)

    time.sleep(runtime)
    """
    * Perform clean up and exit
    """

    #clear the VoltageRatioChange event handler
    ch.setOnVoltageRatioChangeHandler(None)
    ch2.setOnVoltageRatioChangeHandler(None)
    ch3.setOnVoltageRatioChangeHandler(None)
    ch4.setOnVoltageRatioChangeHandler(None)

    print("Cleaning up...")
    ch.close()
    ch2.close()
    ch3.close()
    ch4.close()

    f1.close()
    f2.close()
    f3.close()
    f4.close()

    print("\nExiting...")
    return 0
Beispiel #13
0
ch = VoltageRatioInput()

# Make directory and open file for writting
if not os.path.exists(LOG_FOLDER_NAME):
    os.makedirs(LOG_FOLDER_NAME)
f = open(FILE_LOG_SESSION, "w+")  # Overwrite

# Write CSV file header
f.write("Time, Time Since Begin, V/V Raw Data, Force \n")
ch.file = f

# Setup Phidget device parameters
ch.setDeviceSerialNumber(-1)
ch.setHubPort(-1)
ch.setIsHubPortDevice(False)
ch.setChannel(0)

print("\n--------------------------------------")
# Setup call back functions that is raised when voltage is changed
ch.setOnAttachHandler(onAttachHandler)
ch.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)

# Open Phidget connection
ch.openWaitForAttachment(5000)

# Wait for user to press Enter to stop
print("Press Enter to stop recording")
readin = sys.stdin.readline(1)

ch.close()
print("\n Phidget Challen Closed")
Beispiel #14
0
def main2():
    global sleeptime
    try:
        """
        * Allocate a new Phidget Channel object
        """
        ch2 = VoltageRatioInput()
        """
        * 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)

        ch2.setDeviceSerialNumber(566690)
        ch2.setChannel(2)
        """
        * Add event handlers before calling open so that no events are missed.
        """
        #print("\n--------------------------------------")
        #print("\nSetting OnAttachHandler...")
        ch2.setOnAttachHandler(onAttachHandler)

        #print("Setting OnDetachHandler...")
        ch2.setOnDetachHandler(onDetachHandler)

        #print("Setting OnErrorHandler...")
        ch2.setOnErrorHandler(onErrorHandler)

        #This call may be harmlessly removed
        #PrintEventDescriptions()

        #print("\nSetting OnVoltageRatioChangeHandler...")
        ch2.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)

        #print("\nSetting OnSensorChangeHandler...")
        ch2.setOnSensorChangeHandler(onSensorChangeHandler)
        """
        * Open the channel with a timeout
        """

        #print("\nOpening and Waiting for Attachment...")

        try:
            ch2.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch2)
            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(sleeptime)
        """
        * Perform clean up and exit
        """
        #print("\nDone Sampling...")

        #print("Cleaning up...")
        ch2.close()
        #print("\nExiting...")
        global data
        weight2 = data
        datalist.clear()
        return weight2

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        traceback.print_exc()
        print("Cleaning up...")
        ch2.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        ch2.close()
        return 1
    except RuntimeError as e:
        sys.stderr.write("Runtime Error: \n\t" + e)
        traceback.print_exc()
        return 1
Beispiel #15
0
def main():
    try:
        """
        * Allocate a new Phidget Channel object
        """
        try:
            ch0 = VoltageRatioInput()
            ch1 = VoltageRatioInput()
            ch2 = VoltageRatioInput()
            ch3 = VoltageRatioInput()
            ch4 = VoltageRatioInput()
            ch5 = VoltageRatioInput()
            ch6 = VoltageRatioInput()
            ch7 = VoltageRatioInput()
            ch8 = VoltageRatioInput()
            ch9 = 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)

        ch0.setDeviceSerialNumber(474147)
        ch0.setHubPort(0)
        ch0.setIsHubPortDevice(0)
        ch0.setChannel(0)

        ch1.setDeviceSerialNumber(474147)
        ch1.setHubPort(0)
        ch1.setIsHubPortDevice(0)
        ch1.setChannel(1)

        ch2.setDeviceSerialNumber(474147)
        ch2.setHubPort(0)
        ch2.setIsHubPortDevice(0)
        ch2.setChannel(2)

        ch3.setDeviceSerialNumber(474147)
        ch3.setHubPort(0)
        ch3.setIsHubPortDevice(0)
        ch3.setChannel(3)

        ch4.setDeviceSerialNumber(000000)
        ch4.setHubPort(0)
        ch4.setIsHubPortDevice(0)
        ch4.setChannel(0)

        ch5.setDeviceSerialNumber(000000)
        ch5.setHubPort(0)
        ch5.setIsHubPortDevice(0)
        ch5.setChannel(1)

        ch6.setDeviceSerialNumber(000000)
        ch6.setHubPort(0)
        ch6.setIsHubPortDevice(0)
        ch6.setChannel(2)

        ch7.setDeviceSerialNumber(000000)
        ch7.setHubPort(0)
        ch7.setIsHubPortDevice(0)
        ch7.setChannel(3)

        ch8.setDeviceSerialNumber(000000)
        ch8.setHubPort(0)
        ch8.setIsHubPortDevice(0)
        ch8.setChannel(0)

        ch9.setDeviceSerialNumber(000000)
        ch9.setHubPort(0)
        ch9.setIsHubPortDevice(0)
        ch9.setChannel(1)
        """
        * Add event handlers before calling open so that no events are missed.
        """
        print("\n--------------------------------------")
        print("\nSetting OnAttachHandler...")
        ch0.setOnAttachHandler(onAttachHandler)
        ch1.setOnAttachHandler(onAttachHandler)
        ch2.setOnAttachHandler(onAttachHandler)
        ch3.setOnAttachHandler(onAttachHandler)
        ch4.setOnAttachHandler(onAttachHandler)
        ch5.setOnAttachHandler(onAttachHandler)
        ch6.setOnAttachHandler(onAttachHandler)
        ch7.setOnAttachHandler(onAttachHandler)
        ch8.setOnAttachHandler(onAttachHandler)
        ch9.setOnAttachHandler(onAttachHandler)

        print("Setting OnDetachHandler...")
        ch0.setOnDetachHandler(onDetachHandler)
        ch1.setOnDetachHandler(onDetachHandler)
        ch2.setOnDetachHandler(onDetachHandler)
        ch3.setOnDetachHandler(onDetachHandler)
        ch4.setOnDetachHandler(onDetachHandler)
        ch5.setOnDetachHandler(onDetachHandler)
        ch6.setOnDetachHandler(onDetachHandler)
        ch7.setOnDetachHandler(onDetachHandler)
        ch8.setOnDetachHandler(onDetachHandler)
        ch9.setOnDetachHandler(onDetachHandler)

        print("Setting OnErrorHandler...")
        ch0.setOnErrorHandler(onErrorHandler)
        ch1.setOnErrorHandler(onErrorHandler)
        ch2.setOnErrorHandler(onErrorHandler)
        ch3.setOnErrorHandler(onErrorHandler)
        ch4.setOnErrorHandler(onErrorHandler)
        ch5.setOnErrorHandler(onErrorHandler)
        ch6.setOnErrorHandler(onErrorHandler)
        ch7.setOnErrorHandler(onErrorHandler)
        ch8.setOnErrorHandler(onErrorHandler)
        ch9.setOnErrorHandler(onErrorHandler)
        """
        * Open the channel with a timeout
        """

        print("\nOpening and Waiting for Attachment...")

        try:
            ch0.openWaitForAttachment(5000)
            ch1.openWaitForAttachment(5000)
            ch2.openWaitForAttachment(5000)
            ch3.openWaitForAttachment(5000)
            ch4.openWaitForAttachment(5000)
            ch5.openWaitForAttachment(5000)
            ch6.openWaitForAttachment(5000)
            ch7.openWaitForAttachment(5000)
            ch8.openWaitForAttachment(5000)
            ch9.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch0)
            PrintOpenErrorMessage(e, ch1)
            PrintOpenErrorMessage(e, ch2)
            PrintOpenErrorMessage(e, ch3)
            PrintOpenErrorMessage(e, ch4)
            PrintOpenErrorMessage(e, ch5)
            PrintOpenErrorMessage(e, ch6)
            PrintOpenErrorMessage(e, ch7)
            PrintOpenErrorMessage(e, ch8)
            PrintOpenErrorMessage(e, ch9)
            raise EndProgramSignal("Program Terminated: Open Failed")

        print("Sampling data...")

        print(
            "You can do stuff with your Phidgets here and/or in the event handlers."
        )

        time.sleep(5)

        #Create csv file to write data to
        file_path = os.path.join('C:', 'Users', 'Jacob Bennedsen', 'Desktop',
                                 'Python Files', 'Learning', 'Creep_Test.csv')
        csvfile = open(file_path, 'w')
        filewriter = csv.writer(csvfile,
                                delimiter=',',
                                lineterminator='\n',
                                quotechar='|',
                                quoting=csv.QUOTE_MINIMAL)

        #Write header row to csv
        filewriter.writerow([
            'Time (s)', 'ch0 (V/V)', 'ch1 (V/V)', 'ch2 (V/V)', 'ch3 (V/V)',
            'ch4 (V/V)', 'ch5 (V/V)', 'ch6 (V/V)', 'ch7 (V/V)', 'ch8 (V/V)',
            'ch9 (V/V)'
        ])

        delay = 1  #seconds

        #Initialize lists to be used for data plotting
        logged_time = list()
        w0 = list()
        w1 = list()
        w2 = list()
        w3 = list()
        w4 = list()
        w5 = list()
        w6 - list()
        w7 = list()
        w8 = list()
        w9 = list()

        tms = list(1, 3600, delay)

        for i in tms:
            v0 = ch0.getVoltageRatio()
            v1 = ch1.getVoltageRatio()
            v2 = ch2.getVoltageRatio()
            v3 = ch3.getVoltageRatio()
            v4 = ch4.getVoltageRatio()
            v5 = ch5.getVoltageRatio()
            v6 = ch6.getVoltageRatio()
            v7 = ch7.getVoltageRatio()
            v8 = ch8.getVoltageRatio()
            v9 = ch9.getVoltageRatio()

            w0.append(v0)  #Add latest voltage ratio to list
            w1.append(v1)
            w2.append(v2)
            w3.append(v3)
            w4.append(v4)
            w5.append(v5)
            w6.append(v6)
            w7.append(v7)
            w8.append(v8)
            w9.append(v9)

            #Write the collected data to a csv
            filewriter.writerow(
                [tms[i], v0, v1, v2, v3, v4, v5, v6, v7, v8, v9])

            time.sleep(
                delay)  #Wait for the specified time before looping again

        csvfile.close()

        #Plot data
        plt.plot(logged_time, w0, label='ch0')
        plt.plot(logged_time, w1, label='ch1')
        plt.plot(logged_time, w2, label='ch2')
        plt.plot(logged_time, w3, label='ch3')
        plt.plot(logged_time, w4, label='ch4')
        plt.plot(logged_time, w5, label='ch5')
        plt.plot(logged_time, w6, label='ch6')
        plt.plot(logged_time, w7, label='ch7')
        plt.plot(logged_time, w8, label='ch8')
        plt.plot(logged_time, w9, label='ch9')
        plt.legend()
        plt.show()
        """
        * Perform clean up and exit
        """

        #clear the VoltageRatioChange event handler
        ch0.setOnVoltageRatioChangeHandler(None)
        ch1.setOnVoltageRatioChangeHandler(None)
        ch2.setOnVoltageRatioChangeHandler(None)
        ch3.setOnVoltageRatioChangeHandler(None)
        ch4.setOnVoltageRatioChangeHandler(None)
        ch5.setOnVoltageRatioChangeHandler(None)
        ch6.setOnVoltageRatioChangeHandler(None)
        ch7.setOnVoltageRatioChangeHandler(None)
        ch8.setOnVoltageRatioChangeHandler(None)
        ch9.setOnVoltageRatioChangeHandler(None)

        print("\nDone Sampling...")

        print("Cleaning up...")
        ch0.close()
        ch1.close()
        ch2.close()
        ch3.close()
        ch4.close()
        ch5.close()
        ch6.close()
        ch7.close()
        ch8.close()
        ch9.close()
        print("\nExiting...")
        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        traceback.print_exc()
        print("Cleaning up...")
        ch0.setOnVoltageRatioChangeHandler(None)
        ch1.setOnVoltageRatioChangeHandler(None)
        ch2.setOnVoltageRatioChangeHandler(None)
        ch3.setOnVoltageRatioChangeHandler(None)
        ch0.close()
        ch1.close()
        ch2.close()
        ch3.close()
        ch4.close()
        ch5.close()
        ch6.close()
        ch7.close()
        ch8.close()
        ch9.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        ch0.setOnVoltageRatioChangeHandler(None)
        ch1.setOnVoltageRatioChangeHandler(None)
        ch2.setOnVoltageRatioChangeHandler(None)
        ch3.setOnVoltageRatioChangeHandler(None)
        ch0.close()
        ch1.close()
        ch2.close()
        ch3.close()
        ch4.close()
        ch5.close()
        ch6.close()
        ch7.close()
        ch8.close()
        ch9.close()
        return 1
    finally:
        print("Press ENTER to end program.")
        readin = sys.stdin.readline()
def VoltageRatioChangeHandlerB(e, voltageRatio):
        global b
        b = voltageRatio
#
start = time.time()
# Bridge (DAQ1500) is enabled by default so no need to enable it.
# Some functions are Boolean. 1 means enabled. Unit of time is ms.
ch.setOnVoltageRatioChangeHandler(VoltageRatioChangeHandlerA)
ch.setHubPort(1)
ch.setIsHubPortDevice(1)
ch.openWaitForAttachment(5000)
ch.setDataInterval(500) #minimum 1
#
ch2.setOnVoltageRatioChangeHandler(VoltageRatioChangeHandlerB)
ch2.setHubPort(0)
ch2.setChannel(0)
ch2.openWaitForAttachment(5000)
ch2.setDataInterval(500) # minimum 20
################################
X=[]
Y=[]
################################
while 1:
    F= b*S+CS  # Force # "b" is signal from load cell
    D= a*L+CL #Displacement or position. "a" comes from lvdt  
    # in this example, mechanical zero and stage zero coincide. Equation for D
    # may need to be modified.
    if D!=25:
            try:
                # Printing outputs in Console 
                print("Force: {0}   Disp: {1}".format(F,D))
Beispiel #17
0
def main():
    try:
        try:
            ch0 = VoltageRatioInput()
            ch1 = VoltageRatioInput()
            ch2 = VoltageRatioInput()
            ch3 = 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"
        ch0.setDeviceSerialNumber(494011)
        ch0.setChannel(0)
        ch1.setDeviceSerialNumber(494011)
        ch1.setChannel(1)
        ch2.setDeviceSerialNumber(494011)
        ch2.setChannel(2)
        ch3.setDeviceSerialNumber(494011)
        ch3.setChannel(3)

        " event handlers before calling open so that no events are missed. "
        print("\n--------------------------------------")

        print("\nSetting OnAttachHandler...")
        ch0.setOnAttachHandler(onAttachHandler)
        ch1.setOnAttachHandler(onAttachHandler)
        ch2.setOnAttachHandler(onAttachHandler)
        ch3.setOnAttachHandler(onAttachHandler)

        print("Setting OnDetachHandler...")
        ch0.setOnDetachHandler(onDetachHandler)
        ch1.setOnDetachHandler(onDetachHandler)
        ch2.setOnDetachHandler(onDetachHandler)
        ch3.setOnDetachHandler(onDetachHandler)

        print("Setting OnErrorHandler...")
        ch0.setOnErrorHandler(onErrorHandler)
        ch1.setOnErrorHandler(onErrorHandler)
        ch2.setOnErrorHandler(onErrorHandler)
        ch3.setOnErrorHandler(onErrorHandler)

        print("\nSetting onVoltageRatioChangeHandler...")
        #ch0.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)
        #ch1.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)
        #ch2.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)
        #ch3.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)

        " Open the channel with a timeout "
        print("\nOpening and Waiting for Attachment...")
        try:
            ch0.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch0)
            raise EndProgramSignal("Program Terminated: Open Failed")
        try:
            ch1.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch1)
            raise EndProgramSignal("Program Terminated: Open Failed")
        try:
            ch2.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch2)
            raise EndProgramSignal("Program Terminated: Open Failed")
        try:
            ch3.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch3)
            raise EndProgramSignal("Program Terminated: Open Failed")

        for n in range(100):
            cal0 = -ch0.getVoltageRatio()
            cal1 = -ch1.getVoltageRatio()
            cal2 = -ch2.getVoltageRatio()
            cal3 = -ch3.getVoltageRatio()
            time.sleep(0.008)

        while True:
            conv(ch0, ch1, ch2, ch3, cal0, cal1, cal2, cal3)
            time.sleep(0.008)

        #Print(ch0.getVoltageRatio())
        print(" Press enter to exit ")
        readin = sys.stdin.readline()
        " Perform clean up and exit "

        print("\nDone Sampling...")
        print("Cleaning up...")
        ch0.close()
        ch1.close()
        ch2.close()
        ch3.close()
        print("\nExiting...")
        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        traceback.print_exc()
        print("Cleaning up...")
        ch0.close()
        ch1.close()
        ch2.close()
        ch3.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        ch0.close()
        ch1.close()
        ch2.close()
        ch3.close()
        return 1
Beispiel #18
0
def main():
    try:
        """
        * Allocate a new Phidget Channel object
        """
        try:
            ch0 = VoltageRatioInput()
            ch1 = VoltageRatioInput()
            ch2 = VoltageRatioInput()
            ch3 = VoltageRatioInput()
            ch4 = VoltageRatioInput()
            ch5 = VoltageRatioInput()
            ch6 = VoltageRatioInput()
            ch7 = VoltageRatioInput()
            ch8 = VoltageRatioInput()
            ch9 = VoltageRatioInput()
            digi = DigitalInput()

        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)

        ch0.setDeviceSerialNumber(474147)
        ch0.setHubPort(0)
        ch0.setIsHubPortDevice(0)
        ch0.setChannel(0)

        ch1.setDeviceSerialNumber(474147)
        ch1.setHubPort(0)
        ch1.setIsHubPortDevice(0)
        ch1.setChannel(1)

        ch2.setDeviceSerialNumber(474147)
        ch2.setHubPort(0)
        ch2.setIsHubPortDevice(0)
        ch2.setChannel(2)

        ch3.setDeviceSerialNumber(474147)
        ch3.setHubPort(0)
        ch3.setIsHubPortDevice(0)
        ch3.setChannel(3)

        ch4.setDeviceSerialNumber(474147)
        ch4.setHubPort(0)
        ch4.setIsHubPortDevice(0)
        ch4.setChannel(0)

        ch5.setDeviceSerialNumber(000000)
        ch5.setHubPort(0)
        ch5.setIsHubPortDevice(0)
        ch5.setChannel(1)

        ch6.setDeviceSerialNumber(000000)
        ch6.setHubPort(0)
        ch6.setIsHubPortDevice(0)
        ch6.setChannel(2)

        ch7.setDeviceSerialNumber(000000)
        ch7.setHubPort(0)
        ch7.setIsHubPortDevice(0)
        ch7.setChannel(3)

        ch8.setDeviceSerialNumber(000000)
        ch8.setHubPort(0)
        ch8.setIsHubPortDevice(0)
        ch8.setChannel(0)

        ch9.setDeviceSerialNumber(000000)
        ch9.setHubPort(0)
        ch9.setIsHubPortDevice(0)
        ch9.setChannel(1)

        digi.setDeviceSerialNumber(000000)
        digi.setHubPort(0)
        digisetIsHubPortDevice(0)
        digi.setChannel(0)
        """
        * Add event handlers before calling open so that no events are missed.
        """
        print("\n--------------------------------------")
        print("\nSetting OnAttachHandler...")
        ch0.setOnAttachHandler(onAttachHandler)
        ch1.setOnAttachHandler(onAttachHandler)
        ch2.setOnAttachHandler(onAttachHandler)
        ch3.setOnAttachHandler(onAttachHandler)
        ch4.setOnAttachHandler(onAttachHandler)
        ch5.setOnAttachHandler(onAttachHandler)
        ch6.setOnAttachHandler(onAttachHandler)
        ch7.setOnAttachHandler(onAttachHandler)
        ch8.setOnAttachHandler(onAttachHandler)
        ch9.setOnAttachHandler(onAttachHandler)

        print("Setting OnDetachHandler...")
        ch0.setOnDetachHandler(onDetachHandler)
        ch1.setOnDetachHandler(onDetachHandler)
        ch2.setOnDetachHandler(onDetachHandler)
        ch3.setOnDetachHandler(onDetachHandler)
        ch4.setOnDetachHandler(onDetachHandler)
        ch5.setOnDetachHandler(onDetachHandler)
        ch6.setOnDetachHandler(onDetachHandler)
        ch7.setOnDetachHandler(onDetachHandler)
        ch8.setOnDetachHandler(onDetachHandler)
        ch9.setOnDetachHandler(onDetachHandler)

        print("Setting OnErrorHandler...")
        ch0.setOnErrorHandler(onErrorHandler)
        ch1.setOnErrorHandler(onErrorHandler)
        ch2.setOnErrorHandler(onErrorHandler)
        ch3.setOnErrorHandler(onErrorHandler)
        ch4.setOnErrorHandler(onErrorHandler)
        ch5.setOnErrorHandler(onErrorHandler)
        ch6.setOnErrorHandler(onErrorHandler)
        ch7.setOnErrorHandler(onErrorHandler)
        ch8.setOnErrorHandler(onErrorHandler)
        ch9.setOnErrorHandler(onErrorHandler)
        """
        * Open the channel with a timeout
        """

        print("\nOpening and Waiting for Attachment...")

        try:
            ch0.openWaitForAttachment(5000)
            ch1.openWaitForAttachment(5000)
            ch2.openWaitForAttachment(5000)
            ch3.openWaitForAttachment(5000)
            ch4.openWaitForAttachment(5000)
            ch5.openWaitForAttachment(5000)
            ch6.openWaitForAttachment(5000)
            ch7.openWaitForAttachment(5000)
            ch8.openWaitForAttachment(5000)
            ch9.openWaitForAttachment(5000)
            digi.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch0)
            PrintOpenErrorMessage(e, ch1)
            PrintOpenErrorMessage(e, ch2)
            PrintOpenErrorMessage(e, ch3)
            PrintOpenErrorMessage(e, ch4)
            PrintOpenErrorMessage(e, ch5)
            PrintOpenErrorMessage(e, ch6)
            PrintOpenErrorMessage(e, ch7)
            PrintOpenErrorMessage(e, ch8)
            PrintOpenErrorMessage(e, ch9)
            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(5)

        #Create csv file to write data to
        file_path = os.path.join('C:', 'Users', 'Jacob Bennedsen', 'Desktop',
                                 'Python Files', 'Learning',
                                 'Fatigue_Test.csv')
        csvfile = open(file_path, 'w')
        filewriter = csv.writer(csvfile,
                                delimiter=',',
                                lineterminator='\n',
                                quotechar='|',
                                quoting=csv.QUOTE_MINIMAL)

        #Write header row to csv
        filewriter.writerow([
            'Signal Iteration', 'Time (s)', 'ch0 (V/V)', 'ch1 (V/V)',
            'ch2 (V/V)', 'ch3 (V/V)', 'ch4 (V/V)', 'ch5 (V/V)', 'ch6 (V/V)',
            'ch7 (V/V)', 'ch8 (V/V)', 'ch9 (V/V)'
        ])

        delay = 1  #seconds

        #Initialize lists to be used for data plotting
        logged_time = list()
        w0 = list()
        w1 = list()
        w2 = list()
        w3 = list()
        w4 = list()
        w5 = list()
        w6 - list()
        w7 = list()
        w8 = list()
        w9 = list()

        d = deque([0, 0])  #Deque to check for change in state
        d.maxlen(2)  #Set max length of deque to 2
        sig_count = 0  #Count of changes in state
        i = 0  #Iteration of loop

        start_time = time.monotonic()  #Start time betweeen state change timer
        elapsed_time = 0  #Initialize the elapsed time

        while elapsed_time < 30:  #Loop while the time between state changes is less than 30 sec
            elapsed_time = time.monotonic() - start_time  #Update elapsed time
            d.append(digi.getState())  #Get the latest PLC signal value

            if d[0] != d[1]:  #Check if the latest and previous values changed
                start_time = time.monotonic(
                )  #If yes then reset time between state changes
                sig_count += 1  #Increment signal count

            t = i * delay  #Timestamp based upon loop iterations and data collection delay

            #Store latest voltage ratio from each channel in a variable
            v0 = ch0.getVoltageRatio()
            v1 = ch1.getVoltageRatio()
            v2 = ch2.getVoltageRatio()
            v3 = ch3.getVoltageRatio()
            v4 = ch4.getVoltageRatio()
            v5 = ch5.getVoltageRatio()
            v6 = ch6.getVoltageRatio()
            v7 = ch7.getVoltageRatio()
            v8 = ch8.getVoltageRatio()
            v9 = ch9.getVoltageRatio()

            logged_time.append(t)  #Add latest time to list
            w0.append(v0)  #Add latest voltage ratio to list
            w1.append(v1)
            w2.append(v2)
            w3.append(v3)
            w4.append(v4)
            w5.append(v5)
            w6.append(v6)
            w7.append(v7)
            w8.append(v8)
            w9.append(v9)

            #Write the collected data to a csv
            filewriter.writerow(
                [sig_count, t, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9])

            i += 1  #Increment iterations

            time.sleep(
                delay)  #Wait for the specified time before looping again

        csvfile.close()

        #Plot data
        plt.plot(logged_time, w0, label='ch0')
        plt.plot(logged_time, w1, label='ch1')
        plt.plot(logged_time, w2, label='ch2')
        plt.plot(logged_time, w3, label='ch3')
        plt.plot(logged_time, w4, label='ch4')
        plt.plot(logged_time, w5, label='ch5')
        plt.plot(logged_time, w6, label='ch6')
        plt.plot(logged_time, w7, label='ch7')
        plt.plot(logged_time, w8, label='ch8')
        plt.plot(logged_time, w9, label='ch9')
        plt.legend()
        plt.show()
        """
        * Perform clean up and exit
        """

        #clear the VoltageRatioChange event handler
        ch0.setOnVoltageRatioChangeHandler(None)
        ch1.setOnVoltageRatioChangeHandler(None)
        ch2.setOnVoltageRatioChangeHandler(None)
        ch3.setOnVoltageRatioChangeHandler(None)
        ch4.setOnVoltageRatioChangeHandler(None)
        ch5.setOnVoltageRatioChangeHandler(None)
        ch6.setOnVoltageRatioChangeHandler(None)
        ch7.setOnVoltageRatioChangeHandler(None)
        ch8.setOnVoltageRatioChangeHandler(None)
        ch9.setOnVoltageRatioChangeHandler(None)

        print("\nDone Sampling...")

        print("Cleaning up...")
        ch0.close()
        ch1.close()
        ch2.close()
        ch3.close()
        ch4.close()
        ch5.close()
        ch6.close()
        ch7.close()
        ch8.close()
        ch9.close()
        print("\nExiting...")
        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        traceback.print_exc()
        print("Cleaning up...")
        ch0.setOnVoltageRatioChangeHandler(None)
        ch1.setOnVoltageRatioChangeHandler(None)
        ch2.setOnVoltageRatioChangeHandler(None)
        ch3.setOnVoltageRatioChangeHandler(None)
        ch0.close()
        ch1.close()
        ch2.close()
        ch3.close()
        ch4.close()
        ch5.close()
        ch6.close()
        ch7.close()
        ch8.close()
        ch9.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        ch0.setOnVoltageRatioChangeHandler(None)
        ch1.setOnVoltageRatioChangeHandler(None)
        ch2.setOnVoltageRatioChangeHandler(None)
        ch3.setOnVoltageRatioChangeHandler(None)
        ch0.close()
        ch1.close()
        ch2.close()
        ch3.close()
        ch4.close()
        ch5.close()
        ch6.close()
        ch7.close()
        ch8.close()
        ch9.close()
        return 1
    finally:
        print("Press ENTER to end program.")
        readin = sys.stdin.readline()
Beispiel #19
0
def main():
    global w1
    global w2
    global w3
    global w4
    global c1
    global c2
    global c3
    global c4
    mvalue = []
    """
    * Define how long the program runs for
    """
    runtime = 10  # seconds
    """
    * Allocate a new Phidget Channel object
    """

    ch = VoltageRatioInput()
    ch2 = VoltageRatioInput()
    ch3 = VoltageRatioInput()
    ch4 = VoltageRatioInput()
    """
    * Set matching parameters to specify which channel to open
    """
    ch.setDeviceSerialNumber(533379)
    ch.setIsHubPortDevice(False)
    ch.setChannel(0)

    ch2.setDeviceSerialNumber(533379)
    ch2.setIsHubPortDevice(False)
    ch2.setChannel(1)

    ch3.setDeviceSerialNumber(533379)
    ch3.setIsHubPortDevice(False)
    ch3.setChannel(2)

    ch4.setDeviceSerialNumber(533379)
    ch4.setIsHubPortDevice(False)
    ch4.setChannel(3)
    """
    * Add event handlers before calling open so that no events are missed.
    """
    print("\n--------------------------------------")
    ch.setOnAttachHandler(onAttachHandler)
    ch2.setOnAttachHandler(onAttachHandler)
    ch3.setOnAttachHandler(onAttachHandler)
    ch4.setOnAttachHandler(onAttachHandler)

    ch.setOnDetachHandler(onDetachHandler)
    ch2.setOnDetachHandler(onDetachHandler)
    ch3.setOnDetachHandler(onDetachHandler)
    ch4.setOnDetachHandler(onDetachHandler)

    ch.setOnErrorHandler(onErrorHandler)
    ch2.setOnErrorHandler(onErrorHandler)
    ch3.setOnErrorHandler(onErrorHandler)
    ch4.setOnErrorHandler(onErrorHandler)

    ch.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)
    ch2.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler2)
    ch3.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler3)
    ch4.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler4)
    """
    * Open the channel with a timeout
    """

    print "motor 1 - w1"

    ch.openWaitForAttachment(5000)
    time.sleep(runtime)
    ch.setOnVoltageRatioChangeHandler(None)

    mvalue.append(w1 / c1)
    w1 = 0
    c1 = 0

    x = raw_input("motor 1 - w2")
    ch.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)
    ch.openWaitForAttachment(5000)
    time.sleep(runtime)
    ch.setOnVoltageRatioChangeHandler(None)

    mvalue.append(w1 / c1)
    w1 = 0
    c1 = 0

    x = raw_input("motor 2 - w1")
    ch2.openWaitForAttachment(5000)
    time.sleep(runtime)
    ch2.setOnVoltageRatioChangeHandler(None)

    mvalue.append(w2 / c2)
    w2 = 0
    c2 = 0

    x = raw_input("motor 2 - w2")
    ch2.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler2)
    ch2.openWaitForAttachment(5000)
    time.sleep(runtime)
    ch2.setOnVoltageRatioChangeHandler(None)

    mvalue.append(w2 / c2)
    w2 = 0
    c2 = 0

    x = raw_input("motor 3 - w1")
    ch3.openWaitForAttachment(5000)
    time.sleep(runtime)
    ch3.setOnVoltageRatioChangeHandler(None)

    mvalue.append(w3 / c3)
    w3 = 0
    c3 = 0

    x = raw_input("motor 3 - w2")
    ch3.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler3)
    ch3.openWaitForAttachment(5000)
    time.sleep(runtime)
    ch3.setOnVoltageRatioChangeHandler(None)

    mvalue.append(w3 / c3)
    w3 = 0
    c3 = 0

    x = raw_input("motor 4 - w1")
    ch4.openWaitForAttachment(5000)
    time.sleep(runtime)
    ch4.setOnVoltageRatioChangeHandler(None)

    mvalue.append(w4 / c4)
    w4 = 0
    c4 = 0

    x = raw_input("motor 4 - w2")
    ch4.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler4)
    ch4.openWaitForAttachment(5000)
    time.sleep(runtime)
    ch4.setOnVoltageRatioChangeHandler(None)

    mvalue.append(w4 / c4)
    w4 = 0
    c4 = 0

    # calibration
    cali.run_calibration(mvalue)

    print("calibration file saved...")
    ch.close()
    ch2.close()
    ch3.close()
    ch4.close()

    print("\nExiting...")
    return 0