Example #1
0
    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()
Example #2
0
 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)
Example #3
0
    def __init__(self, tunnel_info, name, logger):
        self.tunnel_info = tunnel_info
        self.name = name
        self.logger = logger

        self.latches = {}
        for name, info in self.tunnel_info.latches_info.items():
            self.latches[name] = Latch(info, self.name + '_' + name + "_latch",
                                       self.logger)

        self.voltage_ratio_input = VoltageRatioInput(
            self.tunnel_info.voltage_ratio_input_info,
            self.name + '_load_cell', self.logger)
Example #4
0
def main():
    print("Setting up Phidget...")

    try:
        ch = VoltageRatioInput()
        ch.setOnAttachHandler(onAttachHandler)
        ch.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)
        print("Phidget Set Up.")

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        print(e)
        print("Cleaning up...")
        ch.close()

    runningLED.on()
    line = []
    testNum = 0

    while 1:
        if startButton.is_pressed:
            testNum += 1
            timeStruct = time.localtime()
            startTime = "{}-{}-{}T{}{}{}".format(timeStruct[0],
                                                    timeStruct[1],
                                                    timeStruct[2],
                                                    timeStruct[3],
                                                    timeStruct[4],
                                                    timeStruct[5])
            output_file = startTime + ".csv"
            simpleQ = startCollecting(ch, testNum, output_file)
            time.sleep(0.5)
            offset = configureOffset(77262, ch.voltageRatio)
            print(offset)
            currentVoltage = ch.voltageRatio
            currentSec = time.time()
            secondsElapsed = 0
            while not stopButton.is_pressed:
                if currentVoltage != ch.voltageRatio:
                    force = 77262 * ch.voltageRatio - offset
                    currentVoltage = ch.voltageRatio
                    force = "{0:.2f}".format(force)
                    print(force)
                    if time.time() - currentSec > 0.9:
                        secondsElapsed += 1
                        currentSec = time.time()
                    seconds = "{}".format(secondsElapsed)
                    simpleQ.put((seconds, force))
            try:
                stopCollecting(ch, testNum, simpleQ, output_file)
                time.sleep(1)

            except error as e:
                print("Something went wrong.")
                print(e)

    pause()
Example #5
0
def main():
    voltageRatioInput0 = VoltageRatioInput()

    voltageRatioInput0.setOnVoltageRatioChangeHandler(onVoltageRatioChange)

    voltageRatioInput0.openWaitForAttachment(5000)

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

    voltageRatioInput0.close()
Example #6
0
def main():
    #Create your Phidget channels
    voltageRatioInput0 = VoltageRatioInput()

    #Set addressing parameters to specify which channel to open (if any)

    #Assign any event handlers you need before calling open so that no events are missed.
    voltageRatioInput0.setOnSensorChangeHandler(onSensorChange)

    #Open your Phidgets and wait for attachment
    voltageRatioInput0.openWaitForAttachment(5000)

    #Do stuff with your Phidgets here or in your event handlers.
    #Set the sensor type to match the analog sensor you are using after opening the Phidget
    voltageRatioInput0.setSensorType(VoltageRatioSensorType.SENSOR_TYPE_1111)

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

    #Close your Phidgets once the program is done.
    voltageRatioInput0.close()
Example #7
0
def connect_to_device():
    # Connect to device. Make sure anything else reading it is closed.
    ch = VoltageRatioInput.VoltageRatioInput()
    ch.close()
    ch.setDeviceSerialNumber(533042)
    ch.setChannel(1)

    ch.open()  # not sure if needed
    ch.openWaitForAttachment(800)
    time.sleep(1.5)

    print("trying to read voltage ratio:")
    print(ch.getVoltageRatio())
    print("setting data interval to 8ms")
    ch.setDataInterval(8)
    return ch
Example #8
0
def main():
    snd1 = SoundSensor()
    snd2 = SoundSensor()
    temp = VoltageRatioInput()
    hum = VoltageRatioInput()
    light = VoltageInput()

    openChannels(snd1, snd2, temp, hum, light)

    for i in range(10):
        print(getJSONSensorValues(snd1, snd2, temp, hum, light))
        print('')
        time.sleep(1)

    snd1.close()
    snd2.close()
    temp.close()
    hum.close()
    light.close()
