Esempio n. 1
0
def main(period):
    taskHandle = daqmx.TaskHandle()
    daqmx.CreateTask("", taskHandle)

    physicalChannel = "Dev1/ao0"

    t = np.linspace(0, 2 * pi / period, 1000)
    data = 2 * np.sin(t)

    daqmx.CreateAOVoltageChan(taskHandle, physicalChannel, "", -10.0, 10.0,
                              daqmx.Val_Volts, None)

    daqmx.CfgSampClkTiming(taskHandle, "", 1000.0, daqmx.Val_Rising,
                           daqmx.Val_ContSamps, 1000)

    daqmx.WriteAnalogF64(taskHandle, 1000, 0, 10.0, daqmx.Val_GroupByChannel,
                         data)

    daqmx.StartTask(taskHandle)

    for n in range(100):
        time.sleep(0.3)

    daqmx.StopTask(taskHandle)
    daqmx.ClearTask(taskHandle)
Esempio n. 2
0
 def start_daq(self):
     # Task parameters
     self.th = daqmx.TaskHandle()
     daqmx.CreateTask("", self.th)
     self.sr = 100.0
         
     daqmx.CreateAIVoltageChan(self.th, self.phys_chan, "", 
                               daqmx.Val_Diff, -10.0, 10.0, 
                               daqmx.Val_Volts, None)  
     daqmx.CfgSampClkTiming(self.th, "", self.sr, daqmx.Val_Rising, 
                            daqmx.Val_ContSamps, 1000)
     daqmx.StartTask(self.th, fatalerror=False)
Esempio n. 3
0
def main():

    # Initializing task
    taskhandle = daqmx.TaskHandle()
    daqmx.CreateTask("", taskhandle)
    phys_chan = "Dev1/ctr0"

    #Timing parameters
    rate = 200.0
    initialdelay = 0
    lowtime = 1 / rate / 2
    hightime = 1 / rate / 2

    daqmx.CreateCOPulseChanTime(taskhandle, phys_chan, "", daqmx.Val_Seconds,
                                daqmx.Val_Low, initialdelay, lowtime, hightime,
                                False)

    print "Sending trigger pulse to", phys_chan + "..."
    daqmx.StartTask(taskhandle, fatalerror=True)
    print "Success!"

    daqmx.WaitUntilTaskDone(taskhandle, timeout=10, fatalerror=False)
    daqmx.ClearTask(taskhandle, fatalerror=False)
Esempio n. 4
0
def main():

    taskhandle = daqmx.TaskHandle()

    daqmx.CreateTask("", taskhandle)
    phys_chan = "cDAQ9188-16D66BBMod3/ctr2"
    globalchan = "VecPulse"

    #Timing parameters
    rate = 200  # Pulse rate in Hz
    initialdelay = 0
    lowtime = 1 / rate / 2
    hightime = 1 / rate / 2

    #    daqmx.CreateCOPulseChanTime(taskhandle, phys_chan, "", daqmx.Val_Seconds,
    #                                daqmx.Val_Low, initialdelay, lowtime, hightime,
    #                                False)

    daqmx.AddGlobalChansToTask(taskhandle, globalchan)

    daqmx.CfgImplicitTiming(taskhandle, daqmx.Val_FiniteSamps, 1)

    # Set up communication with motion controller
    simulator = False

    # Parameters for plotting
    plotting = False
    plot_dynamic = False

    if simulator == True:
        hcomm = acsc.OpenCommDirect()
    else:
        hcomm = acsc.OpenCommEthernetTCP("10.0.0.100", 701)

    axis = 5
    buffno = 7
    target = 0
    timeout = 10

    # Initialize arrays for storing time and position
    t = np.array(0)
    x = np.array(0)

    if plotting == True and plot_dynamic == True:
        plt.ioff()
        fig = plt.figure()
        ax = fig.add_subplot(111)
        #    plt.xlim(0, timeout)
        #    plt.ylim(0, target)
        line, = ax.plot([], [])
        fig.show()

    if hcomm == acsc.INVALID:
        print "Cannot connect to controller. Error:", acsc.GetLastError()

    else:
        #        acsc.Enable(hcomm, axis)
        rpos = acsc.GetRPosition(hcomm, axis)
        x = rpos
        t0 = time.time()

        if simulator == True:
            acsc.ToPoint(hcomm, 0, axis, target + 50000)
        else:
            acsc.RunBuffer(hcomm, buffno, None, None)

        while True:
            rpos = acsc.GetRPosition(hcomm, axis)
            if rpos >= target: break
            x = np.append(x, rpos)
            t = np.append(t, time.time() - t0)

            if plotting == True and plot_dynamic == True:
                line.set_xdata(t)
                line.set_ydata(x)
                ax.relim()
                ax.autoscale_view()
                fig.canvas.draw()

            print "Axis is", acsc.GetAxisState(hcomm, axis) + '...'

            if time.time() - t0 > timeout:
                print "Motion timeout"
                print "Final axis position:", rpos
                break

            time.sleep(0.001)

        print "Target reached. Sending trigger pulse to", globalchan + "..."

        daqmx.StartTask(taskhandle, fatalerror=False)
        daqmx.WaitUntilTaskDone(taskhandle, timeout=10, fatalerror=False)

    daqmx.ClearTask(taskhandle, fatalerror=False)
    acsc.CloseComm(hcomm)

    print "Triggered at", np.max(x)

    if plotting == True:
        if plot_dynamic == False:
            plt.plot(t, x)
    plt.show()

    return t, x
