def run(self):
        '''
        Code to execute immediately prior to the beginning of the task FSM executing, or after the FSM has finished running. 
        See riglib.experiment.Experiment.run(). This 'run' method stops the NIDAQ sink after the FSM has finished running
        '''

        try:
            super(RelayBlackrock, self).run()
        finally:
            self.nidaq.stop()

            # Remotely stop the recording on the blackrock box
            import comedi
            import config
            import time
            com = comedi.comedi_open("/dev/comedi0")
            time.sleep(0.5)
            # strobe pin should already be low

            # set last data pin ("D15"; 16th pin) low
            comedi.comedi_dio_bitfield2(com, 0, 1, 0, 15)

            # set strobe pin high
            comedi.comedi_dio_bitfield2(com, 0, 1, 1, 16)

            # set strobe pin low
            comedi.comedi_dio_bitfield2(com, 0, 1, 0, 16)
Ejemplo n.º 2
0
    def run(self):
        '''
        Code to execute immediately prior to the beginning of the task FSM executing, or after the FSM has finished running. 
        See riglib.experiment.Experiment.run(). This 'run' method stops the NIDAQ sink after the FSM has finished running
        '''

        try:
            super(RelayBlackrock, self).run()
        finally:
            self.nidaq.stop()

            # Remotely stop the recording on the blackrock box
            import comedi
            import config
            import time
            com = comedi.comedi_open("/dev/comedi0")
            time.sleep(0.5)
            # strobe pin should already be low

            # set last data pin ("D15"; 16th pin) low
            comedi.comedi_dio_bitfield2(com, 0, 1, 0, 15)

            # set strobe pin high
            comedi.comedi_dio_bitfield2(com, 0, 1, 1, 16)

            # set strobe pin low
            comedi.comedi_dio_bitfield2(com, 0, 1, 0, 16)
Ejemplo n.º 3
0
    def measure(self,arange,aref,num_scans):
        device = _comedi.comedi_open(comedidev)
        if not device:
             raise Exception('error opening Comedi device {}'.format(
                comedidev))
        setup_read_insn = SetupReadInsn(
            subdevice=subdevice, channel=channel,
            aref=aref, range=arange, n_scan=num_scans)

        insns = setup_insns(
            device, [setup_gtod_insn, setup_read_insn, setup_gtod_insn])
        ret = _comedi.comedi_do_insnlist(device, insns)
        if ret != insns.n_insns:
            raise Exception('error running instructions ({})'.format(ret))
            ret = _comedi.comedi_close(device)
            if ret != 0:
                raise Exception('error closing Comedi device')

        array = _comedi.insn_array.frompointer(insns.insns)
        t1 = get_time_of_day(array[0])
        t2 = get_time_of_day(array[2])
        data = _comedi.lsampl_array.frompointer(array[1].data)
        vals = []
        for i in range(array[1].n):
            vals.append(data[i])
        #sig=str((sum(vals) / float(len(vals))))
        sig=float(median(vals))
        free_insns(insns)
        ret = _comedi.comedi_close(device)
        return(sig)
    def cleanup(self, database, saveid, **kwargs):
        '''
        Function to run at 'cleanup' time, after the FSM has finished executing. See riglib.experiment.Experiment.cleanup
        This 'cleanup' method remotely stops the plexon file recording and then links the file created to the database ID for the current TaskEntry
        '''
        # Stop recording
        import comedi
        import config
        import time

        com = comedi.comedi_open("/dev/comedi0")
        comedi.comedi_dio_bitfield2(com, 0, 16, 16, 16)

        super(RelayPlexon, self).cleanup(database, saveid, **kwargs)

        # Sleep time so that the plx file has time to save cleanly
        time.sleep(2)
        dbname = kwargs['dbname'] if 'dbname' in kwargs else 'default'
        if self.plexfile is not None:
            if dbname == 'default':
                database.save_data(self.plexfile, "plexon", saveid, True, False)
            else:
                database.save_data(self.plexfile, "plexon", saveid, True, False, dbname=dbname)
        else:
            print '\n\nPlexon file not found properly! It will have to be manually linked!\n\n'
Ejemplo n.º 5
0
 def open(self):
     """Starts commmunication with the device, must be called before any
 set_cmd or get_data"""
     self.device = c.comedi_open(self.device_name)
     for chan in self.channels:
         chan['maxdata'] = c.comedi_get_maxdata(self.device, self.subdevice,
                                                chan['num'])
         chan['range_ds'] = c.comedi_get_range(self.device, self.subdevice,
                                               chan['num'],
                                               chan['range_num'])
     for chan in self.out_channels:
         chan['maxdata'] = c.comedi_get_maxdata(self.device,
                                                self.out_subdevice,
                                                chan['num'])
         chan['range_ds'] = c.comedi_get_range(self.device,
                                               self.out_subdevice,
                                               chan['num'],
                                               chan['range_num'])
         c.comedi_dio_config(self.device, 2, chan['num'], 1)
         c.comedi_dio_write(self.device, 2, chan['num'], 1)
     if any([i['make_zero'] for i in self.channels]):
         off = self.eval_offset()
         for i, chan in enumerate(self.channels):
             if chan['make_zero']:
                 chan['offset'] += off[i]
Ejemplo n.º 6
0
    def __init__(self, device="/dev/comedi0", subdevice=1, channel=0, range_num=0, gain=1, offset=0):
        """Convert wanted tension value into digital values and send it to the 
		output of some Comedi-controlled card.
		
		Output is (command * gain) + offset.
		
		Parameters
		----------
		device : str, default = '/dev/comedi0'
			Path to the device.
		subdevice : int, default = 1
			Subdevice 1 is the output.
		channel : int, default = 0
			The desired output channel.
		range_num : int, default = 0
			See the comedi documentation for different values.
		gain : float, default = 1
			Multiplication gain for the output.
		offset : float, default = 0
			Add this value to your output.
		"""
        self.subdevice = 1  # delete as argument
        self.channel = channel
        self.range_num = range_num
        self.gain = gain
        self.offset = offset
        self.device = c.comedi_open(device)
        self.maxdata = c.comedi_get_maxdata(self.device, self.subdevice, self.channel)
        self.range_ds = c.comedi_get_range(self.device, self.subdevice, self.channel, self.range_num)
        c.comedi_dio_config(self.device, 2, self.channel, 1)
Ejemplo n.º 7
0
class stimulus_pulse(object):
    com = comedi.comedi_open('/dev/comedi0')

    def __init__(self, *args, **kwargs):
        #self.com = comedi.comedi_open('/dev/comedi0')
        super(stimulus_pulse, self).__init__(*args, **kwargs)
        subdevice = 0
        write_mask = 0x800000
        val = 0x000000
        base_channel = 0
        comedi.comedi_dio_bitfield2(self.com, subdevice, write_mask, val,
                                    base_channel)

    def pulse(self, ts):
        #super(stimulus_pulse, self).pulse()
        subdevice = 0
        write_mask = 0x800000
        val = 0x000000
        base_channel = 0
        while ts < 0.4:
            val = 0x800000
            comedi.comedi_dio_bitfield2(self.com, subdevice, write_mask, val,
                                        base_channel)
        else:
            val = 0x000000
            comedi.comedi_dio_bitfield2(self.com, subdevice, write_mask, val,
                                        base_channel)