Example #9
0
    def __init__(self):
        self.channelList = [
            VoltageRatioInput(),
            VoltageRatioInput(),
            VoltageRatioInput(),
            VoltageRatioInput(),
            VoltageRatioInput(),
            VoltageRatioInput(),
            VoltageRatioInput(),
            VoltageRatioInput()
        ]
        i = 0
        for i in range(len(self.channelList)):
            self.channelList[i].setChannel(i)
            i = i + 1

        self.sensorOutput = [0, 0, 0, 0, 0, 0, 0, 0]
        self.hasSensor = [False] * 8
        self.hasNewData = False
        self.channelLabel = [""] * 8
Example #10
0
class SensorHandler:
    startTime = 0
    voltageRatioInput0 = VoltageRatioInput()
    results = {}

    def __init__(self, calibrateOutput):
        self.calibrateOutput = calibrateOutput

    def onSensorChangeCalibration(self, test, sensorValue, sensorUnit):
        self.calibrateOutput.setText(str(int(round(100 * sensorValue))) + "%")

    def StartSensorCalibrate(self, outputPath):
        #Set addressing parameters to specify which channel to open (if any)
        self.voltageRatioInput0.setIsHubPortDevice(True)
        self.voltageRatioInput0.setHubPort(0)
        self.voltageRatioInput0.setOnSensorChangeHandler(
            self.onSensorChangeCalibration)
        try:
            self.voltageRatioInput0.openWaitForAttachment(5000)
            self.voltageRatioInput0.setSensorType(
                VoltageRatioSensorType.SENSOR_TYPE_1112)
        except PhidgetException:
            print("Please attach the sensor")

    def CloseSensor(self):
        self.voltageRatioInput0.close()
        return self.results

    def onSensorChange(self, test, sensorValue, sensorUnit):
        if self.startTime == 0:
            self.startTime = time.time()
        self.results["{0:.2f}".format(time.time() - self.startTime)] = str(
            sensorValue * 100)

    def StartSensor(self, outputPath):
        self.voltageRatioInput0.setOnSensorChangeHandler(self.onSensorChange)
        try:
            self.voltageRatioInput0.openWaitForAttachment(5000)
            self.voltageRatioInput0.setSensorType(
                VoltageRatioSensorType.SENSOR_TYPE_1112)
        except PhidgetException:
            print("Please attach the sensor")
async def LoadCellManagerTest(logger_func, **kwargs):
    """
        First Prototype Function
    """
    voltage_func = lambda V: kwargs["m"] * V + kwargs["b"]
    manager = Manager()

    def onVoltage(self, vr):
        logger_func(voltage_func, vr)

    volr = VoltageRatioInput()
    volr.setOnVoltageRatioChangeHandler(onVoltage)
    volr.openWaitForAttachment(5000)
    while 1:
        pass
async def LoadCellManager(logger_func, **kwargs):
    """
        Generic Function for DataRecorderClass Format
    """
    #voltage_func = lambda V: kwargs["m"]*V + kwargs["b"]
    manager = Manager()

    def onVoltage(self, vr):
        data = {"timestamp": ts(), "voltage": vr}
        logger_func(data)

    volr = VoltageRatioInput()
    volr.setOnVoltageRatioChangeHandler(onVoltage)
    volr.openWaitForAttachment(5000)
    while 1:
        pass
 def init_load_cell(self, cfg):
     self.lc = VoltageRatioInput()
     self.lc.setDeviceSerialNumber(cfg["serialnumber"])
     self.lc.setChannel(cfg["channel"])
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
Example #15
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()
Example #16
0
import sys
import time
import csv
from Phidget22.Devices.VoltageRatioInput import *
from Phidget22.PhidgetException import *
from Phidget22.Phidget import *
from Phidget22.Net import *

#declaration des 2 cartes et des 4 voies par jauges (8 au total)
ch1 = VoltageRatioInput()
ch10 = VoltageRatioInput()
ch11 = VoltageRatioInput()
ch12 = VoltageRatioInput()
ch13 = VoltageRatioInput()
ch2 = VoltageRatioInput()
ch20 = VoltageRatioInput()
ch21 = VoltageRatioInput()
ch22 = VoltageRatioInput()
ch23 = VoltageRatioInput()