Esempio n. 5
0
 def start_reading(self):
     # start read analog 
     daqmx.StartTask(self.AItask, fatalerror=False)
Esempio n. 6
0
 def start(self):
     if not self.sample_clock_configured:
         self.configure_sample_clock()
     daqmx.StartTask(self.handle)
Esempio n. 7
0
daqmx.CreateAOVoltageChan(AOtaskHandle, "Dev1/ao0", "", -10.0, 10.0,
                          daqmx.Val_Volts, None)

daqmx.CfgSampClkTiming(AOtaskHandle, "", sr, daqmx.Val_Rising,
                       daqmx.Val_ContSamps, 1000)

daqmx.CreateAIVoltageChan(AItaskHandle, "Dev1/ai1", "", daqmx.Val_Diff, -10.0,
                          10.0, daqmx.Val_Volts, None)

daqmx.CfgSampClkTiming(AItaskHandle, "", sr, daqmx.Val_Rising,
                       daqmx.Val_ContSamps, 1000)

written = daqmx.WriteAnalogF64(AOtaskHandle, 1000, 0, 10.0,
                               daqmx.Val_GroupByChannel, data)

dataread, nread = daqmx.ReadAnalogF64(AItaskHandle, 1000, 10.0,
                                      daqmx.Val_GroupByChannel, 1000, 1)

daqmx.StartTask(AOtaskHandle)
daqmx.StartTask(AItaskHandle)

print written, "samples written"
print nread, "samples read"

plt.plot(dataread)

daqmx.StopTask(AItaskHandle)
daqmx.ClearTask(AItaskHandle)
daqmx.StopTask(AOtaskHandle)
daqmx.ClearTask(AOtaskHandle)
Esempio n. 8
0
def main():

    # Task parameters
    taskhandle = daqmx.TaskHandle()
    daqmx.CreateTask("", taskhandle)
    phys_chan = b"Dev1/ai0"
    nchan = 1
    sr = 100.0
    dt = 1 / sr
    totaltime = 3
    nloops = int(sr * totaltime / 10)

    # Analog read parameters
    samps_per_chan = 10
    timeout = 10
    fillmode = daqmx.Val_GroupByChannel
    array_size_samps = 1000

    daqmx.CreateAIVoltageChan(taskhandle, phys_chan, "", daqmx.Val_Diff, -10.0,
                              10.0, daqmx.Val_Volts, None)

    daqmx.CfgSampClkTiming(taskhandle, "", sr, daqmx.Val_Rising,
                           daqmx.Val_ContSamps, 1000)

    # Parameters for plotting
    plotting = True
    plot_dynamic = True

    if plotting == True and plot_dynamic == True:
        plt.ioff()
        fig = plt.figure()
        ax = fig.add_subplot(111)
        line, = ax.plot([], )
        fig.show()

    daqmx.StartTask(taskhandle, fatalerror=False)

    v = np.array([])

    for n in range(nloops):
        data, spc = daqmx.ReadAnalogF64(taskhandle, samps_per_chan, timeout,
                                        fillmode, array_size_samps, nchan)
        v = np.append(v, data[:, 0])
        time.sleep(0.001)
        t = np.float64(range(len(v))) * dt

        if plotting == True and plot_dynamic == True:
            line.set_xdata(t)
            line.set_ydata(v)
            ax.relim()
            ax.autoscale_view()
            fig.canvas.draw()

    daqmx.ClearTask(taskhandle)
    print("Task complete")

    if plotting == True:
        if plot_dynamic == False:
            plt.plot(t, v)
    plt.show()

    return t, data