Ejemplo n.º 8
0
 def __init__(self,
              K=1,
              Ki=0,
              Kd=0,
              device='/dev/comedi0',
              subdevice=1,
              channel=0,
              range_num=1,
              gain=1,
              offset=0,
              out_min=0,
              out_max=4.095):
     self.subdevice = subdevice
     self.channel = channel
     self.range_num = range_num
     self.device0 = c.comedi_open(device)
     self.maxdata = c.comedi_get_maxdata(self.device0, self.subdevice,
                                         self.channel)
     self.range_ds = c.comedi_get_range(self.device0, self.subdevice,
                                        self.channel, self.range_num)
     self.out = 0
     self.gain = gain
     self.offset = offset
     self.I_term = 0
     self.last_sensor_input = 0
     self.K = K
     self.Ki = Ki
     self.Kd = Kd
     self.last_time = time.time()
     self.out_min = out_min
     self.out_max = out_max
     self.last_output = 0
    def cleanup(self, database, saveid, **kwargs):
        '''
        Function to run at 'cleanup' time, after the FSM has finished executing. See riglib.experiment.Experiment.cleanup
        This 'cleanup' method remotely stops the plexon file recording and then links the file created to the database ID for the current TaskEntry
        '''
        # Stop recording
        import comedi
        import time

        com = comedi.comedi_open("/dev/comedi0")
        comedi.comedi_dio_bitfield2(com, 0, 16, 16, 16)

        super(RelayPlexon, self).cleanup(database, saveid, **kwargs)

        # Sleep time so that the plx file has time to save cleanly
        time.sleep(2)
        dbname = kwargs['dbname'] if 'dbname' in kwargs else 'default'
        if self.plexfile is not None:
            if dbname == 'default':
                database.save_data(self.plexfile, "plexon", saveid, True,
                                   False)
            else:
                database.save_data(self.plexfile,
                                   "plexon",
                                   saveid,
                                   True,
                                   False,
                                   dbname=dbname)
        else:
            print(
                '\n\nPlexon file not found properly! It will have to be manually linked!\n\n'
            )
Ejemplo n.º 10
0
def imagecapture_part(xb, yb, xe, ye, nx, ny, n):
    dev = comedi.comedi_open("/dev/comedi0")
    outsubdevice = 1
    insubdevice = 0
    xchannel = 0
    ychannel = 1
    inchannel = 0
    analogref = comedi.AREF_GROUND
    arange =  0

    image = numpy.zeros((nx,ny), float)
	
    for y in range(ny, 0, -1):
        y = y-1
        write_data = int(  (float(y)/(ny-1) *(ye-yb) + yb ) * 65535)
        msg = comedi.comedi_data_write(dev, outsubdevice, ychannel, arange, analogref, write_data)
        for x in range(0, nx):
#            print "( " + str(x) + ", " + str(y) + ")" 
            write_data = int(  (float(x)/(nx-1) * (xe-xb) + xb ) * 65535)
            msg = comedi.comedi_data_write(dev, outsubdevice, xchannel, arange, analogref, write_data)
            pixel = 0.0
            for i in range(0, n):
                result = comedi.comedi_data_read(dev,insubdevice,inchannel,arange,analogref)
                pixel = pixel + float(result[1])
            pixel = pixel/n
#            print pixel,
            msg=result[0]
            image[x][y] = pixel
        print
		
    comedi.comedi_close(dev)
    return image
Ejemplo n.º 11
0
 def __init__(self, subdevice = c.COMEDI_SUBD_AI):
     self.device = c.comedi_open('/dev/comedi0')
     self.subdevice = c.comedi_find_subdevice_by_type(self.device, subdevice, 0)
     self.numChannels = c.comedi_get_n_channels(self.device, self.subdevice)
     self.numRanges = c.comedi_get_n_channels(self.device, self.subdevice)
     self.channelRange = c.comedi_get_range(self.device, self.subdevice, 0, 0)
     self.maxdata = c.comedi_get_maxdata(self.device, 0, 0)
Ejemplo n.º 12
0
def getimage(nx, ny, n):
	dev = comedi.comedi_open("/dev/comedi0")
	outsubdevice = 1
	insubdevice = 0
	xchannel = 0
	ychannel = 1
	inchannel = 0
	analogref = comedi.AREF_GROUND
	arange =  0
	
	image = numpy.zeros((nx,ny), float)
	
	for y in range(0, ny):
		write_data = int(  (float(y)/(ny-1) ) * 65535)	
		msg = comedi.comedi_data_write(dev, outsubdevice, ychannel, arange, analogref, write_data)
		for x in range(0, nx):
			write_data = int(  (float(x)/(nx-1) ) * 65535)
			msg = comedi.comedi_data_write(dev, outsubdevice, xchannel, arange, analogref, write_data)
			pixel = 0.0
			for i in range(0, n):
				result = comedi.comedi_data_read(dev,insubdevice,inchannel,arange,analogref)
				pixel = pixel + float(result[1])
			pixel = pixel/n
#			print pixel,
			msg=result[0]
			image[x][y] = pixel
#		print
		
	comedi.comedi_close(dev)
	return pixel
Ejemplo n.º 13
0
 def __init__(self, subdevice=c.COMEDI_SUBD_AI):
     self.device = c.comedi_open('/dev/comedi0')
     self.subdevice = c.comedi_find_subdevice_by_type(
         self.device, subdevice, 0)
     self.numChannels = c.comedi_get_n_channels(self.device, self.subdevice)
     self.numRanges = c.comedi_get_n_channels(self.device, self.subdevice)
     self.channelRange = c.comedi_get_range(self.device, self.subdevice, 0,
                                            0)
     self.maxdata = c.comedi_get_maxdata(self.device, 0, 0)
Ejemplo n.º 14
0
 def __init__(self,device='/dev/comedi0',subdevice=0,channel=1,range_num=0,gain=1,offset=0): 
   self.subdevice=subdevice
   self.channel=channel
   self.range_num=range_num
   self.device0=c.comedi_open(device)
   self.maxdata=c.comedi_get_maxdata(self.device0,self.subdevice,self.channel)
   self.range_ds=c.comedi_get_range(self.device0,self.subdevice,self.channel,self.range_num)
   self.gain=gain
   self.offset=offset
Ejemplo n.º 15
0
 def __init__(self,dev_file='/dev/comedi0',**kw):
     if not 'comedi' in globals().keys():
         raise RuntimeError("Comedi input/output not supported on this platform.")
     VisionEgg.Daq.Device.__init__(self,**kw)
     self.dev = comedi.comedi_open(dev_file)
     if not self.dev:
         raise RuntimeError("Error openning Comedi device")
     for channel in self.channels:
         if not isinstance(channel,ComediChannel):
             raise ValueError("ComediDevice only has ComediChannel.")
Ejemplo n.º 16
0
def get_dio_channels(path):
    device = c.comedi_open(path)
    n_subdevices = c.comedi_get_n_subdevices(device)
    dio_list = []
    for n_subdevice in range(n_subdevices):
        if (c.comedi_get_subdevice_type(
                device, n_subdevice) == comedi_subdevice_type("dio")):
            n_channel = c.comedi_get_n_channels(device, n_subdevice)
            #dio_list.extend([DioSocket(path, n_subdevice, chan)
            #                for chan in range(n_channel)])
    return dio_list