def init():
    #declaration des cartes avec numero de serie le gain de 1, internal de temps 8 millisecondes
    ch1.setDeviceSerialNumber(513024)
    ch1.openWaitForAttachment(5000)
    ch1.setBridgeGain(1)
    ch1.setDataInterval(8)
    ch1.setBridgeEnabled(1)
    ch1.close()
    time.sleep(0.5)
    ch2.setDeviceSerialNumber(514788)
Example #17
0
    elif compensatedvalue > self.maxVoltageRatio:
        self.maxVoltageRatio = 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):
        print("[Sensor Event] -> Sensor Value: " + str(sensorValue) +
              sensorUnit.symbol)


# New channel object
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)
Example #18
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")
Example #19
0
 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 main():
    voltageRatioInput0 = VoltageRatioInput()

    voltageRatioInput0.setIsHubPortDevice(True)
    voltageRatioInput0.setHubPort(0)

    print(*[x for x in voltageRatioInput0.__dir__() if "DataInterval" in x],
          sep="\n")

    voltageRatioInput0.setOnVoltageRatioChangeHandler(onVoltageRatioChange)

    voltageRatioInput0.openWaitForAttachment(5000)

    print(voltageRatioInput0.getMinDataInterval(),
          voltageRatioInput0.getMaxDataInterval())
    voltageRatioInput0.setDataInterval(100)
    voltageRatioInput0.setSensorValueChangeTrigger(0.01)
    try:
        input("Press Enter to Stop\n")
    except (Exception, KeyboardInterrupt):
        pass

    voltageRatioInput0.close()
def main():
    global current, voltage, app, serverUpdateThread, hadPhidgetException, sessionFile

    hadPhidgetException = False

    voltage_sensor = None
    current_sensor = None
    serverUpdateThread = StoppableThread()

    sessionNum = 0

    with open("numSessions.txt", "r+") as numSessionsFile:
        sessionNum = int(numSessionsFile.read()) + 1
        print(sessionNum)
        numSessionsFile.seek(0)
        numSessionsFile.write(str(sessionNum))
        numSessionsFile.truncate()
        numSessionsFile.close()

    timestamp = datetime.now()
    sessionFile = open(
        "Sessions/session" + str(sessionNum) + "_" + str(timestamp.month) +
        "-" + str(timestamp.day) + "_" + str(timestamp.hour) + "-" +
        str(timestamp.minute) + "-" + str(timestamp.second) + ".txt", "w+")

    print("Session File created")

    try:
        voltage_sensor = VoltageInput()
        current_sensor = VoltageRatioInput()

        voltage_sensor.setHubPort(0)
        voltage_sensor.setIsHubPortDevice(False)
        voltage_sensor.setOnVoltageChangeHandler(on_new_voltage_reading)

        current_sensor.setHubPort(1)
        current_sensor.setIsHubPortDevice(True)
        current_sensor.setOnVoltageRatioChangeHandler(on_new_current_reading)

        voltage_sensor.openWaitForAttachment(1000)
        current_sensor.openWaitForAttachment(1000)

        serverUpdateThread.start()

        atexit.register(exit_handler)
        app.run(host='0.0.0.0')
        voltage_sensor.close()
        current_sensor.close()

    except PhidgetException as e:
        print(e)
        hadPhidgetException = True
        exit_handler(voltage_sensor, current_sensor)

    except KeyboardInterrupt as key:
        print(key)
        exit_handler(voltage_sensor, current_sensor)

    except IOError as e:
        print(e)
        exit_handler(voltage_sensor, current_sensor)
Example #22
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
Example #23
0
    bCur = CurrentInput()
    bCur.setDeviceSerialNumber(465371)
    bCur.openWaitForAttachment(1000)