Esempio n. 9
0
    def run(self, dur):
        """Start DAQmx tasks."""

        # Acquire and throwaway samples for alignment
        # Need to set these up on a different task?
        # Callback code from PyDAQmx
        class MyList(list):
            pass

        # List where the data are stored
        data = MyList()
        id_data = daqmx.create_callbackdata_id(data)

        def EveryNCallback_py(taskHandle, everyNsamplesEventType, nSamples,
                              callbackData_ptr):
            """Function called every N samples"""
            callbackdata = daqmx.get_callbackdata_from_id(callbackData_ptr)
            data, npoints = daqmx.ReadAnalogF64(taskHandle, self.nsamps, 10.0,
                                                daqmx.Val_GroupByChannel,
                                                self.nsamps,
                                                len(self.analogchans))
            callbackdata.extend(data.tolist())
            self.data["torque_trans"] = np.append(self.data["torque_trans"],
                                                  data[:, 0],
                                                  axis=0)
            self.data["torque_arm"] = np.append(self.data["torque_arm"],
                                                data[:, 1],
                                                axis=0)
            self.data["drag_left"] = np.append(self.data["drag_left"],
                                               data[:, 2],
                                               axis=0)
            self.data["drag_right"] = np.append(self.data["drag_right"],
                                                data[:, 3],
                                                axis=0)
            self.data["t"] = np.arange(len(self.data["torque_trans"]),
                                       dtype=float) / self.sr
            carpos, cpoints = daqmx.ReadCounterF64(self.carpostask,
                                                   self.nsamps, 10.0,
                                                   self.nsamps)
            self.data["carriage_pos"] = np.append(self.data["carriage_pos"],
                                                  carpos)
            turbang, cpoints = daqmx.ReadCounterF64(self.turbangtask,
                                                    self.nsamps, 10.0,
                                                    self.nsamps)
            self.data["turbine_angle"] = np.append(self.data["turbine_angle"],
                                                   turbang)
            self.data["turbine_rpm"] \
                = ts.smooth(fdiff.second_order_diff(self.data["turbine_angle"],
                                          self.data["t"])/6.0, 50)
            return 0  # The function should return an integer

        # Convert the python callback function to a CFunction
        EveryNCallback = daqmx.EveryNSamplesEventCallbackPtr(EveryNCallback_py)
        daqmx.RegisterEveryNSamplesEvent(self.analogtask,
                                         daqmx.Val_Acquired_Into_Buffer,
                                         self.nsamps, 0, EveryNCallback,
                                         id_data)

        def DoneCallback_py(taskHandle, status, callbackData_ptr):
            print("Status", status.value)
            return 0

        DoneCallback = daqmx.DoneEventCallbackPtr(DoneCallback_py)
        daqmx.RegisterDoneEvent(self.analogtask, 0, DoneCallback, None)

        # Start the tasks
        daqmx.StartTask(self.carpostask)
        daqmx.StartTask(self.turbangtask)
        daqmx.StartTask(self.analogtask)

        time.sleep(dur)
        self.clear()