Ejemplo n.º 17
0
def get_dio_channels(path):
    device = c.comedi_open(path)
    n_subdevices = c.comedi_get_n_subdevices(device)
    dio_list = []
    for n_subdevice in range(n_subdevices):
        if (c.comedi_get_subdevice_type(device, n_subdevice)
            == comedi_subdevice_type("dio")):
            n_channel = c.comedi_get_n_channels(device, n_subdevice)
            #dio_list.extend([DioSocket(path, n_subdevice, chan)
            #                for chan in range(n_channel)])
    return dio_list
Ejemplo n.º 18
0
def setx(voltage):
    dev = comedi.comedi_open("/dev/comedi0")
    outsubdevice = 1
    insubdevice = 0
    xchannel = 0
    ychannel = 1
    inchannel = 0
    analogref = comedi.AREF_GROUND
    arange =  0
    write_data = int(  (float(voltage)+10)/20*65535)
    msg = comedi.comedi_data_write(dev, outsubdevice, xchannel, arange, analogref, write_data)
    comedi.comedi_close(dev)
Ejemplo n.º 19
0
 def __init__(self):
     # Open device
     self.device = comedi.comedi_open('/dev/comedi0')
     # Set max values as numbers
     comedi.comedi_set_global_oor_behavior(comedi.COMEDI_OOR_NUMBER)
     # Get channel range info
     self.range_info_input_1 = comedi.comedi_get_range(self.device, 0 , 0 , 0)
     self.range_info_input_2 = comedi.comedi_get_range(self.device, 0 , 1 , 0)
     self.range_info_output_1 = comedi.comedi_get_range(self.device, 1 , 0 , 0)
     # Get channel max inputs
     self.maxdata_input_1 = comedi.comedi_get_maxdata(self.device,0 ,0)
     self.maxdata_input_2 = comedi.comedi_get_maxdata(self.device,0 ,1)
     self.maxdata_output_1 = comedi.comedi_get_maxdata(self.device,1 ,0)
     self.lock = threading.Lock()       
Ejemplo n.º 20
0
Archivo: io.py Proyecto: joeybowie/heis
	def init(self):
		self.c_con = c.comedi_open('/dev/comedi0')

		if self.c_con == None:
			return 0

		status = 0
		for i in range(8):
			status |= c.dio_config(self.c_con, channel.PORT_1_SUBDEVICE, i + channel.PORT_1_CHANNEL_OFFSET, channel.PORT_1_DIRECTION)
	    	status |= c.dio_config(self.c_con, channel.PORT_2_SUBDEVICE, i + channel.PORT_2_CHANNEL_OFFSET, channel.PORT_2_DIRECTION)
	    	status |= c.dio_config(self.c_con, channel.PORT_3_SUBDEVICE, i + channel.PORT_3_CHANNEL_OFFSET, channel.PORT_3_DIRECTION)
	    	status |= c.dio_config(self.c_con, channel.PORT_4_SUBDEVICE, i + channel.PORT_4_CHANNEL_OFFSET, channel.PORT_4_DIRECTION)
	    
		return status == 0
Ejemplo n.º 21
0
    def setup_adc(self):
        self.subdevice=0 #Always the case here
        self.dev = c.comedi_open('/dev/comedi0')
        if not self.dev: 
            self.logger.error("Error openning Comedi device")
            return -1
        
        self.file_device = c.comedi_fileno(self.dev)
        if not self.file_device:
            self.logger.error("Error obtaining Comedi device file descriptor")
            return -1

        self.buffer_size = c.comedi_get_buffer_size(self.dev, self.subdevice)
        temp_msg = "Debug size: %i" % self.buffer_size
        self.logger.info(temp_msg)
        self.map = mmap.mmap(self.file_device,self.buffer_size,mmap.MAP_SHARED, mmap.PROT_READ)
Ejemplo n.º 22
0
def diowrite(subdevice, channel, data):
	dev = comedi.comedi_open("/dev/comedi0")
	ret1 = comedi.comedi_dio_config(dev, subdevice, channel, comedi.COMEDI_OUTPUT)

	if ret1 == 1:
		pass
	else:
		print "initialisation failed"
		
	ret=comedi.comedi_dio_write(dev, subdevice, channel, data)

	if ret == 1:
		pass
	else:
		print "setting failed"
	comedi.comedi_close(dev)
Ejemplo n.º 23
0
def SetComediDevice():
    if os.path.isfile("/proc/comedi"):
        device = "/dev/comedi0"
        try:
            dev = comedi.comedi_open(device)
            global insubdevice
            insubdevice = comedi.comedi_get_read_subdevice(dev)
        #    print "subdevice for input = " + str(insubdevice)
            global outsubdevice
            outsubdevice = comedi.comedi_get_write_subdevice(dev)
        #    print "subdevice for output = " + str(outsubdevice)

            return "/dev/comedi0"
        except:
            print "cannot open /dev/comedi0, permissions?"
    else:
        return ""
    def run(self):
        '''
        Code to execute immediately prior to the beginning of the task FSM executing, or after the FSM has finished running.
        See riglib.experiment.Experiment.run(). This 'run' method stops the NIDAQ sink after the FSM has stopped running.
        '''
        try:
            super(RelayPlexon, self).run()
        finally:
            # Stop the NIDAQ sink
            self.nidaq.stop()

            # Remotely stop the recording on the plexon box
            import comedi
            import time
            com = comedi.comedi_open("/dev/comedi0")
            time.sleep(0.5)
            comedi.comedi_dio_bitfield2(com, 0, 16, 16, 16)
    def pre_init(cls, saveid=None):
        '''
        Run prior to starting the task to remotely start recording from the plexon system
        '''
        if saveid is not None:
            import comedi
            import time

            com = comedi.comedi_open("/dev/comedi0")
            # stop any recording
            comedi.comedi_dio_bitfield2(com, 0, 16, 16, 16)
            time.sleep(0.1)
            # start recording
            comedi.comedi_dio_bitfield2(com, 0, 16, 0, 16)

            time.sleep(3)
            super(RelayPlexon, cls).pre_init(saveid=saveid)
Ejemplo n.º 26
0
    def __init__(self, path, serialNum="FT24092", comediNum=0):
        #The defaults are configured for the Linux computer by the MTMs
        #The other force sensor is serialNum="FT24093", comedi_num=1
        self.num_channels = 6
        self.sub_device = 0
        self.aref = 0  # = AREF_GROUND
        self.range = 0  #0 = [-10V, 10V]

        #Create a comedi connection for connected device
        self.dev = comedi.comedi_open("/dev/comedi" + str(comediNum))
        #Read in calibration matrix
        self.cal_matrix = self.read_cal_file(path + "/calibration/" +
                                             serialNum + ".cal")
        self.bias = self.findBias()

        print("Created sensor " + serialNum + " on port " + str(comediNum) +
              "\n")