if C:
    # Motor C: Setup Motor Control and Motor Current
    mtrC = DCMotor()
    mtrC.setDeviceSerialNumber(474333)
    mtrC.openWaitForAttachment(1000)
    mtrC.setAcceleration(ACCEL)

    cCur = CurrentInput()
    cCur.setDeviceSerialNumber(474333)
    cCur.openWaitForAttachment(1000)

    pot = VoltageRatioInput()
    pot.setDeviceSerialNumber(474333)
    pot.openWaitForAttachment(1000)
    pot.setOnVoltageRatioChangeHandler(joystick_movement)
    pot.setVoltageRatioChangeTrigger(0.05)

root = Tk()

if A:
    aCur_reading = StringVar()
if B:
    bCur_reading = StringVar()
if C:
    cCur_reading = StringVar()

title = Label(root, text="3 Axis Open Loop Controller", font="Courier, 14")
Example #24
0
def main():
    port = "/dev/ttyACM0"
    try:
        print("Trying Arduino Set Up...")
        s1 = serial.Serial(port, 9600)
        if s1.name == port:
            current_time_struct = time.localtime()
            current_time = "{}:{}:{}".format(current_time_struct[3],
                                             current_time_struct[4],
                                             current_time_struct[5])
            s1.flushInput()
            lines = []
            time.sleep(1.5)

            try:
                with open("hx711_output.csv", newline='') as csvFile:
                    print("Successfully found CSV file.\n")
                    reader = csv.reader(csvFile)
            except:
                print("File does not exist, creating file.\n")
                with open("hx711_output.csv", 'w') as csvFile:
                    writer = csv.writer(csvFile)
                    writer.writerows(["Time", "Weight"])

            with open("hx711_output.csv", 'a') as csvFile:
                print("Successfully opened CSV file for writing\n")
                writer = csv.writer(csvFile)
                while 1:
                    current_time_struct = time.localtime()
                    current_time = '{}:{}:{}'.format(current_time_struct[3],
                                                     current_time_struct[4],
                                                     current_time_struct[5])

                    if s1.in_waiting > 0:
                        num_bytes = s1.read(1)
                        print(num_bytes)
                        weight = s1.read(num_bytes)
                        print(weight)
                        #writer.writerows([current_time, weight])

    except:
        try:
            print("Arduino Set Up Failed, Trying Phidget...")
            ch = VoltageRatioInput()
            ch.setOnAttachHandler(onAttachHandler)
            ch.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler)
            ch.voltageRatio = 0.0

            try:
                print("Waiting for Attachment")
                ch.openWaitForAttachment(10000)
                ch.setDataInterval(10)
            except PhidgetException as e:
                print("Attachment Timed Out")

            #time.sleep(10)

            #Checks to see if enter has been pressed
            readin = sys.stdin.readline()

            while readin != "\n":
                time.sleep(1)

            ch.close()
            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 RunTimeError as e:
            sys.stderr.write("Runtime Error: \n\t" + e)
            traceback.print_exc()
            return 1