Esempio n. 10
0
    def run(self, Nepisode, targetQN, train=True):
        self.setup_DAQmx()
        # Parameters for plotting
        # initiate
        seq      = np.zeros((self.num,self.NICH))
        read     = np.zeros((0,self.NCH)) 
        state_t  = np.zeros((self.SPC,self.NICH))
        b        = np.ones(self.num_mave)/self.num_mave
        tilen    = int(self.intispn / 0.01)
        # start read analog 
        daqmx.StartTask(self.AItask, fatalerror=False)
        # first loop
        # you read 
        # you do not act 
        # this loop is for caliburation of reward
        # you need to satrt writeanalog in first loop
        # 'cause the function takes time to start 
        for n in range(self.nloops):    
            read_t, _ = daqmx.ReadAnalogF64(self.AItask,self.SPC,self.TO,self.MODE,self.ASS,self.NCH)
            read_t = read_t/self.sensor_coff
        
            # moving average filter
            for ich in range(self.NICH):
                state_t[self.num_mave-1:,ich] = np.convolve(read_t[:,self.IAIs[ich]], b, mode='vaild')

            state_ave = ( np.average(np.split(state_t,int(self.num/tilen),0),axis=1) + self.dynamic_pressre )/self.dynamic_pressre
            seq[self.num-int(self.num/tilen):self.num,:] = np.round(state_ave,2)

            # action
            # adopt output timing and action zero
            if n!=10 or n!=20 or n!=40 or n!=50 or n!=60 or n!=80 or n!=90:
                daqmx.WriteAnalogF64(self.AOtask,self.OB,1,self.TO,daqmx.Val_GroupByChannel,np.zeros(self.OB))
            # reward
            reward_t  = np.average(read_t[:,self.CH100])
            self.memory.add_local(seq,0,reward_t,0)
            read = np.append(read,read_t,axis=0)
            seq = shift(seq,[-self.num/tilen,0],cval=0)

        # calibulate
        self.memory.calc_calibulation()
        # second loop
        # you read 
        # you act
        for n in range(self.nloops):
            read_t, _ = daqmx.ReadAnalogF64(self.AItask,self.SPC,self.TO,self.MODE,self.ASS,self.NCH)
            read_t = read_t/self.sensor_coff

            # moving average filter
            for ich in range(self.NICH):
                state_t[self.num_mave-1:,ich] = np.convolve(read_t[:,self.IAIs[ich]], b, mode='vaild')
            
            state_ave = ( np.average(np.split(state_t,int(self.num/tilen),0),axis=1) + self.dynamic_pressre )/self.dynamic_pressre
            seq[self.num-int(self.num/tilen):self.num,:] = np.round(state_ave,2)
            # action
            ai = self.actor.get_action(seq.reshape(-1,self.num,self.NICH), self.QN,train)
            daqmx.WriteAnalogF64(self.AOtask,self.OB,1,self.TO,daqmx.Val_GroupByChannel,self.PA[ai,:]*3)
            # reward
            reward_t  = np.average(read_t[:,self.CH100])
            self.memory.add_local(seq,ai,reward_t,0)
            read = np.append(read,read_t,axis=0)
            seq = shift(seq,[-self.num/tilen,0],cval=0)

        # third loop
        # you read 
        # you do not act
        # make sure PA turn off
        for n in range(self.nloops):
            read_t, _ = daqmx.ReadAnalogF64(self.AItask,self.SPC,self.TO,self.MODE,self.ASS,self.NCH)
            read_t = read_t/self.sensor_coff
            
            # moving average filter
            for ich in range(self.NICH):
                state_t[self.num_mave-1:,ich] = np.convolve(read_t[:,self.IAIs[ich]], b, mode='vaild')

            state_ave = ( np.average(np.split(state_t,int(self.num/tilen),0),axis=1) + self.dynamic_pressre )/self.dynamic_pressre
            seq[self.num-int(self.num/tilen):self.num,:] = np.round(state_ave,2)
            # action
            # action zero
            daqmx.WriteAnalogF64(self.AOtask,self.OB,1,self.TO,daqmx.Val_GroupByChannel,np.zeros(self.OB))
            # reward
            reward_t  = np.average(read_t[:,self.CH100])
            self.memory.add_local(seq,0,reward_t,0)
            read = np.append(read,read_t,axis=0)
            seq = shift(seq,[-self.num/tilen,0],cval=0)

        # stop DAQmx
        self.stop_DAQmx()
        # edit experience in buffer
        self.memory.edit_experience_local()
        self.save(read,Nepisode)
        total_reward = self.memory.totalreward()
        # move current experience to global buffer
        self.memory.add_global(total_reward)

        if (self.memory.len() > self.batch_num) and train:
            self.loss=self.QN.replay(self.memory,self.batch_num,self.gamma,targetQN)
            self.actor.reduce_epsilon()

            
        return total_reward, self.loss 
Esempio n. 11
0
diTaskHandle = daqmx.TaskHandle()

daqmx.CreateTask("", aiTaskHandle)
daqmx.CreateAIVoltageChan(aiTaskHandle, "Dev1/ai0", "", daqmx.Val_Diff, 0.0,
                          10.0, daqmx.Val_Volts)

daqmx.CfgSampClkTiming(aiTaskHandle, "", 100.0, daqmx.Val_Rising,
                       daqmx.Val_ContSamps, 1000)

trigname = daqmx.GetTerminalNameWithDevPrefix(aiTaskHandle, "ai/SampleClock")

daqmx.CreateTask("", diTaskHandle)
daqmx.CreateDIChan(diTaskHandle, "Dev1/port0", "", daqmx.Val_ChanForAllLines)
daqmx.CfgSampClkTiming(diTaskHandle, trigname, 100.0, daqmx.Val_Rising,
                       daqmx.Val_ContSamps, 1000)

daqmx.StartTask(diTaskHandle)
daqmx.StartTask(aiTaskHandle)

