Example #1
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)
Example #2
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
Example #3
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 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..."
Example #5
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
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..."
Example #7
0
## GNU General Public License for more details.

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

sys.path.append(sys.path.pop(0))
import mmap

import comedi as c

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

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

#BUFSZ = 10000
freq = 1000  # as defined in demo/common.c
subdevice = 0  #as defined in demo/common.c
nscans = 8000  #specify total number of scans
secs = 10  # used to stop scan after "secs" seconds

#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]

cmdtest_messages = [
Example #8
0
    def pci_6033e_init(self, dev_name):
        self.dev = c.comedi_open(dev_name)
        if not(self.dev):
            self.warn_dialog("Unable to open device: " + dev_name)
            return(-1)

        ret = c.comedi_lock(self.dev, SUBDEVICE)
        if (ret < 0):
            self.warn_dialog("Could not lock comedi device")
            return(-1)

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

        # Channel range (0-5V)
        if (c.comedi_range_is_chan_specific(self.dev, SUBDEVICE) != 0):
            self.warn_dialog("Comedi range is channel specific!")
            c.comedi_close(self.dev)
            return(-1)

        self.comedi_range = c.comedi_get_range(self.dev, SUBDEVICE, 0, CHAN_RANGE)
        self.comedi_maxdata = c.comedi_get_maxdata(self.dev, SUBDEVICE, 0)

        board_name = c.comedi_get_board_name(self.dev)
        if (board_name != "pci-6033e"):
            print("Opened wrong device!")
        
        # Prepare channels, gains, refs
        self.comedi_num_chans = NUM_CHANNELS
        chans = range(self.comedi_num_chans)
        gains = [0]*self.comedi_num_chans
        aref = [c.AREF_GROUND]*self.comedi_num_chans

        chan_list = c.chanlist(self.comedi_num_chans)

        # Configure all the channels!
        for i in range(self.comedi_num_chans):
            chan_list[i] = c.cr_pack(chans[i], gains[i], aref[i])

        # The comedi command
        self.cmd = c.comedi_cmd_struct()

        # 1.0e9 because this number is in nanoseconds for some reason
        period = int(1.0e9/float(SCAN_FREQ))

        # Init cmd
        ret = c.comedi_get_cmd_generic_timed(self.dev, SUBDEVICE, self.cmd, self.comedi_num_chans, period)
        if (ret):
            self.warn_dialog("Could not initiate command")
            c.comedi_close(self.dev)
            return(-1)

        # Populate command 
        self.cmd.chanlist = chan_list
        self.cmd.chanlist_len = self.comedi_num_chans
        self.cmd.scan_end_arg = self.comedi_num_chans
        self.cmd.stop_src = c.TRIG_NONE
        self.cmd.stop_arg = 0

        print("real timing: %d ns" % self.cmd.convert_arg)
        print("Real scan freq: %d Hz" % (1.0/(float(self.cmd.convert_arg)*32.0*1.0e-9)))
        #print("period: %d ns" % period)
    
        print_cmd(self.cmd)

        # Test command out.
        ret = c.comedi_command_test(self.dev, self.cmd)
        if (ret < 0):
            self.warn_dialog("Comedi command test failed!")
            c.comedi_close(self.dev)
            return(-1)

        print("Command test passed")

        return(0)
Example #9
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