Ejemplo n.º 27
0
 def __init__(self,
              device='/dev/comedi0',
              subdevice=0,
              channel=1,
              range_num=0,
              gain=1,
              offset=0):
     self.subdevice = subdevice
     self.channel = channel
     self.range_num = range_num
     self.device0 = c.comedi_open(device)
     self.maxdata = c.comedi_get_maxdata(self.device0, self.subdevice,
                                         self.channel)
     self.range_ds = c.comedi_get_range(self.device0, self.subdevice,
                                        self.channel, self.range_num)
     self.gain = gain
     self.offset = offset
Ejemplo n.º 28
0
def open_dev(devname):
    #open a comedi device
    sys.stdout.write("NICOMEDI: Opening comedi subdevice... ")
    sys.stdout.flush()

    dev=c.comedi_open(devname)
    name = c.comedi_get_board_name(dev)
    if not dev:
        comedi_errcheck()
    sys.stdout.write("found %s\n" % (name))
    sys.stdout.flush()

    #get a file-descriptor for use later
    fd = c.comedi_fileno(dev)
    if fd == -1:
        comedi_errcheck()

    return dev, fd, name
Ejemplo n.º 29
0
    def __init__(self, *args, **kwargs):
        '''
        Constructor for TTLReward

        Parameters
        ----------
        pulse_device: string
            Path to the NIDAQ device used to generate the solenoid pulse
        args, kwargs: optional positional and keyword arguments to be passed to parent constructor
            None necessary

        Returns
        -------
        TTLReward instance
        '''
        import comedi
        self.com = comedi.comedi_open('/dev/comedi0')
        super(TTLReward, self).__init__(*args, **kwargs)
Ejemplo n.º 30
0
def open_dev(devname):
    #open a comedi device
    sys.stdout.write("NICOMEDI: Opening comedi subdevice... ")
    sys.stdout.flush()

    dev = c.comedi_open(devname)
    name = c.comedi_get_board_name(dev)
    if not dev:
        comedi_errcheck()
    sys.stdout.write("found %s\n" % (name))
    sys.stdout.flush()

    #get a file-descriptor for use later
    fd = c.comedi_fileno(dev)
    if fd == -1:
        comedi_errcheck()

    return dev, fd, name
    def pre_init(cls, saveid=None):
        '''
        Run prior to starting the task to remotely start recording from the plexon system
        '''
        if saveid is not None:
            import comedi
            import config
            import time

            com = comedi.comedi_open("/dev/comedi0")
            # stop any recording
            comedi.comedi_dio_bitfield2(com, 0, 16, 16, 16)
            time.sleep(0.1)
            # start recording
            comedi.comedi_dio_bitfield2(com, 0, 16, 0, 16)

            time.sleep(3)
            super(RelayPlexon, cls).pre_init(saveid=saveid)
    def run(self):
        '''
        Code to execute immediately prior to the beginning of the task FSM executing, or after the FSM has finished running. 
        See riglib.experiment.Experiment.run(). This 'run' method stops the NIDAQ sink after the FSM has stopped running.
        '''
        try:
            super(RelayPlexon, self).run()
        finally:
            # Stop the NIDAQ sink
            self.nidaq.stop()

            # Remotely stop the recording on the plexon box
            import comedi
            import config
            import time
            com = comedi.comedi_open("/dev/comedi0")
            time.sleep(0.5)
            comedi.comedi_dio_bitfield2(com, 0, 16, 16, 16)            
Ejemplo n.º 33
0
 def __init__(self,K=1,Ki=0,Kd=0,device='/dev/comedi0',subdevice=1,channel=0,range_num=1,gain=1,offset=0,out_min=0,out_max=4.095):
   self.subdevice=subdevice
   self.channel=channel
   self.range_num=range_num
   self.device0=c.comedi_open(device)
   self.maxdata=c.comedi_get_maxdata(self.device0,self.subdevice,self.channel)
   self.range_ds=c.comedi_get_range(self.device0,self.subdevice,self.channel,self.range_num)
   self.out=0
   self.gain=gain
   self.offset=offset
   self.I_term=0
   self.last_sensor_input=0
   self.K=K
   self.Ki=Ki
   self.Kd=Kd
   self.last_time=time.time()
   self.out_min=out_min
   self.out_max=out_max
   self.last_output=0
Ejemplo n.º 34
0
	def __init__(self,device='/dev/comedi0',subdevice=0,channels=0,
			  range_num=0,gain=1,offset=0): 
		"""
Convert tension value into digital values, on several channels.

Output is (measured_value * gain) + offset.

Parameters
----------
device : str, default = '/dev/comedi0'
	Path to the device.
subdevice : int, default = 0
	Subdevice 0 is the intput.
channel : int or list of int, default = 0
	The desired output channel(s).
range_num : int, default = 0
	See the comedi documentation for different values.
gain : float or list of float, default = 1
	Multiplication gain for each channel. If there is multiple channels
	for a single gain, it will be applied to all.
offset : float, default = 0
	Add this value for each channel. If there is multiple channels
		for a single offset, it will be applied to all.
		"""
		self.subdevice=subdevice
		self.channels=channels
		self.range_num=range_num
		self.gain=gain
		self.offset=offset
		self.device=c.comedi_open(device)
		#if type(self.channels)==int or len(self.channels)==1:	# for getData
			#self.nchans=1
		if type(self.channels)==list:	# if multiple channels
			self.nchans=len(self.channels)
			self.range_num=[self.range_num]*self.nchans
			if type(self.gain)==int:
				self.gain=[self.gain]*self.nchans
			if type(self.offset)==int:
				self.offset=[self.offset]*self.nchans
			self.new()
		else:
			raise Exception("channels must be int or list")
    def pre_init(cls, saveid=None):
        if saveid is not None:
            import comedi
            import config
            import time

            com = comedi.comedi_open("/dev/comedi0")
            # set strobe pin low
            comedi.comedi_dio_bitfield2(com, 0, 1, 0, 16)

            # set last data pin ("D15"; 16th pin) high
            comedi.comedi_dio_bitfield2(com, 0, 1, 1, 15)

            # set strobe pin high
            comedi.comedi_dio_bitfield2(com, 0, 1, 1, 16)

            # set strobe pin low
            comedi.comedi_dio_bitfield2(com, 0, 1, 0, 16)

            time.sleep(3)
            super(RelayPlexon, cls).pre_init(saveid=saveid)
Ejemplo n.º 36
0
    def pre_init(cls, saveid=None):
        if saveid is not None:
            import comedi
            import config
            import time

            com = comedi.comedi_open("/dev/comedi0")
            # set strobe pin low
            comedi.comedi_dio_bitfield2(com, 0, 1, 0, 16)

            # set last data pin ("D15"; 16th pin) high
            comedi.comedi_dio_bitfield2(com, 0, 1, 1, 15)

            # set strobe pin high
            comedi.comedi_dio_bitfield2(com, 0, 1, 1, 16)

            # set strobe pin low
            comedi.comedi_dio_bitfield2(com, 0, 1, 0, 16)

            time.sleep(3)
            super(RelayPlexon, cls).pre_init(saveid=saveid)