Example #25
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
Example #26
0
class Tunnel():
    def __init__(self, tunnel_info, name, logger):
        self.tunnel_info = tunnel_info
        self.name = name
        self.logger = logger

        self.latches = {}
        for name, info in self.tunnel_info.latches_info.items():
            self.latches[name] = Latch(info, self.name + '_' + name + "_latch",
                                       self.logger)

        self.voltage_ratio_input = VoltageRatioInput(
            self.tunnel_info.voltage_ratio_input_info,
            self.name + '_load_cell', self.logger)

    def open(self):
        for name, latch in self.latches.items():
            latch.open()
        self.voltage_ratio_input.open()

    def close(self):
        for name, latch in self.latches.items():
            latch.close()
        self.voltage_ratio_input.close()

    def set_on_attach_handler(self, on_attach_handler):
        for name, latch in self.latches.items():
            latch.set_on_attach_handler(on_attach_handler)
        self.voltage_ratio_input.set_on_attach_handler(on_attach_handler)

    def _on_attach_handler(self, handle):
        for name, latch in self.latches.items():
            if latch.has_handle(handle):
                latch._on_attach_handler(handle)
                return
        if self.voltage_ratio_input.has_handle(handle):
            self.voltage_ratio_input._on_attach_handler(handle)

    def is_attached(self):
        for name, latch in self.latches.items():
            if not latch.is_attached():
                return False
        if not self.voltage_ratio_input.is_attached():
            return False
        return True

    def set_stepper_on_change_handlers(self, stepper_on_change_handler):
        for name, latch in self.latches.items():
            latch.stepper_joint.stepper.set_on_position_change_handler(
                stepper_on_change_handler)
            latch.stepper_joint.stepper.set_on_velocity_change_handler(
                stepper_on_change_handler)

    def set_stepper_on_change_handlers_to_disabled(self):
        for name, latch in self.latches.items():
            latch.stepper_joint.stepper.set_on_position_change_handler(None)
            latch.stepper_joint.stepper.set_on_velocity_change_handler(None)

    def set_stepper_on_stopped_handlers(self, stepper_on_stopped_handler):
        for name, latch in self.latches.items():
            latch.stepper_joint.stepper.set_on_stopped_handler(
                stepper_on_stopped_handler)

    def set_stepper_on_stopped_handlers_to_disabled(self):
        for name, latch in self.latches.items():
            latch.stepper_joint.stepper.set_on_stopped_handler(None)

    def set_stepper_on_homed_handlers(self, on_homed_handler):
        for name, latch in self.latches.items():
            latch.stepper_joint.set_on_homed_handler(on_homed_handler)

    def set_limit_switch_handlers(self, limit_switch_handler):
        for name, latch in self.latches.items():
            latch.stepper_joint.set_limit_switch_handler(limit_switch_handler)

    def home_latches(self):
        for name, latch in self.latches.items():
            latch.stepper_joint.home()

    def all_latches_homed(self):
        all_homed = True
        for name, latch in self.latches.items():
            if not latch.stepper_joint.homed:
                all_homed = False
                break
        return all_homed

    def any_latches_moving(self):
        any_moving = False
        for name, latch in self.latches.items():
            if latch.stepper_joint.stepper.is_moving():
                any_moving = True
                break
        return any_moving

    def latch_all(self):
        for name, latch in self.latches.items():
            latch.latch()

    def unlatch_all(self):
        for name, latch in self.latches.items():
            latch.unlatch()
Example #27
0
    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)
Example #28
0
    except PhidgetException as e:
        sys.stderr.write("Runtime Error -> Set Detach Handler: \n\t")
        DisplayError(e)
        raise

    print("Setting OnErrorHandler...")
    try:
        ph.setOnErrorHandler(onErrorHandler)
    except PhidgetException as e:
        sys.stderr.write("Runtime Error -> Set Error Handler: \n\t")
        DisplayError(e)
        raise

    return


ch = VoltageRatioInput()

ch.openWaitForAttachment(5000)
# ch.setDeviceSerialNumber(-1)
# ch.setChannel(2)
# # ch.setDataInterval(1000)
# # ch.setVoltageRatioChangeTrigger(0.0)

# SetAttachDetachError_Handlers(ch)
# SetVoltageRatioHandler(ch,onVoltageRatioChangeHandler)
# SetSensorHandler(ch,onSensorChangeHandler)
# OpenPhidgetChannel_waitForAttach(ch,5000)

state = ch.getVoltageRatio()
print(state)
Example #29
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()
Example #30
0
import time
from Phidget22.Devices.VoltageRatioInput import *
from Phidget22.PhidgetException import *
from Phidget22.Phidget import *
from Phidget22.Net import *

#%% Paul DeTrempe8, Hybrid rocket load cell data collection script
# Big shoutout to Phidget for writing 90% of this
# Change data collection time duration in %%Collect Data section
# Change output text file name in %%Store Voltage Ratios section

# define storage vector of voltage ratios
Vratios = [0.0]

try:
    ch = VoltageRatioInput()
    #ch.open()
except RuntimeError as e:
    print("Runtime Exception %s" % e.details)
    print("Press Enter to Exit...\n")
    readin = sys.stdin.read(1)
    exit(1)


def VoltageRatioInputAttached(e):
    try:
        attached = e
        print("\nAttach Event Detected (Information Below)")
        print("===========================================")
        print("Library Version: %s" % attached.getLibraryVersion())
        print("Serial Number: %d" % attached.getDeviceSerialNumber())
Example #31
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()
Example #32
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()