adata = daqmx.ReadAnalogF64(aiTaskHandle, 1000, 10.0, daqmx.Val_GroupByChannel,
                            1000, 1)
ddata = daqmx.ReadDigitalU32(diTaskHandle, 1000, 10.0,
                             daqmx.Val_GroupByChannel, 1000, 1)

print adata
print ddata

daqmx.StopTask(diTaskHandle)
daqmx.StopTask(aiTaskHandle)
daqmx.ClearTask(diTaskHandle)
daqmx.ClearTask(aiTaskHandle)
Esempio n. 12
0
    def run(self):
        self.rampeddown = False
        self.cleared = False
        self.making = False

        # Compute the voltage time series associated with the wave
        self.wave.gen_ts_volts()

        # Get parameters from the wave object
        self.period = self.wave.period
        self.height = self.wave.height
        self.buffsize = self.wave.sbuffsize
        self.sr = self.wave.sr

        # Get data to write from the wave object
        self.ts_plot = self.wave.ts_elev
        self.dataw = self.wave.ts_volts

        # If random waves, divide up time series into 120 256 sample parts
        if self.wavetype != "Regular":
            tsparts = np.reshape(self.dataw, (120, 256))
            self.dataw = tsparts[0, :]

        # Compute spectrum for plot
        if self.wavetype == "Regular":
            self.outf, self.outspec = self.wave.comp_spec()
        else:
            self.outf, self.outspec = self.wave.f, self.wave.spec

        # Ramp time series
        rampup_ts = ramp_ts(self.dataw, "up")

        # Set making variable true
        self.making = True

        self.AOtaskHandle = daqmx.TaskHandle()
        daqmx.CreateTask("", self.AOtaskHandle)
        daqmx.CreateAOVoltageChan(self.AOtaskHandle, "Dev1/ao0", "", -10.0,
                                  10.0, daqmx.Val_Volts, None)
        daqmx.CfgSampClkTiming(self.AOtaskHandle, "", self.sr,
                               daqmx.Val_Rising, daqmx.Val_ContSamps,
                               self.buffsize)
        daqmx.SetWriteRegenMode(self.AOtaskHandle, daqmx.Val_DoNotAllowRegen)

        # Setup a callback function to run once the DAQmx driver finishes
        def DoneCallback_py(taskHandle, status, callbackData_ptr):
            self.rampeddown = True
            return 0

        DoneCallback = daqmx.DoneEventCallbackPtr(DoneCallback_py)
        daqmx.RegisterDoneEvent(self.AOtaskHandle, 0, DoneCallback, None)

        # Output the rampup time series
        daqmx.WriteAnalogF64(self.AOtaskHandle, self.buffsize, False, 10.0,
                             daqmx.Val_GroupByChannel, rampup_ts)

        daqmx.StartTask(self.AOtaskHandle)

        # Wait a second to allow the DAQmx buffer to empty
        if self.wavetype == "Regular":
            time.sleep(self.period * 0.99)  # was self.period*0.4
        else:
            time.sleep(0.99)

        # Set iteration variable to keep track of how many chunks of data
        # have been written
        i = 1

        # Main running loop that writes data to DAQmx buffer
        while self.enable:
            writeSpaceAvail = daqmx.GetWriteSpaceAvail(self.AOtaskHandle)
            if writeSpaceAvail >= self.buffsize:
                if self.wavetype != "Regular":
                    if i >= 120:
                        self.dataw = tsparts[i % 120, :]
                    else:
                        self.dataw = tsparts[i, :]
                daqmx.WriteAnalogF64(self.AOtaskHandle, self.buffsize, False,
                                     10.0, daqmx.Val_GroupByChannel,
                                     self.dataw)
                i += 1
            if self.wavetype == "Regular":
                time.sleep(0.99 * self.period)
            else:
                time.sleep(0.99)  # Was self.period

        # After disabled, initiate rampdown time series
        if self.wavetype != "Regular":
            if i >= 120:
                self.rampdown_ts = ramp_ts(tsparts[i % 120, :], "down")
            else:
                self.rampdown_ts = ramp_ts(tsparts[i, :], "down")
        else:
            self.rampdown_ts = ramp_ts(self.dataw, "down")
        # Write rampdown time series
        daqmx.WriteAnalogF64(self.AOtaskHandle, self.buffsize, False, 10.0,
                             daqmx.Val_GroupByChannel, self.rampdown_ts)
        # Keep running, part of PyDAQmx callback syntax
        while True:
            pass