Ejemplo n.º 37
0
    def init(self):
        self.c_con = c.comedi_open('/dev/comedi0')

        if self.c_con == None:
            return 0

        status = 0
        for i in range(8):
            status |= c.dio_config(self.c_con, channel.PORT_1_SUBDEVICE,
                                   i + channel.PORT_1_CHANNEL_OFFSET,
                                   channel.PORT_1_DIRECTION)
        status |= c.dio_config(self.c_con, channel.PORT_2_SUBDEVICE,
                               i + channel.PORT_2_CHANNEL_OFFSET,
                               channel.PORT_2_DIRECTION)
        status |= c.dio_config(self.c_con, channel.PORT_3_SUBDEVICE,
                               i + channel.PORT_3_CHANNEL_OFFSET,
                               channel.PORT_3_DIRECTION)
        status |= c.dio_config(self.c_con, channel.PORT_4_SUBDEVICE,
                               i + channel.PORT_4_CHANNEL_OFFSET,
                               channel.PORT_4_DIRECTION)

        return status == 0
Ejemplo n.º 38
0
def _phys_channel(context):
    """Comedi uses device names such as /dev/comedi0 SUBDEVICE CHANNEL
    where SUBDEVICE and CHANNEL are integers.

    In the config file, we must set /dev/comedi0 as the port and
    SUBDEVICE.CHANNEL as the node.

    .. code-block:: yaml

        daq:
            /dev/comedi0:
                - node: 1.1
                  name: dio1
                - node: 1.2
                  name: dio2

    """
    filename = context.path[0].device
    subdevice, channel = context.node.split(".")
    device = c.comedi_open(filename)
    if not device:
        raise ComediError("Failed to open device %s" % filename)
    return device, int(subdevice), int(channel)
Ejemplo n.º 39
0
def _phys_channel(context):
    """Comedi uses device names such as /dev/comedi0 SUBDEVICE CHANNEL
    where SUBDEVICE and CHANNEL are integers.

    In the config file, we must set /dev/comedi0 as the port and
    SUBDEVICE.CHANNEL as the node.

    .. code-block:: yaml

        daq:
            /dev/comedi0:
                - node: 1.1
                  name: dio1
                - node: 1.2
                  name: dio2

    """
    filename = context.path[0].device
    subdevice, channel = context.node.split(".")
    device = c.comedi_open(filename)
    if not device:
        raise ComediError("Failed to open device %s" % filename)
    return device, int(subdevice), int(channel)
Ejemplo n.º 40
0
def timedbeamunblank(delay):
    dev = comedi.comedi_open("/dev/comedi0")

    subdevice = 2
    channel = 0
    data = 0
    ret1 = comedi.comedi_dio_config(dev, subdevice, channel, comedi.COMEDI_OUTPUT)

    if ret1 == 1:
        pass
    else:
        print "initialisation failed"

    start_time = datetime.datetime.now()   
    ret=comedi.comedi_dio_write(dev, subdevice, channel, data)
    blanked_time = datetime.datetime.now()
    
    if ret == 1:
        pass
    else:
        print "setting failed"

    time.sleep(delay)
        
    data = 1
    ret=comedi.comedi_dio_write(dev, subdevice, channel, data)
    end_time = datetime.datetime.now()

    print "blanked_time =", blanked_time  - start_time
    print "end_time =", end_time  - start_time
    
    if ret == 1:
        pass
    else:
        print "setting failed"

    comedi.comedi_close(dev)
Ejemplo n.º 41
0
# comedi_combo_test.py

import comedi as c
import time

channel = 0

comediDevice = c.comedi_open('/dev/comedi0')
print comediDevice

print "***** HANDLING INPUT DEVICE(S) *****"

inputSubdev = c.comedi_find_subdevice_by_type(comediDevice, c.COMEDI_SUBD_AI, 0)
print "input subdevice: %d" % inputSubdev 

inputMaxdata = c.comedi_get_maxdata(comediDevice, inputSubdev, channel)
print "Input max Data: %d" % inputMaxdata

nInputChannels = c.comedi_get_n_channels(comediDevice, inputSubdev)
print "Num input Channels: %d" % nInputChannels

nInputRanges = c.comedi_get_n_ranges(comediDevice, inputSubdev, channel)
print "number Input Ranges: %d" % nInputRanges

inputRange = c.comedi_get_range(comediDevice, inputSubdev, channel, 0)
print "input range: : %s" % str(inputRange)

print "Input locked? %d" % c.comedi_lock(comediDevice, inputSubdev)

print "***** HANDLING OUTPUT DEVICE(S) *****"
Ejemplo n.º 42
0
    return insns


def free_insns(insns):
    array = _comedi.insn_array.frompointer(insns.insns)
    array.thisown = True
    for i in range(insns.n_insns):
        insn = array[i]
        data = _comedi.lsampl_array.frompointer(insn.data)
        data.thisown = True


if True:

    fname = '/dev/comedi0'
    device = _comedi.comedi_open(fname)
    if not device:
        raise Exception('error opening Comedi device {}'.format(fname))

    subdevice = 0
    channel = 2
    aref = 'ground'
    rng = 0
    n_scan = 1

    if True:

        setup_read_insn = SetupReadInsn(subdevice=subdevice,
                                        channel=channel,
                                        aref=aref,
                                        range=rng,
Ejemplo n.º 43
0
def acquire_data(config):
    """
    Acquire data from data acquisition device. 
    """

    #Open a comedi device
    dev = c.comedi_open(config['device'])
    if not dev:
        err_msg = "%s: error: unable to open openning Comedi device" % (
            PROG_NAME, )
        sys.stderr.write(err_msg)
        sys.exit(1)

    # Get a file-descriptor to access data
    fd = c.comedi_fileno(dev)

    # Setup channels
    nchans = len(config['channels'])
    aref_str = config['aref'].lower()
    if aref_str == 'diff':
        aref = [c.AREF_DIFF] * nchans
    elif aref_str == 'common':
        aref = [c.AREF_COMMON] * nchans
    elif aref_str == 'ground':
        aref = [c.AREF_GROUND] * nchans
    else:
        raise ValueError, 'unknown aref'

    #nchans = len(config['channels'])
    #aref =[c.AREF_GROUND]*nchans

    # Pack the channel, gain and reference information into the chanlist object
    channel_list = c.chanlist(nchans)
    for i in range(nchans):
        channel_list[i] = c.cr_pack(config['channels'][i], config['gains'][i],
                                    aref[i])

    # Construct a comedi command
    cmd = c.comedi_cmd_struct()
    cmd.subdev = config['subdev']
    cmd.flags = DEFAULT_CMD_FLAGS
    cmd.start_src = c.TRIG_NOW
    cmd.sart_arg = DEFAULT_CMD_SART_ARG
    cmd.scan_begin_src = c.TRIG_TIMER
    cmd.scan_begin_arg = int(NANO_SEC / config['sample_freq'])
    cmd.convert_src = c.TRIG_TIMER
    cmd.convert_arg = DEFAULT_CMD_CONVERT_ARG
    cmd.scan_end_src = c.TRIG_COUNT
    cmd.scan_end_arg = nchans
    cmd.stop_src = c.TRIG_COUNT
    cmd.stop_arg = config['sample_num']
    cmd.chanlist = channel_list
    cmd.chanlist_len = nchans

    # Test comedi command
    if config['verbose']:
        print 'Testing comedi command'
        print
    for i in range(0, DEFAULT_CMD_TEST_NUM):
        if config['verbose']:
            print_cmd(cmd)
        ret = c.comedi_command_test(dev, cmd)
        if config['verbose']:
            print
            print '\t*** test %d returns %s' % (i, CMD_TEST_MSG[ret])
            print
    if not ret == 0:
        msg_data = (PROG_NAME, CMD_TEST_MSG[ret])
        err_msg = '%s: error: unable to configure daq device - %s' % msg_data
        sys.stderr.write(err_msg)

    # Acquire data
    if config['verbose']:
        print 'acquiring data'
        print
        sys.stdout.flush()
    ret = c.comedi_command(dev, cmd)  # non blocking
    if not ret == 0:
        err_msg = '%s: error: unable to execute comedi command' % (PROG_NAME, )
        sys.stderr.write(err_msg)
        sys.exit(1)

    # Read data from buffer - may want to add a timeout here
    read_done = False
    bytes_total = 2 * config['sample_num'] * nchans
    bytes_read = 0
    datastr = ''
    while not read_done:
        try:
            buffstr = os.read(fd, bytes_total)
        except OSError, err:
            if err.args[0] == 4:
                continue
            raise
        datastr += buffstr
        bytes_read += len(buffstr)
        if config['verbose']:
            print '\tread:', bytes_read, 'of', 2 * config[
                'sample_num'] * nchans, 'bytes'
        if bytes_read == bytes_total:
            read_done = True
Ejemplo n.º 44
0
    c.COMEDI_SUBD_UNUSED: "unused",
    c.COMEDI_SUBD_AI: "analog input",
    c.COMEDI_SUBD_AO: "analog output",
    c.COMEDI_SUBD_DI: "digital input",
    c.COMEDI_SUBD_DO: "digital output",
    c.COMEDI_SUBD_DIO: "digital I/O",
    c.COMEDI_SUBD_COUNTER: "counter",
    c.COMEDI_SUBD_SERIAL: "serial",
    c.COMEDI_SUBD_PWM: "pulse width modulation",
    c.COMEDI_SUBD_TIMER: "timer",
    c.COMEDI_SUBD_MEMORY: "memory",
    c.COMEDI_SUBD_CALIB: "calibration",
    c.COMEDI_SUBD_PROC: "processor"
}
#open a comedi device
dev = c.comedi_open('/dev/comedi0')
if not dev: raise "Error openning Comedi device"

