def __init__(self,dir,cb,port=None): self.dir=dir self.wait=False self.triggerCallback=cb self.port=port if self.port==None: self.port=UL.FIRSTPORTA if dir==0: #IN print 'Opening input port %d...' % self.port, try: UL.cbDConfigPort(0, self.port, UL.DIGITALIN) self.success=True print 'success!' except: print 'failure to open incoming digital port!' self.success=False else: #OUT print 'Opening output port %d...' % self.port, try: UL.cbDConfigPort(0, self.port, UL.DIGITALOUT) self.success=True print 'success!' except: self.success=False print 'failure to open outgoing digital port! (%d)' % self.port
def __init__(self): """ Returns a Measurement Computing daq object, if possible. Returns None if """ self.UL = None print "MCC DAQ: Connecting..." try: import UniversalLibrary as UL self.UL = UL except: print "Could not open Measurement Computing DAQ. " print "Check that the daq is connected. Also, ensure InstaCal and PyUniversalLibrary are installed." print "DAQ output will be unavailable for this session." traceback.print_exc() return print "MCC Daq: Success!" # DAQ setup self.boardNum = 0 UL.cbDConfigPort(self.boardNum, UL.FIRSTPORTA, UL.DIGITALOUT) UL.cbDConfigPort(self.boardNum, UL.FIRSTPORTB, UL.DIGITALOUT) # trigger bits for frame onset, stim onset, etc self.triggerBits = [0,0,0,0,0,0,0,0] self.stimcodeReadBit = 0 # constant telling you which bit tells CED to read the current stimcode self.stimBit = 2 # constant telling you which bit is for stim on / off self.frameBit = 3 # constant telling you which bit is for frame flip triggers
def led_off(): BoardNum = 0 PortNum = UL.FIRSTPORTB Direction = UL.DIGITALOUT UL.cbDConfigPort (BoardNum, PortNum, Direction) DataValue = 0 UL.cbDOut(BoardNum, PortNum, DataValue)
def __init__(self): """ Returns a Measurement Computing daq object, if possible. Returns None if """ self.UL = None print "MCC DAQ: Connecting..." try: import UniversalLibrary as UL self.UL = UL except: print "Could not open Measurement Computing DAQ. " print "Check that the daq is connected. Also, ensure InstaCal and PyUniversalLibrary are installed." print "DAQ output will be unavailable for this session." traceback.print_exc() return print "MCC Daq: Success!" # DAQ setup self.boardNum = 0 UL.cbDConfigPort(self.boardNum, UL.FIRSTPORTA, UL.DIGITALOUT) UL.cbDConfigPort(self.boardNum, UL.FIRSTPORTB, UL.DIGITALOUT) # trigger bits for frame onset, stim onset, etc self.triggerBits = [0, 0, 0, 0, 0, 0, 0, 0] self.stimcodeReadBit = 0 # constant telling you which bit tells CED to read the current stimcode self.stimBit = 2 # constant telling you which bit is for stim on / off self.frameBit = 3 # constant telling you which bit is for frame flip triggers
def getTorque(): Gain = UL.BIP5VOLTS Chan = 0 DataValue = UL.cbAIn(BoardNum, Chan, Gain) #return (UL.cbToEngUnits(BoardNum, Gain, DataValue)) engUnits = UL.cbToEngUnits(BoardNum, Gain, DataValue) return (2.26*engUnits)
def SetBitOff(BitChanX): '''Set a digital channel to 0V output''' UL.cbDConfigBit( BoardNum, PortType, BitChanX, UL.DIGITALOUT ) # necessary otherwise setting voltage directly does not work #Syntax : int cbDConfigBit(int BoardNum, int PortType, int BitNum, int Direction) UL.cbDBitOut(BoardNum, PortType, BitChanX, 1)
def updateVoltage(self, volt): global voltage, EngUnits, BoardNum, Chan, Gain, Conv, VtoA self.setVoltage(volt) EngUnits = self.getVoltage() DataValue = UL.cbFromEngUnits(BoardNum, Gain, EngUnits * Conv, 0) UL.cbAOut(BoardNum, Chan, Gain, DataValue) self.vLabelUpdate(voltage) self.aLabelUpdate(voltage * VtoA)
def sampleCurrent(self): Gain = UL.BIP5VOLTS Chan = 2 try: DataValue = UL.cbAIn(self.BoardNum, Chan, Gain) engUnits = UL.cbToEngUnits(self.BoardNum, Gain, DataValue) self.Current = (engUnits) / .02 - self.CurrentOffset except: pass
def postFlip(self, args): if self.needToSendStimcode: #record the time at the first flip self.triggerTimes.append(self.timer.getTime()) #Tell CED to read stimcode #this costs 1.2ms (+/- 0.1ms). UL.cbDOut(self.boardNum,UL.FIRSTPORTB,0) #Only need to do this once per stim self.needToSendStimcode = False
def led_on(): BoardNum = 0 PortNum = UL.FIRSTPORTB Direction = UL.DIGITALOUT UL.cbDConfigPort (BoardNum, PortNum, Direction) DataValue = 1 UL.cbDOut(BoardNum, PortNum, DataValue) sound_1 = sound.SoundPyo(value='C', secs=0.5, octave=4, stereo=True, volume=1.0, loops=0, sampleRate=44100, bits=16, hamming=True, start=0, stop=-1, name='', autoLog=True) sound_1.play()
def sampleTorque(self): Gain = UL.BIP5VOLTS Chan = 0 try: DataValue = UL.cbAIn(self.BoardNum, Chan, Gain) engUnits = UL.cbToEngUnits(self.BoardNum, Gain, DataValue) self.Torque = 2.26 * engUnits # - self.TorqueOffset; except: pass
def toggle(self): if self.success: if self.dir==1: #OUT if self.currentState==self.HIGH: UL.cbDOut(0, self.port, self.LOW) self.currentState=self.LOW else: UL.cbDOut(0, self.port, self.HIGH) self.currentState=self.HIGH
def startdisplayclicked(self): """Starts the data display""" #start functions and update handles self.stopdisplayclicked() # Stop an existing timer if self.driftalert.isChecked(): DataValue = UL.cbAIn(BoardNum, Chan, Gain)#raw input data for drift check initialValue = UL.cbToEngUnits(BoardNum, Gain, DataValue)#convert raw data to volts self._displayloop = self.startdisplayloop() #start the display loop function self._timerId = self.startTimer(0) # idle timer
def get_some_data(npts): #acquire from the board BoardNum=0 Gain=ul.BIP5VOLTS Chan=0 v=zeros(npts) for i in arange(npts): d=ul.cbAIn(BoardNum,Chan,Gain) v[i]=ul.cbToEngUnits(BoardNum,Gain,d) return v
def sampleVoltage(self): Gain = UL.BIP5VOLTS Chan = 1 try: DataValue = UL.cbAIn(self.BoardNum, Chan, Gain) engUnits = UL.cbToEngUnits(self.BoardNum, Gain, DataValue) self.Voltage = -1 * ( (engUnits - 2.5) * 20.2030 - self.VoltageOffset) except: pass
def updateCurrent(self, amp): global current, EngUnits, BoardNum, Chan, Gain, Conv, VtoA, curUp self.setCurrent(amp) EngUnits = self.getCurrent() / VtoA DataValue = UL.cbFromEngUnits(BoardNum, Gain, EngUnits * Conv, 0) UL.cbAOut(BoardNum, Chan, Gain, DataValue) self.aLabelUpdate(current) self.vLabelUpdate(current / VtoA) curUp = True curUp = False
def lick_detection(SIDE): EngUnits = 0 DataValue = 0 if SIDE == 0: while ((EngUnits) * (EngUnits))**0.5 < 1.55: DataValue = UL.cbAIn(0, SIDE, UL.BIP5VOLTS) EngUnits = UL.cbToEngUnits(0, UL.BIP5VOLTS, DataValue) else: get_reward(UL.FIRSTPORTA)
def record_port(self, volt_interval=UL.BIP10VOLTS): """Reads the electrical voltage and transforms \ the value with the scale factor and the offset. :param volt_interval: Interval of the electrical voltage of the machine :type volt_interval: int. :returns: The value of the machine :rtype: float """ data = UL.cbAIn(self.board.id, self.id, volt_interval) volt = UL.cbToEngUnits(self.board.id, volt_interval, data) return self.scale_factor * volt + self.offset
def lick_detection_no_reward(SIDE): EngUnits = 0 DataValue = 0 if SIDE == 0: while ((EngUnits) * (EngUnits))**0.5 < 1.5: DataValue = UL.cbAIn(0, SIDE, UL.BIP5VOLTS) EngUnits = UL.cbToEngUnits(0, UL.BIP5VOLTS, DataValue) else: print 'nope'
def updateVoltage(self, volt): global voltage, EngUnits, BoardNum, Chan, Gain, Conv, VtoA if self.isVoltageInRange(volt): self.setVoltage(volt) EngUnits = self.getVoltage() DataValue = UL.cbFromEngUnits(BoardNum, Gain, EngUnits * Conv, 0) UL.cbAOut(BoardNum, Chan, Gain, DataValue) self.vLabelUpdate(voltage, False) self.aLabelUpdate(voltage * VtoA, False) else: self.vLabelUpdate( "Your voltage is too high: It must be between " + str(4 / VtoA) + " and " + str(-4 / VtoA) + "Amps", True)
def __init__(self, args): #serial port setup self.boardNum = 0 self.serialPortName = args self.ser = serial.Serial(self.serialPortName, 9600, timeout=0) #DAQ setup UL.cbDConfigPort(self.boardNum, UL.FIRSTPORTA, UL.DIGITALOUT) UL.cbDConfigPort(self.boardNum,UL.FIRSTPORTB, UL.DIGITALOUT) #CSV logging setup self.timer = core.Clock() self.triggerTimes = [] self.stimCodes = []
def updateCurrent(self, amp): global current, EngUnits, BoardNum, Chan, Gain, Conv, VtoA, curUp, MAXCURRENT, MINCURRENT if amp <= MAXCURRENT and amp >= MINCURRENT: self.setCurrent(amp) EngUnits = self.getCurrent() / VtoA DataValue = UL.cbFromEngUnits(BoardNum, Gain, EngUnits * Conv, 0) UL.cbAOut(BoardNum, Chan, Gain, DataValue) self.aLabelUpdate(current) self.vLabelUpdate(current / VtoA) curUp = True curUp = False else: self.aLabel.setValue( "Your current is too high: It must be between 4 and -4 Amps")
def lick_detection(SIDE): EngUnits=0 DataValue=0 if SIDE==0: #threshold while ((EngUnits)*(EngUnits))**0.5<1.25: DataValue = UL.cbAIn(0, SIDE, UL.BIP5VOLTS) EngUnits = UL.cbToEngUnits(0, UL.BIP5VOLTS, DataValue) #print 1/(((EngUnits+1)*(EngUnits))**0.5) else: print EngUnits+1 print core.Clock() get_reward(UL.FIRSTPORTA)
def preStim(self, args): stimNumber = args #record the stim number we're about to display self.stimCodes.append(stimNumber) #send stimcode to CED via measurement computing UL.cbDOut(self.boardNum,UL.FIRSTPORTA,stimNumber) UL.cbDOut(self.boardNum,UL.FIRSTPORTB,1) #wait for 2pt frame trigger self.waitForSerial() #Tell ourselves to send the signal the CED as soon as we flip self.needToSendStimcode = True
def lick_detection(SIDE): EngUnits=0 DataValue=0 time.sleep(1.4) if SIDE==0: while ((EngUnits)*(EngUnits))**0.5<1.35: DataValue = UL.cbAIn(0, SIDE, UL.BIP5VOLTS) EngUnits = UL.cbToEngUnits(0, UL.BIP5VOLTS, DataValue) #print EngUnit else: print EngUnits print core.Clock() get_reward(UL.FIRSTPORTA)
def updateCurrent(self, amp): global current, EngUnits, BoardNum, Chan, Gain, Conv, VtoA, curUp if self.isCurrentInRange(amp): self.setCurrent(amp) EngUnits = self.getCurrent() / VtoA DataValue = UL.cbFromEngUnits(BoardNum, Gain, EngUnits * Conv, 0) UL.cbAOut(BoardNum, Chan, Gain, DataValue) self.aLabelUpdate(current, False) self.vLabelUpdate(current / VtoA, False) self.addCurrentVal(current) curUp = True curUp = False else: self.aLabelUpdate( "Your current is too high: It must be between 4 and -4 Amps", True)
def daq_thread_func(wxapp): TotalCount = 3000 ADData = numpy.zeros((TotalCount+512,), dtype=numpy.int16) BoardNum = 0 UDStat = 0 Gain = UL.BIP5VOLTS LowChan = 0 HighChan = 1 Rate = 20000 PretrigCount = 500 Options = UL.CONVERTDATA while 1: PretrigCount, TotalCount, Rate = UL.cbAPretrig (BoardNum, LowChan, HighChan, PretrigCount, TotalCount, Rate, Gain, ADData, Options) datacopy = ADData[:] wxapp.AddPendingEvent(TrigEvent(TotalCount,datacopy))
def startdisplayloop(self,samplefrequency,datalength): """Continuously updates graph and acquires data""" rawdata = np.zeros(((samplefrequency//2)-1),np.int16)#set the number of samples acquired per scan, for display at 2Hz Options = UL.CONVERTDATA raw_mean = np.zeros(1,np.int16) while 1: ActualRate = UL.cbAInScan(0, 1, 1, ((samplefrequency//2)-1), samplefrequency, Gain, rawdata, Options) #scan in data data.extend(rawdata) if len(data) > 10*samplefrequency: #cap length of data at 10 seconds del data[0:((samplefrequency//2)-1)] smalldata.append(np.mean(rawdata)) #add mean of scan to display data smalltimes.append( time.time()-tstart ) #add time points for display data if(len(smalldata)>20): smalldata.pop(0) smalltimes.pop(0) if self.trapalert.isChecked(): #if checking for trapping is enabled trapCheck = (np.mean(smalldata[10:18])-np.mean(smalldata[2:10])) #calculate the difference between two averages trapCheck = (trapCheck/np.mean(smalldata[2:10])) if(trapCheck > trapThreshold): #trappingThreshold self.stopdisplayclicked() self.sendemailalert() if self.driftalert.isChecked(): #if the voltage has depreciated by 75% if (np.mean(smalldata[1:18]) < (initialValue*driftThreshold)): self.stopdisplayclicked() self.sendemailalert() self.displaywindow.canvas.ax.clear() #clear plot self.displaywindow.canvas.ax.plot(smalltimes,smalldata,'g') #plot downsampled values self.displaywindow.canvas.draw() #force image redraw yield
def sampleCount(self): Chan = 0 DataValue = 0 try: self.Count = UL.cbCIn(self.BoardNum, Chan, DataValue) except: pass
def preStim(self, args): print 'Waiting for stimcode to arrive on DAQ...' stimcode = 0; while stimcode > 64 or stimcode == 0: #keep trying until a valid stimcode appears stimcode = UL.cbDIn(self.boardNum, UL.FIRSTPORTA, stimcode) print 'Got stimcode ',stimcode
def get_reward(PORTNUM): BoardNum = 0 PortNum = PORTNUM Direction = UL.DIGITALOUT UL.cbDConfigPort (BoardNum, PortNum, Direction) DataValue = 1 UL.cbDOut(BoardNum, PortNum, DataValue) time.sleep(.07) BoardNum = 0 PortNum = PORTNUM Direction = UL.DIGITALOUT UL.cbDConfigPort (BoardNum, PortNum, Direction) DataValue = 0 UL.cbDOut(BoardNum, PortNum, DataValue)
def Adquire(self, Ch = 0): RawData = numpy.zeros(self._NSamples, numpy.int16) OPTS = UL.DMAIO if self.Trigger <> 'Auto': OPTS = UL.DMAIO + UL.EXTTRIGGER if Ch not in([0,1]): Ch = 0 trueRate = UL.cbAInScan(0, Ch, Ch, self._NSamples, self._Rate, self._Range, RawData, OPTS) rpp = {'10V':20.0, '2.5V':5.0, '0.5V':1.0} voltsOut = numpy.uint16(RawData) * rpp[self.Range] / 2**16 - rpp[self.Range]/2.0 self.dT = 1.0/trueRate ts = numpy.arange(len(voltsOut)) * self.dT return ts, voltsOut
def poll(self): #global yo data=0 if self.success: if self.dir==0: #IN data = UL.cbDIn(0, self.port, data) if data==self.HIGH: #yo=time.time() return True else: return False else: return True
def sampleAllFast(self): Count = 300 Rate = 5000 Gain = UL.BIP5VOLTS Options = UL.CONVERTDATA + UL.BACKGROUND + UL.SINGLEIO ADData = numpy.zeros((Count, ), dtype=numpy.int16) UL.cbAInScan(self.BoardNum, 0, 2, Count, Rate, Gain, ADData, Options) time.sleep(Count / Rate) torqueVolts = UL.cbToEngUnits(self.BoardNum, Gain, int(numpy.mean(ADData[0::3]))) voltageVolts = UL.cbToEngUnits(self.BoardNum, Gain, int(numpy.mean(ADData[1::3]))) currentVolts = UL.cbToEngUnits(self.BoardNum, Gain, int(numpy.mean(ADData[2::3]))) print(torqueVolts, voltageVolts, currentVolts) self.Torque = 2.26 * torqueVolts - self.TorqueOffset self.Voltage = -1 * ( (voltageVolts - 2.5) * 20.2030 - self.VoltageOffset) self.Current = (currentVolts) / .02 - self.CurrentOffset
def startdisplayloop(self): """Continuously updates graph and acquires data""" counter = 0 #runtime counter, counts number of iterations while 1: counter = counter + 1 #increment counter """DAQ Capture and storage""" DataValue = UL.cbAIn(BoardNum, Chan, Gain)#raw input data EngUnits = UL.cbToEngUnits(BoardNum, Gain, DataValue)#convert raw data to volts data.append( EngUnits ) #DAQ at high frequency but not displayed times.append( time.time()-tstart ) #time stamps at high frequency but not displayed if(len(data)>10000): #10 second capture interval, upper bound = (capture frequency)*10 data.pop(0) #remove first data point in list times.pop(0) #remove first time point in list """DAQ downsample and display""" if counter % 1000: #downsampling by (1/(modulo value)) for display smalldata.append( EngUnits ) #add plotted data point smalltimes.append( time.time()-tstart ) #add plotted time point if(len(smalldata)>100):#len(data)/modulo value, defines number of points plotted smalldata.pop(0) #remove first plotted data point in the list smalltimes.pop(0) #remove first plotted time point in the list if self.trapalert.isChecked(): #if checking for trapping is enabled trapCheck = (np.mean(smalldata[10:50])-np.mean(smalldata[50:100])) #calculate the difference between two averages trapCheck = (trapCheck/np.mean(smalldata[10:15])) if(trapCheck > 0.20): #put trapping threshold here self.stopdisplayclicked() self.sendemailalert() if self.driftalert.isChecked(): #if the voltage has depreciated by 75% if (np.mean(smalldata[10:100]) < (initialValue*0.60)): self.stopdisplayclicked() self.sendemailalert() # force an image redraw on every 3rd data capture if counter % 2000: #downsampled values are plotted as they are added self.displaywindow.canvas.ax.clear() #clear plot self.displaywindow.canvas.ax.plot(smalltimes,smalldata,'g') #plot downsampled values self.displaywindow.canvas.draw() #force image redraw """Delay and yield for proper capture frequency""" time.sleep(0.001)#1kHz yield
def startdisplayclicked(self): """Starts the data display""" #start functions and update handles self.stopdisplayclicked() # Stop an existing timer if self.driftalert.isChecked(): DataValue = UL.cbAIn(BoardNum, Chan, Gain)#raw input data for drift check initialValue = UL.cbToEngUnits(BoardNum, Gain, DataValue)#convert raw data to volts QdriftThreshold = self.driftpercent.text() #get text from UI SdriftThreshold = str(QdriftThreshold) #convert to string driftThreshold = int(SdriftThreshold) #convert to int driftThreshold = driftThreshold/100 #convert to percent if self.trapalert.isChecked(): QtrapThreshold = self.trappercent.text() StrapThreshold = str(QtrapThreshold) trapThreshold = int(StrapThreshold) trapThreshold = trapThreshold/100 Qsamplefrequency = self.frequencyinput.text() #get sampling frequency from ui samplefrequency = int(Qsamplefrequency) datalength = 10*samplefrequency #10 second storing interval self._displayloop = self.startdisplayloop(samplefrequency,datalength) #start the display loop function self._timerId = self.startTimer(0) # idle timer
def get_reward(PORTNUM): print 'reward' BoardNum = 0 PortNum = PORTNUM Direction = UL.DIGITALOUT UL.cbDConfigPort (BoardNum, PortNum, Direction) DataValue = 1 UL.cbDOut(BoardNum, PortNum, DataValue) #sound_1 = sound.SoundPyo(value='C', secs=0.5, octave=4, stereo=True, volume=1.0, loops=0, sampleRate=44100, bits=16, hamming=True, start=0, stop=-1, name='', autoLog=True) #sound_1.play() time.sleep(.1) #time BoardNum = 0 PortNum = PORTNUM Direction = UL.DIGITALOUT UL.cbDConfigPort (BoardNum, PortNum, Direction) DataValue = 0 UL.cbDOut(BoardNum, PortNum, DataValue)
def startsweepdisplay(self,sweepfrequency): """Continuously updates graph and acquires data""" srawdata = np.zeros(((sweepfrequency//2)-1),np.int16)#set the number of samples acquired per scan, for display at 2Hz Options = UL.CONVERTDATA """Acquire data from the UI""" Qsweepmodulo = self.sweepmoduloinput.text() #get sweep modulo value from UI sweepmodulo = int(Qsweepmodulo) Qstarttemp = self.starttemp.text() #get starting temperature sweepstarttemp = int(Qstarttemp) Qstoptemp = self.stoptemp.text() #get ending temperature sweepstoptemp = int(Qstoptemp) """Set up serial port""" ser = serial.Serial(3) #COM4, must be equal to what com port the UT232R shows up as ser.baudrate = 9600 #Baud rate must match laser controller ser.bytesize = serial.EIGHTBITS #specific to RS-232 setup ser.parity = serial.PARITY_NONE #specific to RS-232 setup ser.stopbits = serial.STOPBITS_ONE #specific to RS-232 setup ser.write("TEC:T %d",sweepstoptemp) #set starting temperature numOfIterations = (10*sweepmodulo)*abs(sweepstarttemp-sweepstoptemp) #calculate the number of steps needed counter = 0 #counter for modulo while counter < numOfIterations: """DAQ Capture and storage""" ActualRate = UL.cbAInScan(0, 1, 1, ((sweepfrequency//2)-1), sweepfrequency, Gain, srawdata, Options) #scan in data sweepdata.extend(srawdata) sweepsmalldata.append(np.mean(srawdata)) #add plotted data point sweepsmalltimes.append( time.time()-tstart ) #add plotted time point # force an image redraw canvas self.sweepwindow.canvas.ax.clear() #clear plot self.sweepwindow.canvas.ax.plot(sweepsmalltimes,sweepsmalldata,'g') #plot downsampled values self.sweepwindow.canvas.draw() #force image redraw """Delay and yield for user input""" if (counter%sweepmodulo) == 0: #only happens when ser.write("TEC:INC") #increment TEC temperature counter = counter + 1 yield
def preStim(self, args): stimNumber = args #send stimcode to CED via measurement computing UL.cbDOut(self.boardNum,UL.FIRSTPORTA,stimNumber) UL.cbDOut(self.boardNum,UL.FIRSTPORTB,1) #wait for 2pt frame trigger self.waitForSerial() self.triggerTimes.append(self.timer.getTime()) self.stimCodes.append(stimNumber) #Tell CED to read stimcode #this costs 1.2ms (+/- 0.1ms). UL.cbDOut(self.boardNum,UL.FIRSTPORTB,0)
def daq_thread_func(wxapp): TotalCount = 3000 ADData = numpy.zeros((TotalCount + 512, ), dtype=numpy.int16) BoardNum = 0 UDStat = 0 Gain = UL.BIP5VOLTS LowChan = 0 HighChan = 1 Rate = 20000 PretrigCount = 500 Options = UL.CONVERTDATA while 1: PretrigCount, TotalCount, Rate = UL.cbAPretrig(BoardNum, LowChan, HighChan, PretrigCount, TotalCount, Rate, Gain, ADData, Options) datacopy = ADData[:] wxapp.AddPendingEvent(TrigEvent(TotalCount, datacopy))
def trigger(self, reset_time=-1): """Triggers a digital signal. :param reset_time: Time (in seconds) to pass until reset the value. \ If the reset_time will not set, the trigger will change \ the electrical voltage. :type reset_time: float. :returns: True if the signal was sent, False otherwise. :rtype: bool :raises: ValueError, ctypes.ArgumentError """ if reset_time < -1: raise ValueError("Invalid value: Value must positive") value = 0 if self.value == 255 else 255 if reset_time != -1: UL.cbDOut(self.board.id, self.id, value) sleep(reset_time) UL.cbDOut(self.board.id, self.id, self.value) else: UL.cbDOut(self.board.id, self.id, value) self.value = value return True
#collect data in a loop until user asks to stop nextSample='' #nextSample=input('enter next sample name:\n') nextSample=raw_input('enter next sample name:\n') if nextSample=='x': cont=0 else: cont=1 nextSample.replace(' ','_') #%% while cont==1: analogData=numpy.zeros((sampleNum,),dtype=numpy.int16) #actually collect the data print('starting data collection') actualRate = UL.cbAInScan(boardNum, lowChan, highChan, sampleNum, sampleRate, gain, analogData,Options) print('data collection complete') voltData = numpy.asarray([ UL.cbToEngUnits(boardNum, gain, int(y)) for y in analogData]) #take FFT #following matlab code to try and get scaling right--need to check complexFreqData=numpy.fft.fft(voltData)/sampleNum freqData=complexFreqData[:sampleNum/2+1] frequencies=actualRate*numpy.linspace(0,1,sampleNum/2+1) db=10*numpy.log10(2*numpy.abs(freqData)) plt.figure(figsize=(16,6),dpi=50) plt.subplot(2,1,1) fakeX=numpy.linspace(0,sampleNum,sampleNum)/actualRate downsample=100 plt.plot(fakeX[0::downsample],voltData[0::downsample],'-',linewidth=0.1)
# disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the California Institute of Technology nor # the names of its contributors may be used to endorse or promote # products derived from this software without specific prior # written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Author: Andrew Straw import UniversalLibrary as UL BoardNum = 0 PortNum = UL.FIRSTPORTA Direction = UL.DIGITALIN UL.cbDConfigPort(BoardNum, PortNum, Direction) DataValue = 0 while 1: DataValue = UL.cbDIn(BoardNum, PortNum, DataValue) print "Port Value:", DataValue
def __setTrig(self, keyTrig): if keyTrig not in(self.TriggersDictionary): keyTrig = 'Auto' if keyTrig <> 'Auto': UL.cbSetTrigger(0, self.TriggersDictionary[keyTrig], 0, 0) self._Trigger = keyTrig
def SetPower(VChanX, Percent): '''Set modulation voltage in % from 0 to 5V on a given channel - 100% = 5V''' Vout = UL.cbFromEngUnits( BoardNum, Gain, 5 * Percent / 100, 0) # convert from % to volt, and from volt to bytes UL.cbAOut(BoardNum, VChanX, Gain, Vout)
def Reset(): '''Set all digital channels (the entire port) to 0V output''' UL.cbDConfigPort(BoardNum, PortNum, UL.DIGITALOUT) UL.cbDOut(BoardNum, PortNum, 0)
def off(self): if self.success: if self.dir==1: #OUT self.currentState=self.LOW UL.cbDOut(0, self.port, self.LOW)
import UniversalLibrary as UL UL.cbDConfigPort(0,10,1) print('You are starting at angle 0 degrees') position=0 cmd='b' angle=0.0 while cmd.lower() != 'q': print('Current position = '),position print('Current delta angle request = '),angle cmd=raw_input('What to do now? (a: choose angle, p:set position value here, g:go,s:stop moving! q:quit) ') if cmd.lower() == 'a': anglestring=raw_input('Input angle to move by in +- degrees ' ) angle=float(anglestring) elif cmd.lower() == 'p': positionstring=raw_input('Input current position angle ' ) position=float(positionstring) elif cmd.lower()=='q' : chk=raw_input('Really quit? (y,n) ') if chk.lower()!='y': cmd='b' elif cmd.lower()=='g' : npulses=int(abs(angle)*80) dir=0 if angle < 0: dir=1 UL.cbDBitOut(0,10,1,dir) for i in range(0,npulses+1): try: UL.cbDBitOut(0,10,0,1) UL.cbDBitOut(0,10,0,0) except KeyboardInterrupt:
# copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the California Institute of Technology nor # the names of its contributors may be used to endorse or promote # products derived from this software without specific prior # written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Author: Andrew Straw import UniversalLibrary as UL BoardNum = 0 Chan = 0 Gain = UL.UNI4VOLTS # works on USB 1208FS EngUnits = 2.5 # Volts DataValue = UL.cbFromEngUnits(BoardNum, Gain, EngUnits, 0) UL.cbAOut(BoardNum, Chan, Gain, DataValue)
# * Neither the name of the California Institute of Technology nor # the names of its contributors may be used to endorse or promote # products derived from this software without specific prior # written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Author: Andrew Straw import UniversalLibrary as UL BoardNum = 0 Gain = UL.BIP5VOLTS Chan = 0 while 1: DataValue = UL.cbAIn(BoardNum, Chan, Gain) EngUnits = UL.cbToEngUnits(BoardNum, Gain, DataValue) print DataValue, EngUnits
def getCount(): Chan = 0; DataValue = 0 #return UL.cbCIn32(BoardNum, Chan, DataValue) return UL.cbCIn(BoardNum, Chan, DataValue)
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Author: Andrew Straw import UniversalLibrary as UL BoardNum = 0 devNum = 0 FirstPort = 0 FirstPort = UL.cbGetConfig(UL.DIGITALINFO, BoardNum, devNum, UL.DIDEVTYPE, FirstPort) PortNum = UL.FIRSTPORTA Direction = UL.DIGITALOUT UL.cbDConfigPort(BoardNum, PortNum, Direction) DataValue = 0 UL.cbDOut(BoardNum, PortNum, DataValue) if FirstPort == UL.AUXPORT: devNum = 1 UL.cbGetConfig(UL.DIGITALINFO, BoardNum, devNum, UL.DIDEVTYPE, FirstPort) if FirstPort == UL.FIRSTPORTA: FirstBit = 0 elif FirstPort == UL.FIRSTPORTB:
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Author: Andrew Straw import UniversalLibrary as UL import numpy BoardNum = 0 Gain = UL.BIP5VOLTS LowChan = 0 HighChan = 0 Rate = 2000 PretrigCount = 10 TotalCount = 700 ADData = numpy.zeros((TotalCount+512,), dtype=numpy.int16) Options = UL.CONVERTDATA PretrigCount, TotalCount, Rate = UL.cbAPretrig (BoardNum, LowChan, HighChan, PretrigCount, TotalCount, Rate, Gain, ADData, Options) ##Rate = UL.cbAInScan(BoardNum, LowChan, HighChan, Count, ## Rate, Gain, ADData, Options)
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Author: Andrew Straw import UniversalLibrary as UL import numpy BoardNum = 0 UDStat = 0 Gain = UL.BIP5VOLTS LowChan = 0 HighChan = 0 Count = 20 Rate = 3125 Options = UL.CONVERTDATA + UL.BACKGROUND + UL.SINGLEIO ADData = numpy.zeros((Count,), dtype=numpy.int16) print "a" Rate = UL.cbAInScan(BoardNum, LowChan, HighChan, Count, Rate, Gain, ADData, Options) Status = UL.RUNNING while Status == UL.RUNNING: print "b" Status, CurCount, CurIndex = cbGetStatus(BoardNum, Status, CurCount, CurIndex, UL.AIFUNCTION)
def on(self): #print 'ON: %s, %s' % (str(self.success),str(self.dir)) if self.success: if self.dir==1: #OUT self.currentState=self.HIGH UL.cbDOut(0, self.port, self.HIGH)
def __init__(self, args): #DAQ setup self.boardNum = 0 UL.cbDConfigPort(self.boardNum,UL.FIRSTPORTA, UL.DIGITALIN)
# <codecell> # example1.py import UniversalLibrary as UL import time BoardNum = 0 Gain = UL.BIP5VOLTS Chan = 0 tstart = time.time() data = [] times = [] while 1: DataValue = UL.cbAIn(BoardNum, Chan, Gain) data.append( DataValue ) times.append( time.time()-tstart ) if times[-1] > 1.0: break import pylab pylab.plot(times,data,'o-') pylab.xlabel('time (sec)') pylab.ylabel('ADC units') pylab.show() # <markdowncell> # When I ran this, I had a function generator generating a sine wave # connected to pins 1 and 2 of my device. This should produce a figure
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Author: Andrew Straw import UniversalLibrary as UL import numpy BoardNum = 0 Gain = UL.BIP5VOLTS LowChan = 0 HighChan = 0 Count = 10000 Rate = 3125 Options = UL.CONVERTDATA + UL.BACKGROUND + UL.SINGLEIO ADData = numpy.zeros((10000,), dtype=numpy.int16) # Note that one could do similar things with a multi-threaded program Rate = UL.cbAInScan(BoardNum, LowChan, HighChan, Count, Rate, Gain, ADData, Options) Status = UL.RUNNING CurCount = 0 CurIndex = 0 while Status==UL.RUNNING: Status, CurCount, CurIndex = UL.cbGetStatus(BoardNum, Status, CurCount, CurIndex, UL.AIFUNCTION)