def toggle(self): """ Digital modulation of Device via Digital output of NIDAQ board Toggles Device on if off and vice versa """ self._t_switch = not self._t_switch try: with nidaqmx.Task() as task: task.do_channels.add_do_chan(self.INPUT_PORT) task.write(self._t_switch, auto_start=True) except NotFoundException: print("DAQ device not found")
def set_trigger_state(self, value, return_to_zero_ms=None): """Sets the current trigger states to an 8-bit value. Arguments value - Unsigned 8-bit integer value, i.e. an int between 0 and 255. Passing anything else, even a float, will result in an Exception. Keyword Arguments return_to_zero_ms - Value (int or float) that indicates how long to wait before returning the trigger value to 0. None can be passed to not reset to 0 automatically, but instead to return straight after setting the trigger value. Default = None Returns t0, t1 t2 - t0 is the time of this function being called. t1 is the time of the trigger being sent t2 is the time of the 0 trigger being sent, or None if return_to_zero_ms==None. t1 and t2 are clocked directly after the write function returns, in seconds (time.time) """ # Start time. t0 = time.time() # Input sanity checks. if value < 0 or value > 255 or type(value) != int: raise Exception("ERROR: Invalid value '%s' (type=%s); please use an unsigned 8-bit integer!" \ % (value, type(value))) # Create a new Task to listen in on the button channels. with nidaqmx.Task() as task: # Add the digital output (do) channels. task.do_channels.add_do_chan("%s/%s" % \ (self._dev_name, self._trigger_channels)) # Write a single sample to each channel. task.write(value, timeout=0.1) t1 = time.time() # Pause if requested. if return_to_zero_ms is not None: time.sleep(return_to_zero_ms / 1000.0) task.write(0, timeout=0.1) t2 = time.time() else: t2 = None return t0, t1, t2
def start_measure(self): ## What happens when you click "start" ## self.start.setEnabled(False) self.stop.setEnabled(True) self.update_value() self.time_last_refresh=time.time() voltage_list=[self.V_0-self.dV/2]*self.nplus+[self.V_0+self.dV/2]*self.nplus self.voltage_out=nidaqmx.Task() self.voltage_out.ao_channels.add_ao_voltage_chan('Dev1/ao0') self.voltage_out.timing.cfg_samp_clk_timing(self.f_acq,sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS, samps_per_chan=self.n_acq) self.voltage_out.write(voltage_list) self.tension=nidaqmx.Task() self.tension.ai_channels.add_ai_voltage_chan("Dev1/ai11") self.tension.timing.cfg_samp_clk_timing(self.f_acq,sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS, samps_per_chan=self.n_acq) self.tension.triggers.start_trigger.cfg_dig_edge_start_trig('/Dev1/ao/StartTrigger') self.tension.start() self.hist_data=[] self.hist_data_plus=[] self.hist_data_moins=[] self.repeat=0 #Start the timer self.timer = QTimer(self,interval=0) self.timer.timeout.connect(self.take_point) self.voltage_out.start() self.timer.start()
def stop_measure(self): #A ameliorer en recuperant dirrectement les tasks depuis system.truc try : self.timer.stop() except : pass try : self.apd.close() except : pass try : self.sample_clock.close() except : pass try : self.PG.write('*RST') self.PG.write('*WAI') except : pass try : self.digout.close() self.digout=nidaqmx.Task() self.digout.do_channels.add_do_chan('Dev1/port0/line3') self.digout.write([False]) self.digout.close() self.digout=nidaqmx.Task() self.digout.do_channels.add_do_chan('Dev1/port0/line2') self.digout.write([True]) self.digout.close() except : pass self.stop.setEnabled(False) self.start.setEnabled(True)
def update_figure_send_controls(n, target_gap, target_speed, kp, kd, max_accel, min_accel, car_position): global X, Y0, Y1, CAN_VARIABLES X.append(datetime.now()) Y0.append(target_gap) # Check if the gap has become zero and take the previous value if CAN_VARIABLES[1] < 1.2: CAN_VARIABLES[1] = Y1[-1] Y1.append(CAN_VARIABLES[1]) # Control Input if car_position == 'Following': a_control = kp*(CAN_VARIABLES[1] - target_gap) + kd*(target_speed - CAN_VARIABLES[0])*0.44704 else: a_control = - kp*(CAN_VARIABLES[1] - target_gap) + kd*(target_speed - CAN_VARIABLES[0])*0.44704 if a_control > max_accel: a_control = max_accel elif a_control < min_accel: a_control = min_accel # Acceleration pedal input accel_pedal_per = PEDAL_MODEL.pedal_per(CAN_VARIABLES[0]*0.44704, a_control) # Send the voltages v0, v1 = PEDAL_MODEL.voltage_from_pedal(accel_pedal_per) with nidaqmx.Task() as task: task.ao_channels.add_ao_voltage_chan(DEV + "/ao0") task.ao_channels.add_ao_voltage_chan(DEV + "/ao1") task.write([v0, v1], auto_start=True) if len(X) >= PROPS_VIS['points_per_plot']: X.pop(0) Y0.pop(0) Y1.pop(0) TRACES0 = go.Scatter( x = X, y = Y0, mode = 'lines+markers', name = 'target_gap_m' ) TRACES1 = go.Scatter( x = X, y = Y1, mode = 'lines+markers', name = 'real_gap_m' ) return { 'data': [TRACES0, TRACES1] }
def channelsOpenStep(self): """ Open and Config of all the channels for use step by step""" if self.channelramp: self.done() if self.channelsteps: print("Ya estan abiertos los canales step") # to dont open again # usando esto podria no cerrarlos nunca. else: self.channelsteps = True # Create all the channels self.aotask = nidaqmx.Task('aotask') # self.dotask = nidaqmx.Task('dotask') # self.aitask = nidaqmx.Task('aitask') # self.ditask = nidaqmx.Task('ditask') self.citask = nidaqmx.Task('citask') # Configure the counter channel to read the APD self.citask.ci_channels.add_ci_count_edges_chan( counter='Dev1/ctr0', name_to_assign_to_channel=u'conter', initial_count=0) totalcinumber = self.Napd + 1 self.citask.timing.cfg_samp_clk_timing( rate=self.apdrate, sample_mode=nidaqmx.constants.AcquisitionType.FINITE, source=r'100kHzTimebase', samps_per_chan=totalcinumber) # Following loop creates the voltage channels for n in range(len(self.AOchans)): self.aotask.ao_channels.add_ao_voltage_chan( physical_channel='Dev1/ao%s' % self.AOchans[n], name_to_assign_to_channel='chan_%s' % self.activeChannels[n], min_val=minVolt[self.activeChannels[n]], max_val=maxVolt[self.activeChannels[n]])
def FetchDAQ(clk, Npts, dev, ch_read): readtask = nidaqmx.Task() # print(ch_read) readtask.ai_channels.add_ai_voltage_chan(ch_read, min_val=0, max_val=5) readtask.timing.cfg_samp_clk_timing( clk, sample_mode=AcquisitionType.CONTINUOUS, samps_per_chan=int(Npts)) data = readtask.read(number_of_samples_per_channel=int(Npts)) readtask.close() return data
def __init__(self, channel, debug=False, dummy=False): self.debug = debug self.dummy = dummy self.channel = channel if not self.dummy: #self.task= nidaqmx.Task() #self.task.close() self.task = nidaqmx.Task() self.task.ai_channels.add_ai_voltage_chan(channel)
def reset_tasks(self,cfg,n): self._clear_tasks() self.ao_scan.dq_task=dq.Task(new_task_name="Scan") self.ao_scan.dq_task.ao_channels.add_ao_voltage_chan(self.device.name+"/ao"+cfg['CAVITY']['OutputChannel']) self.ao_laser.dq_task=dq.Task(new_task_name="Lasers") self.ao_laser._channel_no=0 self.power_PDs.dq_task=dq.Task(new_task_name="Power") self.power_PDs._channel_no=0 self.ai_PDs.dq_task=dq.Task(new_task_name="PDs") self.ai_PDs.dq_task.ai_channels.add_ai_voltage_chan(self.device.name+"/ai"+cfg['CAVITY']['InputChannel']) self.ai_PDs._channel_no=1 self.add_laser(int(cfg['LASER1']['InputChannel']),int(cfg['LASER1']['OutputChannel']),int(cfg['LASER1']['PowerChannel'])) if n>1: self.add_laser(int(cfg['LASER2']['InputChannel']),int(cfg['LASER2']['OutputChannel']),int(cfg['LASER2']['PowerChannel'])) #Timing (synchronisation) has to be set every time we recreate a task. self.set_input_timing()
def get_di_state(self, port, di_channel): """Measures the state of a digital Input of a of NI DAQ mx card :param port: (str) port name ['port0'] :param channel: (str) channel name ['line1'] """ channel = self._gen_di_ch_path(port, di_channel) with nidaqmx.Task() as task: task.di_channels.add_di_chan( channel, line_grouping=nidaqmx.constants.LineGrouping.CHAN_PER_LINE) return task.read(number_of_samples_per_channel=1) return -1
def activa_salida_digital(): #nidaqmx._task_modules.channels.channel.Channel #nidaqmx.system._collections.PhysicalChannelCollection with daq.Task() as task: #daq.constants.ChannelType(10153) task.do_channels.add_do_chan( "Dev13/port0/line0", line_grouping=LineGrouping.CHAN_PER_LINE) #samples = [True] while (True): time.sleep(periodoPWM) task.write(False) time.sleep(periodoPWM) task.write(True)
def __init__(self): """Assumes first device by default.""" self.system = nidaqmx.system.System.local() self.task = nidaqmx.Task() self.sampleSize = 100 self.buffer = numpy.zeros(self.sampleSize) self.reader = ASCR(self.task.in_stream) if len(self.system.devices) > 0: self.device = self.system.devices[0] else: raise RuntimeError("NIDAQmx device not found during init." \ + " Please make sure a NI device is connected.") self.devAddr = self.device.name + '/ai0'
def update_tasks(self, ao_channels, ai_channels, power_channels): self._clear_tasks() self.ao_scan.dq_task = dq.Task(new_task_name="Scan") self.ao_scan.dq_task.ao_channels.add_ao_voltage_chan(ao_channels[0]) self.ao_laser.dq_task = dq.Task(new_task_name="Lasers") for ch in ao_channels[1:]: self.ao_laser.dq_task.ao_channels.add_ao_voltage_chan(ch) self.ai_PDs.dq_task = dq.Task(new_task_name="PDs") for ch in ai_channels: self.ai_PDs.dq_task.ai_channels.add_ai_voltage_chan(ch) self.power_PDs.dq_task = dq.Task(new_task_name="Power") for ch in power_channels: self.power_PDs.dq_task.ai_channels.add_ai_voltage_chan(ch) try: self.set_input_timing() except: raise Exception('Input timing was not set.')
def TempratureMeasurement(device_name, ports, round_time, rounds): import matplotlib.pyplot as plt plt.ion() i = 0 with daq.Task() as task: task.ai_channels.add_ai_thrmcpl_chan(device_name + '/ai' + ports) while i < rounds: data = task.read(number_of_samples_per_channel=1) plt.scatter(i.data[0], c='r') plt.scatter(i.data[1], c='b') plt.pause(round_time) i += 1 print data
def openall(aoi=0, aof=3, aii=0, aif=31, read=True, write=False, clock=False, sample_rate=500000, initial_delay=0, duty_cycle=0.5, samps_per_chan=1): ''' 4 output channels, 32 input channels duty cycle = pulse width / pulse period clock must involve read and write ''' ad = address() rs = ad.lookup(mdlname) # Instrument's Address print(type(rs)) read_task, write_task, clock_task, max_samp_rate, writer, reader = None, None, None, None, None, None if read: read_task = nidaqmx.Task() read_task.ai_channels.add_ai_voltage_chan("%s/ai%s:%s" %(rs,aii,aif), terminal_config=TerminalConfiguration.RSE, min_val=-10, max_val=10) if write: write_task = nidaqmx.Task() write_task.ao_channels.add_ao_voltage_chan("%s/ao%s:%s" %(rs,aoi,aof)) # write_task.ao_channels.add_ao_func_gen_chan if clock and write and read: # one-shot data streaming # Use a counter output pulse train task as the sample clock source for both the AI and AO tasks. max_samp_rate = read_task.timing.samp_clk_max_rate print("Max reading rate: %s" %max_samp_rate) sample_rate = floor(min(sample_rate, max_samp_rate)) clock_task = nidaqmx.Task() clock_task.co_channels.add_co_pulse_chan_freq('{0}/ctr0'.format(rs), freq=sample_rate, initial_delay=initial_delay, duty_cycle=duty_cycle) clock_task.timing.cfg_implicit_timing(sample_mode=AcquisitionType.FINITE, samps_per_chan=samps_per_chan) samp_clk_terminal = '/{0}/Ctr0InternalOutput'.format(rs) write_task.timing.cfg_samp_clk_timing(sample_rate, source=samp_clk_terminal, active_edge=Edge.RISING, samps_per_chan=samps_per_chan) read_task.timing.cfg_samp_clk_timing(sample_rate, source=samp_clk_terminal, active_edge=Edge.FALLING, samps_per_chan=samps_per_chan) # Single Channel: writer = AnalogSingleChannelWriter(write_task.out_stream) # reader = AnalogSingleChannelReader(read_task.in_stream) # Multi Channel: # writer = AnalogMultiChannelWriter(write_task.out_stream) reader = AnalogMultiChannelReader(read_task.in_stream) pack = dict(write_task=write_task, read_task=read_task, clock_task=clock_task, max_samp_rate=max_samp_rate, writer=writer, reader=reader) return pack
def set_ao_voltage(self, ao_channel, voltages): """Set analog output of NI DAQ mx card to a series of voltages :ao_channel: (str) Name of output channel (e.g. 'ao1', 'ao2') :voltages: (list of int) list of voltages which will be output """ # TODO: Understand the timing between output voltages (sample-wise?) channel = self._gen_ch_path(ao_channel) with nidaqmx.Task() as task: task.ao_channels.add_ao_voltage_chan(channel) task.write(voltages, auto_start=True)
def write_clk_manual(self, c, boolean): """ CLK Manual value is always False. """ if self.seq_task_clk: # Make sure task is close before you add new stuffs. self.seq_task_clk.close() self.seq_task_clk = None with nidaqmx.Task() as task: task.do_channels.add_do_chan('Dev0/port0/line0') task.write(boolean, auto_start=True) task.stop()
def digital_out(): with nidaqmx.Task() as task: task.do_channels.add_do_chan('Dev1/port0/line0') task.timing.cfg_samp_clk_timing( 100, sample_mode=nidaqmx.constants.AcquisitionType.FINITE, samps_per_chan=200) signal = [True, False] * 5 task.write(signal) task.start() while not task.is_task_done(): pass
def write_ao_manual(self, c, voltage, port): """ Writes Voltage for ONE channel that we are interested in. """ if self.seq_task_ao: # Make sure task is close before you add new stuffs. self.seq_task_ao.close() self.seq_task_ao = None with nidaqmx.Task() as task: task.ao_channels.add_ao_voltage_chan('Dev2/ao{}'.format(port)) task.write(voltage, auto_start=True) task.stop()
def __init__(self, dev='Dev1/ao0', volt=0.0): try: with nidaqmx.Task() as task: task.ao_channels.add_ao_voltage_chan(dev) task.write(volt) task.stop() # task.close() except (OSError, nidaqmx.errors.Error): print('ERROR')
def start_measure(self): ## What happens when you click "start" ## self.start.setEnabled(False) self.stop.setEnabled(True) #Read integration input values self.update_value() self.tension = nidaqmx.Task() self.tension.ai_channels.add_ai_voltage_chan("Dev1/ai11", min_val=-10, max_val=10) self.tension.ai_channels.add_ai_voltage_chan("Dev1/ai13", min_val=-10, max_val=10) self.tension.timing.cfg_samp_clk_timing( self.f_acq, sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS, samps_per_chan=self.n_tot) self.voltage_out = nidaqmx.Task() self.voltage_out.ao_channels.add_ao_voltage_chan('Dev1/ao0') self.voltage_out.timing.cfg_samp_clk_timing( self.f_acq, sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS, samps_per_chan=self.n_tot) self.voltage_out.write(self.V_list) self.tension.triggers.start_trigger.cfg_dig_edge_start_trig( '/Dev1/ao/StartTrigger') self.tension.start() self.repeat = 1 #Start the task, then the timer self.voltage_out.start() self.timer.start()
def __init__(self,dev,name,channel): self.dq_task=dq.Task(new_task_name=name) self.dq_task.ao_channels.add_ao_voltage_chan(dev.name+"/ao"+str(channel)) self.n_samples=0 self.scan_time=0 self.sample_rate=0 self.scan_points=0 self.scan_step=0 self.offset=0 self.mn_voltage=0 self.mx_voltage=0 self.scan_end=0 self.amplitude=0
def do2(): with nidaqmx.Task() as task: task.do_channels.add_do_chan('Dev1/port0/line1') out_stream = nidaqmx._task_modules.out_stream.OutStream(task) task.timing.cfg_samp_clk_timing( 10000, sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS) signal = np.zeros(100) for i in range(len(signal)): if i % 2 == 0: signal[i] = 1 signal = np.float64(signal) #print (signal[0].dtype) task.write([False, True], auto_start=True)
def get_ai_voltage(self, ai_channel, num_samples=1, max_range=10.0): """Measures the analog input voltage of NI DAQ mx card :param ao_channel: (str) Name of output channel (e.g. 'ao1', 'ao2') :aram num_samplies: (int) Number of samples to take :param max_range: (float) Maximum range of voltage that will be measured """ channel = self._gen_ch_path(ai_channel) with nidaqmx.Task() as task: task.ai_channels.add_ai_voltage_chan(channel) task.ai_channels[0].ai_rng_high = max_range return task.read(number_of_samples_per_channel=num_samples) return -1
def auto_xlims(self): with nidaqmx.Task() as tension: tension.ai_channels.add_ai_voltage_chan("Dev1/ai11") tension.timing.cfg_samp_clk_timing( 1000, sample_mode=nidaqmx.constants.AcquisitionType.FINITE, samps_per_chan=1000) tension.start() lecture = tension.read(1000) self.xmin = min(lecture) self.lectxmin.setText('%3.2e' % self.xmin) self.xmax = max(lecture) self.lectxmax.setText('%3.2e' % self.xmax)
def test_pulse_ticks_1_samp(self, x_series_device, seed): # Reset the pseudorandom number generator with seed. random.seed(seed) high_ticks = random.randint(100, 1000) low_ticks = random.randint(100, 1000) starting_edge = random.choice([Edge.RISING, Edge.FALLING]) # Select random counters from the device. counters = random.sample(self._get_device_counters(x_series_device), 2) with nidaqmx.Task() as write_task, nidaqmx.Task() as read_task: write_task.co_channels.add_co_pulse_chan_ticks( counters[0], '/{0}/100kHzTimebase'.format(x_series_device.name), high_ticks=high_ticks, low_ticks=low_ticks) write_task.timing.cfg_implicit_timing( sample_mode=AcquisitionType.CONTINUOUS) read_task.ci_channels.add_ci_pulse_chan_ticks( counters[1], source_terminal='/{0}/100kHzTimebase'.format( x_series_device.name), min_val=100, max_val=1000) read_task.ci_channels.all.ci_pulse_ticks_term = ( '/{0}InternalOutput'.format(counters[0])) read_task.ci_channels.all.ci_pulse_ticks_starting_edge = ( starting_edge) read_task.start() write_task.start() value_read = read_task.read(timeout=2) write_task.stop() assert value_read.high_tick == high_ticks assert value_read.low_tick == low_ticks
def medicion(): with nidaqmx.Task() as task: conf_medir(task, sample_rate) medir(task, sample_per_channel) plt.plot(np.arange(samples_per_channel) / sample_rate, data0, 's-', label='Canal 0') plt.xlabel('seg') plt.ylabel('V') plt.legend(loc='upper right') plt.show()
def test_reference_trigger(self, x_series_device, seed): # Reset the pseudorandom number generator with seed. random.seed(seed) counter = random.choice(self._get_device_counters(x_series_device)) with nidaqmx.Task() as task: task.co_channels.add_co_pulse_chan_freq(counter) with pytest.raises(DaqError) as e: task.triggers.reference_trigger.trig_type = ( TriggerType.NONE) assert e.value.error_code == -200452
def setup_DAQmx(self): self.read_task = nidaqmx.Task() self.write_task = nidaqmx.Task() self.sample_clk_task = nidaqmx.Task() # Use a counter output pulse train task as the sample clock source # for both the AI and AO tasks. self.sample_clk_task.co_channels.add_co_pulse_chan_freq( 'Dev1/ctr0', freq=self.sample_rate, idle_state=Level.LOW) self.sample_clk_task.timing.cfg_implicit_timing( sample_mode=AcquisitionType.CONTINUOUS, samps_per_chan=self.number_of_samples) self.sample_clk_task.control(TaskMode.TASK_COMMIT) samp_clk_terminal = '/Dev1/Ctr0InternalOutput' self.read_task.ai_channels.add_ai_voltage_chan(self.input_channel, max_val=10, min_val=-10) self.read_task.timing.cfg_samp_clk_timing( self.sample_rate, source=samp_clk_terminal, active_edge=Edge.FALLING, sample_mode=AcquisitionType.CONTINUOUS, samps_per_chan=self.number_of_samples) self.write_task.ao_channels.add_ao_voltage_chan(self.output_channel, max_val=10, min_val=-10) self.write_task.timing.cfg_samp_clk_timing( self.sample_rate, source=samp_clk_terminal, active_edge=Edge.FALLING, sample_mode=AcquisitionType.CONTINUOUS, samps_per_chan=self.number_of_samples) self.write_task.out_stream.regen_mode = RegenerationMode.DONT_ALLOW_REGENERATION self.write_task.out_stream.auto_start = False self.writer = AnalogSingleChannelWriter(self.write_task.out_stream) self.reader = AnalogMultiChannelReader(self.read_task.in_stream)
def __init__(self, device, shutter_prt='/port1/line1', direction_prt='/port1/line3'): #open file where we will store the last position try: f = open(device + '_last_position.txt', 'r') self._position = float(f.readline()) print(self.position) f.close() except: print( "there was an error trying to load the data from last_position.txt" ) self._position = 0.0 else: print(f'successfully loaded last position for {device}\n') #makes testing easier since trying to access a channel that doesn't exist #or is in use will cause the program to crash try: self.shutter = nidaqmx.Task() #task to control the shutter self.shutter.do_channels.add_do_chan(device + shutter_prt) self.shutter.start() self.direction = nidaqmx.Task() self.direction.do_channels.add_do_chan(device + direction_prt) self.direction.start() except: print( f'the device or channel name you entered for {device} may be incorrect or you may have an unclosed window running' ) print( f'you will be unable to send commands to this daq: {device}\n') self.name = device self.frequency = 2000 #frequency of pulses generated