version_code = c.comedi_get_version_code(dev)
if not version_code: raise "Error reading version_code"
print "version code is: ", version_code

driver_name = c.comedi_get_driver_name(dev)
if not driver_name: raise "Error reading driver_name"
print "driver name is: ", driver_name

board_name = c.comedi_get_board_name(dev)
if not board_name: raise "Error reading board_name"
print "board name is: ", board_name

n_subdevices = c.comedi_get_n_subdevices(dev)
Ejemplo n.º 45
0
#!/usr/bin/python

#set the paths so python can find the comedi module
import sys, os, string, struct, time, mmap, array
import comedi as c
import numpy

#open a comedi device
dev=c.comedi_open('/dev/comedi0')
device = dev
if not dev: 
    raise "Error openning Comedi device"

#get a file-descriptor for use later
fd = c.comedi_fileno(dev)
if fd<=0: 
    raise "Error obtaining Comedi device file descriptor"

freq=50000 # as defined in demo/common.c
subdevice=0 #as defined in demo/common.c
secs = 3 # used to stop scan after "secs" seconds
packetSize = 512

#three lists containing the chans, gains and referencing
#the lists must all have the same length
#~ chans=[0,1,2,3]
#~ gains=[0,0,0,0]
#~ aref =[c.AREF_GROUND, c.AREF_GROUND, c.AREF_GROUND, c.AREF_GROUND]

#nchans = 16
nchans = 2
Ejemplo n.º 46
0
 def open(self):
     self.device = comedi.comedi_open(self.device_name)
     if self.device is None:
         raise InterfaceError('could not open comedi device %s' %
                              self.device_name)
import comedi
import time
com = comedi.comedi_open("/dev/comedi0")
time.sleep(0.010)
print "starting file recording"
comedi.comedi_dio_bitfield2(com,0,16,0,16)
print "Sleeping for 10 seconds"
import time
time.sleep(10)
print "Stopping file recording"
comedi.comedi_dio_bitfield2(com, 0, 16, 16, 16)
Ejemplo n.º 48
0
# The maximum value we display for the final forces
FORCE_MAXREADING = 5

N_FORCES = 6

dumpf = open('dump.txt', 'w')

import math

import numpy as np
sens_to_f = np.genfromtxt('sensor_transf_matrix_FT4714.csv', delimiter=',')
# read the matrix that transforms sensor data into force data.
# note: the columns here are the sensor dimensions, the rows are the force dimensions.

#open a comedi device
dev = c.comedi_open(DEVICE)
if not dev: raise Exception("Error opening Comedi device")

# get maxdata & range
#  - these values are used to convert integer to physical values

i = SUBDEVICE

maxdata = c.comedi_get_maxdata(dev, SUBDEVICE, 0)
#print("\tmax data value: %d" % (maxdata))

ranges = []
#n_ranges = c.comedi_get_n_ranges(dev,i,0)
#print("\t\tall chans:")
n_ranges = c.comedi_get_n_ranges(dev, SUBDEVICE,
                                 0)  # get how many range options we have
Ejemplo n.º 49
0
class TTLStimulation(object):
    '''During the stimulation phase, send a timed TTL pulse to the Master-8 stimulator'''
    hold_time = float(1)
    stimulation_pulse_length = float(0.2 * 1e6)
    stimulation_frequency = float(3)

    status = dict(pulse=dict(pulse_end="interpulse_period", stop=None),
                  interpulse_period=dict(another_pulse="pulse",
                                         pulse_train_end="pulse_off",
                                         stop=None),
                  pulse_off=dict(stop=None))

    com = comedi.comedi_open('/dev/comedi0')
    pulse_count = 0  #initializing number of pulses that have occured

    def __init__(self, *args, **kwargs):
        super(TTLStimulation, self).__init__(*args, **kwargs)
        number_of_pulses = int(
            self.hold_time * self.stimulation_frequency
        )  # total pulses during a stimulation pulse train, assumes hold_time is in s

    def init(self):
        super(TTLStimulation, self).init()

    #### TEST FUNCTIONS ####

    def _test_pulse_end(self, ts):
        #return true if time has been longer than the specified pulse duration
        pulse_length = self.stimulation_pulse_length * 1e-6  # assumes stimulation_pulse_length is in us
        return ts >= pulse_length

    def _test_another_pulse(self, ts):
        interpulse_time = (
            1 / self.stimulationfrequency
        ) - self.stimulation_pulse_length * 1e-6  # period minus the duration of a pulse
        return ts >= interpulse_time

    def _test_pulse_train_end(self, ts):
        return (
            self.pulse_count > number_of_pulses
        )  # end train if number of pulses is completed or if the animal ends holding early

    #### STATE FUNCTIONS ####

    def _start_pulse(self):
        '''
        At the start of the stimulation state, send TTL pulse
        '''

        #super(TTLStimulation, self)._start_pulse()
        subdevice = 0
        write_mask = 0x800000
        val = 0x800000
        base_channel = 0
        comedi.comedi_dio_bitfield2(self.com, subdevice, write_mask, val,
                                    base_channel)
        self.pulse_count = self.pulse_count + 1
        #self.stimulation_start = self.get_time() - self.start_time

    def _end_pulse(self):
        subdevice = 0
        write_mask = 0x800000
        val = 0x000000
        base_channel = 0
        comedi.comedi_dio_bitfield2(self.com, subdevice, write_mask, val,
                                    base_channel)

    def _start_interpulse_period(self):
        super(TTLStimulation, self)._start_interpulse_period()
        subdevice = 0
        write_mask = 0x800000
        val = 0x000000
        base_channel = 0
        comedi.comedi_dio_bitfield2(self.com, subdevice, write_mask, val,
                                    base_channel)

    def _end_interpulse_period(self):
        super(TTLStimulation, self)._end_interpulse_period()
        subdevice = 0
        write_mask = 0x800000
        val = 0x000000
        base_channel = 0
        comedi.comedi_dio_bitfield2(self.com, subdevice, write_mask, val,
                                    base_channel)
Ejemplo n.º 50
0
#curses.nocbreak()
stdscr.keypad(0)
curses.echo()

stdscr.nodelay(1)
gin = stdscr.getch()

# -------------------------------------------------------------------------
# --------- DAQ initialization
# -------------------------------------------------------------------------
chans = [0,1]
subdev = 0
chrange = 0


# Open and configure device
daq = comedi.comedi_open('/dev/comedi0')
if not daq:
    raise "Error openning Comedi device"

maxdata = [0,0]
cr = [0,0]
maxdata[0] = comedi.comedi_get_maxdata(daq,subdev, chans[0])
cr[0]      = comedi.comedi_get_range(daq,subdev,chans[0],chrange)
maxdata[1] = comedi.comedi_get_maxdata(daq,subdev, chans[1])
cr[1]      = comedi.comedi_get_range(daq,subdev,chans[1],chrange)

# -------------------------------------------------------------------------
# --------- polarizer initialization
# -------------------------------------------------------------------------
NUM_TEETH_PASSIVE_GEAR = 80.0 # number of teeth on gear surrounding polarizer
Ejemplo n.º 51
0
        LOG.setLevel(_logging.DEBUG)
    elif args.verbose >= 2:
        LOG.setLevel(_logging.INFO)
    elif args.verbose >= 1:
        LOG.setLevel(_logging.WARN)

    if args.num_scans > MAX_SAMPLES:
        LOG.warn(
            'requested too many samples, reducing to {}'.format(MAX_SAMPLES))
        args.num_scans = MAX_SAMPLES

    LOG.info(('measuring device={0.filename} subdevice={0.subdevice} '
              'channel={0.channel} range={0.range} analog reference={0.aref}'
              ).format(args))

    device = _comedi.comedi_open(args.filename)
    if not device:
        raise Exception('error opening Comedi device {}'.format(args.filename))

    setup_read_insn = SetupReadInsn(subdevice=args.subdevice,
                                    channel=args.channel,
                                    aref=args.aref,
                                    range=args.range,
                                    n_scan=args.num_scans)

    insns = setup_insns(device,
                        [setup_gtod_insn, setup_read_insn, setup_gtod_insn])

    ret = _comedi.comedi_do_insnlist(device, insns)
    if ret != insns.n_insns:
        raise Exception('error running instructions ({})'.format(ret))
Ejemplo n.º 52
0
def main():
    # Find comedi analog device number
    try:
        with open(COMEDI_PROC_F) as f:
            #print(f)
            for line in f.readlines():
                m_analog = re.match(PCI_6033E_PATTERN, line)
                m_digital = re.match(PCI_DIO_32HS_PATTERN, line)
                if m_analog:
                    print(m_analog.group())
                    dev_number = m_analog.groups()[0]
                    analog_dev_fname = "/dev/comedi" + dev_number
                if m_digital:
                    print(m_digital.group())
                    dev_number = m_digital.groups()[0]
                    digital_dev_fname = "/dev/comedi" + dev_number
    except IOError:
        print("Could not find file: %s" % COMEDI_PROC_F)

    if (f):
        f.close()

    if (analog_dev_fname):
        analog_dev = c.comedi_open(analog_dev_fname)
        if not(analog_dev):
            print("Unable to open analog comedi device...")
        
        ret = c.comedi_lock(analog_dev, 0)
        if (ret < 0):
            print("Could not lock comedi device")

        ret = c.comedi_get_max_buffer_size(analog_dev, 0)
        if (ret > 0):
            print("analog max buffer size: %i" % ret)
        else:
            print("Failed to get analog dev max buffer size...")

        ret = c.comedi_set_max_buffer_size(analog_dev, 0, MAX_BUFFER_SIZE)
        if (ret > 0):
            print("analog dev new buffer size: %i" % ret)
        else:
            print("Failed to analog dev set max buffer size...")

        c.comedi_close(analog_dev)


    if (digital_dev_fname):
        digital_dev = c.comedi_open(digital_dev_fname)
        if not(digital_dev):
            print("Unable to open digital comedi device...")
        
        ret = c.comedi_lock(digital_dev, 0)
        if (ret < 0):
            print("Could not lock digital comedi device")

        ret = c.comedi_get_max_buffer_size(digital_dev, 0)
        if (ret > 0):
            print("analog max buffer size: %i" % ret)
        else:
            print("Failed to get digital dev max buffer size...")

        ret = c.comedi_set_max_buffer_size(digital_dev, 0, MAX_BUFFER_SIZE)
        if (ret > 0):
            print("digital dev new buffer size: %i" % ret)
        else:
            print("Failed to digital dev set max buffer size...")

        c.comedi_close(digital_dev)
Ejemplo n.º 53
0
def streamer(device,subdevice,chans,comedi_range,shared_array):
  ''' read the channels defined in chans, on the device/subdevice, and streams the values in the shared_array.
  The shared_array has a lock, to avoid reading and writing at the same time and it's process-proof.
  device: '/dev/comedi0'
  subdevice : 0=in, 1=out
  chans : [0,1,2,3,4....] : BE AWARE the reading is done crescendo, no matter the order given here. It means that [0,1,2] and [2,0,1] will both have [0,1,2] as result, but you can ask for [0,1,5].
  comedi_range: same size as chans, with the proper range for each chan. If unknown, try [0,0,0,....].
  shared_array: same size as chans, must be defined before with multiprocess.Array: shared_array= Array('f', np.arange(len(chans)))
  '''
  dev=c.comedi_open(device)
  if not dev: raise "Error openning Comedi device"

  fd = c.comedi_fileno(dev) #get a file-descriptor for use later

  BUFSZ = 10000 #buffer size
  freq=8000# acquisition frequency: if too high, set frequency to maximum.
 
  nchans = len(chans) #number of channels
  aref =[c.AREF_GROUND]*nchans

  mylist = c.chanlist(nchans) #create a chanlist of length nchans
  maxdata=[0]*(nchans)
  range_ds=[0]*(nchans)

  for index in range(nchans):  #pack the channel, gain and reference information into the chanlist object
    mylist[index]=c.cr_pack(chans[index], comedi_range[index], aref[index])
    maxdata[index]=c.comedi_get_maxdata(dev,subdevice,chans[index])
    range_ds[index]=c.comedi_get_range(dev,subdevice,chans[index],comedi_range[index])

  cmd = c.comedi_cmd_struct()

  period = int(1.0e9/freq)  # in nanoseconds
  ret = c.comedi_get_cmd_generic_timed(dev,subdevice,cmd,nchans,period)
  if ret: raise "Error comedi_get_cmd_generic failed"
	  
  cmd.chanlist = mylist # adjust for our particular context
  cmd.chanlist_len = nchans
  cmd.scan_end_arg = nchans
  cmd.stop_arg=0
  cmd.stop_src=c.TRIG_NONE

  t0 = time.time()
  j=0
  ret = c.comedi_command(dev,cmd)
  if ret !=0: raise "comedi_command failed..."

#Lines below are for initializing the format, depending on the comedi-card.
  data = os.read(fd,BUFSZ) # read buffer and returns binary data
  data_length=len(data)
  #print maxdata
  #print data_length
  if maxdata[0]<=65536: # case for usb-dux-D
    n = data_length/2 # 2 bytes per 'H'
    format = `n`+'H'
  elif maxdata[0]>65536: #case for usb-dux-sigma
    n = data_length/4 # 2 bytes per 'H'
    format = `n`+'I'
  #print struct.unpack(format,data)
    
# init is over, start acquisition and stream
  last_t=time.time()
  try:
    while True:
      #t_now=time.time()
      #while (t_now-last_t)<(1./frequency):
	#t_now=time.time()
	##print t_now-last_t
      #last_t=t_now
      data = os.read(fd,BUFSZ) # read buffer and returns binary data
      #print len(data), data_length
      if len(data)==data_length:
	datastr = struct.unpack(format,data) # convert binary data to digital value
	if len(datastr)==nchans: #if data not corrupted for some reason
	  #shared_array.acquire()
	  for i in range(nchans):
	    shared_array[i]=c.comedi_to_phys((datastr[i]),range_ds[i],maxdata[i])
	  #print datastr
	  #shared_array.release()
	#j+=1
	#print j
	#print "Frequency= ",(j/(time.time()-t0))
	#print np.transpose(shared_array[:])

  except (KeyboardInterrupt):	
    c.comedi_cancel(dev,subdevice)
    ret = c.comedi_close(dev)
    if ret !=0: raise "comedi_close failed..."
Ejemplo n.º 54
0
import comedi
import time

com = comedi.comedi_open("/dev/comedi0")

for i in range(6):
    # set strobe pin low
    comedi.comedi_dio_bitfield2(com, 0, 1, 0, 16)
    time.sleep(1)

    # set strobe pin high
    comedi.comedi_dio_bitfield2(com, 0, 1, 1, 16)
    time.sleep(1)
Ejemplo n.º 55
0
 def __init__(self):
     self.device = comedi.comedi_open(DEVICE_FILENAME)
     if not self.device:
         raise Exception("Cannot open device")
     self.initialize()
Ejemplo n.º 56
0
def streamer(device, subdevice, chans, comedi_range, shared_array):
    ''' read the channels defined in chans, on the device/subdevice, and streams the values in the shared_array.
  The shared_array has a lock, to avoid reading and writing at the same time and it's process-proof.
  device: '/dev/comedi0'
  subdevice : 0=in, 1=out
  chans : [0,1,2,3,4....] : BE AWARE the reading is done crescendo, no matter the order given here. It means that [0,1,2] and [2,0,1] will both have [0,1,2] as result, but you can ask for [0,1,5].
  comedi_range: same size as chans, with the proper range for each chan. If unknown, try [0,0,0,....].
  shared_array: same size as chans, must be defined before with multiprocess.Array: shared_array= Array('f', np.arange(len(chans)))
  '''
    dev = c.comedi_open(device)
    if not dev: raise "Error openning Comedi device"

    fd = c.comedi_fileno(dev)  #get a file-descriptor for use later

    BUFSZ = 10000  #buffer size
    freq = 8000  # acquisition frequency: if too high, set frequency to maximum.

    nchans = len(chans)  #number of channels
    aref = [c.AREF_GROUND] * nchans

    mylist = c.chanlist(nchans)  #create a chanlist of length nchans
    maxdata = [0] * (nchans)
    range_ds = [0] * (nchans)

    for index in range(
            nchans
    ):  #pack the channel, gain and reference information into the chanlist object
        mylist[index] = c.cr_pack(chans[index], comedi_range[index],
                                  aref[index])
        maxdata[index] = c.comedi_get_maxdata(dev, subdevice, chans[index])
        range_ds[index] = c.comedi_get_range(dev, subdevice, chans[index],
                                             comedi_range[index])

    cmd = c.comedi_cmd_struct()

    period = int(1.0e9 / freq)  # in nanoseconds
    ret = c.comedi_get_cmd_generic_timed(dev, subdevice, cmd, nchans, period)
    if ret: raise "Error comedi_get_cmd_generic failed"

    cmd.chanlist = mylist  # adjust for our particular context
    cmd.chanlist_len = nchans
    cmd.scan_end_arg = nchans
    cmd.stop_arg = 0
    cmd.stop_src = c.TRIG_NONE

    t0 = time.time()
    j = 0
    ret = c.comedi_command(dev, cmd)
    if ret != 0: raise "comedi_command failed..."

    #Lines below are for initializing the format, depending on the comedi-card.
    data = os.read(fd, BUFSZ)  # read buffer and returns binary data
    data_length = len(data)
    #print maxdata
    #print data_length
    if maxdata[0] <= 65536:  # case for usb-dux-D
        n = data_length / 2  # 2 bytes per 'H'
        format = ` n ` + 'H'
    elif maxdata[0] > 65536:  #case for usb-dux-sigma
        n = data_length / 4  # 2 bytes per 'H'
        format = ` n ` + 'I'
    #print struct.unpack(format,data)


# init is over, start acquisition and stream
    last_t = time.time()
    try:
        while True:
            #t_now=time.time()
            #while (t_now-last_t)<(1./frequency):
            #t_now=time.time()
            ##print t_now-last_t
            #last_t=t_now
            data = os.read(fd, BUFSZ)  # read buffer and returns binary data
            #print len(data), data_length
            if len(data) == data_length:
                datastr = struct.unpack(
                    format, data)  # convert binary data to digital value
                if len(datastr
                       ) == nchans:  #if data not corrupted for some reason
                    #shared_array.acquire()
                    for i in range(nchans):
                        shared_array[i] = c.comedi_to_phys(
                            (datastr[i]), range_ds[i], maxdata[i])
                    #print datastr
                    #shared_array.release()
                #j+=1
                #print j
                #print "Frequency= ",(j/(time.time()-t0))
                #print np.transpose(shared_array[:])

    except (KeyboardInterrupt):
        c.comedi_cancel(dev, subdevice)
        ret = c.comedi_close(dev)
        if ret != 0: raise "comedi_close failed..."