Esempio n. 1
0
 def _lowLevelSetChannel(self, chNum, enabled, coupling, VRange, VOffset,
                         BWLimited):
     m = self.lib.ps3000_set_channel(c_int16(self.handle), c_enum(chNum),
                                     c_int16(enabled), c_enum(coupling),
                                     c_enum(VRange))
     if m == 0:
         raise IOError('Error calling %s: parameter out of range' % (inspect.stack()[1][3]))
Esempio n. 2
0
    def __init__(self):
        try:
            if sys.platform == 'darwin':
                raise OSError
            self.__DCONDLL = ctypes.windll.LoadLibrary(os.getcwd() + '\DCON_PC.dll')
            self.__UARTDLL = ctypes.windll.LoadLibrary(os.getcwd() + '\Uart.dll')
            mode = 'Hardware driver .dll found'
        except OSError:
            self.__DCONDLL = USB87P4Simulator('DCON')
            self.__UARTDLL = USB87P4Simulator('UART')
            mode = 'OSError, enter simulation mode'
        except AttributeError:
            self.__DCONDLL = USB87P4Simulator('DCON')
            self.__UARTDLL = USB87P4Simulator('UART')
            mode = 'Hardware not present, enter simulation mode'
        print mode

        self.__dwBaudRate = ctypes.c_uint32(115200)
        self.__iAddress = ctypes.c_int16(2)
        self.__iSlot = ctypes.c_int16(-1)
        self.__iCheckSum = ctypes.c_int16(0)
        self.__iTimeOut = ctypes.c_int16(100)
        self.__cParity = ctypes.c_uint8(0)
        self.__cStop = ctypes.c_uint8(0)
        self.__cData = ctypes.c_uint8(8)
        self.__iAOTotalCh = ctypes.c_int16(4)
        # com port 7 as in TPS41 layout
        self.__cComPort = ctypes.c_uint8(7)
Esempio n. 3
0
 def _lowLevelSetChannel(self, chNum, enabled, coupling, VRange, VOffset,
                         BWLimited):
     m = self.lib.ps6000SetChannel(c_int16(self.handle), c_enum(chNum),
                                   c_int16(enabled), c_enum(coupling),
                                   c_enum(VRange), c_float(VOffset),
                                   c_enum(BWLimited))
     self.checkResult(m)
Esempio n. 4
0
 def _lowLevelSetSimpleTrigger(self, enabled, trigsrc, threshold_adc,
                               direction, delay, timeout_ms):
     m = self.lib.ps4000aSetSimpleTrigger(
         c_int16(self.handle), c_int16(enabled),
         c_enum(trigsrc), c_int16(threshold_adc),
         c_enum(direction), c_uint32(delay), c_int16(timeout_ms))
     self.checkResult(m)
Esempio n. 5
0
    def getTimeBaseNum(self, sampleTimeS):
        """ps3000 doesn't seem to have published formula like other scopes."""
        time_interval = c_int32()
        timebases = [None] * self.MAX_TIMEBASES

        # Convert to nS
        sampleTimenS = sampleTimeS * 1E9

        tb = 0
        while tb < self.MAX_TIMEBASES:
            rv = self.lib.ps3000_get_timebase(
                c_int16(self.handle), c_int16(tb), c_uint32(512),
                byref(time_interval), c_void_p(), c_int16(1),  c_void_p())
            if rv != 0:
                timebases[tb] = time_interval.value

            tb += 1

        # Figure out closest option
        besterror = 1E99
        bestindx = 0
        for indx, val in enumerate(timebases):
            if val is not None:
                error = sampleTimenS - val
                if abs(error) < besterror:
                    besterror = abs(error)
                    bestindx = indx

        return bestindx
Esempio n. 6
0
 def getTimestepFromTimebase(self, timebase):
     time_interval = c_int32()
     m = self.lib.ps2000_get_timebase(c_int16(self.handle), c_int16(timebase),
                                     c_uint32(512), byref(time_interval),
                                     c_void_p(), c_int16(1),  c_void_p())        
     self.checkResult(m)
     return (time_interval.value / 1.0E9)
Esempio n. 7
0
    def set_analog_channel(self, channel, reading_type, voltage_range, enabled):

        """
            Enable a analog channel to specified settings

        """

        if channel < self.max_channels + 1:

            self.logger.debug('Setting up channel %d' % channel)

            assert type(reading_type) is c_int16
            assert type(voltage_range) is c_int16

            # 0: dormant, <> 0: active
            c_enabled = c_int16(enabled)

            result = self.lib.HRDLSetAnalogInChannel(self.handle, c_int16(channel), c_enabled, voltage_range, reading_type)

            if not result:

                self.logger.error('Error setting up channel %d' % channel)
                self._get_settings_error()

        else:

            self.logger.error('Nonsense channel number %d' % channel)

    
        return
Esempio n. 8
0
 def set_current(self, k_val, board_ind=0):
     """
     sets the k value (must be int between 0 and 255)
     """
     board_ind = ctypes.c_int16(board_ind)
     k_val = ctypes.c_int16(k_val)
     self.cmd.send_command(6, (board_ind, k_val))
Esempio n. 9
0
 def set_accel(self, accel, board_ind=0):
     """
     sets accel and decell to value specified
     """
     board_ind = ctypes.c_int16(board_ind)
     accel = ctypes.c_int16(accel)
     self.cmd.send_command(5, (board_ind, accel))
Esempio n. 10
0
    def _lowLevelSetChannel(self, chNum, enabled, coupling, VRange, VOffset,
                            bandwidth):
        m = self.lib.ps5000aSetChannel(c_int16(self.handle), c_enum(chNum),
                                       c_int16(enabled), c_enum(coupling),
                                       c_enum(VRange), c_float(VOffset))
        self.checkResult(m)

        # The error this might through are
        #    INVALID_HANDLE
        #    INVALID_CHANNEL
        #    INVALID_BANDWIDTH
        # Invalid bandwidth is the only case that could go wrong.
        # The others would be thrown above (assuming no race condition:
        # i.e. unplugging the scope in between this call.
        # I decided to keep the logic below to avoid a possible error
        # picobase/SetChannel should be changed to the following
        # Set the channel
        # save the new channel settings
        # check if ps5000a
        # change the bandwidth separately
        # changing the bandwidth would be it's own function (implemented below)
        if bandwidth:
            m = self.lib.ps5000aSetBandwidthFilter(c_int16(self.handle),
                                                   c_enum(chNum), c_enum(1))
        else:
            m = self.lib.ps5000aSetBandwidthFilter(c_int16(self.handle),
                                                   c_enum(chNum), c_enum(0))
        self.checkResult(m)
Esempio n. 11
0
 def set_max_speed(self, max_sp, board_ind=0):
     """
     sets the max speed to integer value specified
     """
     board_ind = ctypes.c_int16(board_ind)
     max_sp = ctypes.c_int16(max_sp)
     self.cmd.send_command(4, (board_ind, max_sp))
Esempio n. 12
0
 def DVI(self, b, a):
     if a.value == 0:
         b.value = 0
     b_signed = c_int16(b.value)
     a_signed = c_int16(a.value)
     b.value = b_signed.value / a_signed.value
     self.cpu.EX.value = ((b_signed.value << 16) / a.value) & 0xffff
Esempio n. 13
0
    def _lowLevelSetAWGSimpleDeltaPhase(self, waveform, deltaPhase,
                                        offsetVoltage, pkToPk, indexMode,
                                        shots, triggerType, triggerSource):
        """ waveform should be an array of shorts. """

        waveformPtr = waveform.ctypes.data_as(POINTER(c_int16))

        m = self.lib.ps6000SetSigGenArbitrary(
            c_int16(self.handle),
            c_uint32(int(offsetVoltage * 1E6)),  # offset voltage in microvolts
            c_uint32(int(pkToPk * 1E6)),         # pkToPk in microvolts
            c_uint32(int(deltaPhase)),           # startDeltaPhase
            c_uint32(int(deltaPhase)),           # stopDeltaPhase
            c_uint32(0),                         # deltaPhaseIncrement
            c_uint32(0),                         # dwellCount
            waveformPtr,                         # arbitraryWaveform
            c_int32(len(waveform)),              # arbitraryWaveformSize
            c_enum(0),                           # sweepType for deltaPhase
            c_enum(0),            # operation (adding random noise and whatnot)
            c_enum(indexMode),                   # single, dual, quad
            c_uint32(shots),
            c_uint32(0),                         # sweeps
            c_uint32(triggerType),
            c_uint32(triggerSource),
            c_int16(0))                          # extInThreshold
        self.checkResult(m)
 def get_rotation(self):
     raw_data = self.__bus.read_i2c_block_data(self.__dev_id,
                                               C.MPU6050_RA_GYRO_XOUT_H, 6)
     gyro = [0] * 3
     gyro[0] = ctypes.c_int16(raw_data[0] << 8 | raw_data[1]).value
     gyro[1] = ctypes.c_int16(raw_data[2] << 8 | raw_data[3]).value
     gyro[2] = ctypes.c_int16(raw_data[4] << 8 | raw_data[5]).value
     return gyro
Esempio n. 15
0
 def getTimestepFromTimebase(self, timebase):
     time_interval = c_int32()
     m = self.lib.ps3000_get_timebase(c_int16(self.handle), c_int16(timebase),
                                      c_uint32(512), byref(time_interval),
                                      c_void_p(), c_int16(1),  c_void_p())        
     if m == 0:
         raise IOError('Error calling %s: invalid parameters given' % (inspect.stack()[1][3]))
     return (time_interval.value / 1.0E9)
Esempio n. 16
0
 def set_microstepping(self, ms, board_ind=0):
     """
     sets the microstepping value int power
     i.e 7 = 2^7
     """
     board_ind = ctypes.c_int16(board_ind)
     ms = ctypes.c_int16(ms)
     self.cmd.send_command(7, (board_ind, ms))
Esempio n. 17
0
 def rotate(self, direction, sps, board_ind=0):
     """
     rotates the motor in the direction of dir at sps steps per second
     """
     board_ind = ctypes.c_int16(board_ind)
     direction = ctypes.c_int16(direction)
     sps = ctypes.c_int16(sps)
     self.cmd.send_command(11, (board_ind, direction, sps))
Esempio n. 18
0
 def move_steps(self, direction, steps, board_ind=0):
     """
     moves number of steps in the direction specified
     """
     board_ind = ctypes.c_int16(board_ind)
     direction = ctypes.c_int16(direction)
     steps = ctypes.c_int16(steps)
     self.cmd.send_command(12, (board_ind, direction, steps))
 def get_acceleration(self):
     raw_data = self.__bus.read_i2c_block_data(self.__dev_id,
                                               C.MPU6050_RA_ACCEL_XOUT_H, 6)
     accel = [0] * 3
     accel[0] = ctypes.c_int16(raw_data[0] << 8 | raw_data[1]).value
     accel[1] = ctypes.c_int16(raw_data[2] << 8 | raw_data[3]).value
     accel[2] = ctypes.c_int16(raw_data[4] << 8 | raw_data[5]).value
     return accel
Esempio n. 20
0
 def _lowLevelIsReady(self):
     ready = c_int16()
     m = self.lib.ps4000aIsReady(c_int16(self.handle), byref(ready))
     self.checkResult(m)
     if ready.value:
         return True
     else:
         return False
Esempio n. 21
0
File: vaht.py Progetto: agrif/moiety
 def rect(self, i):
     left = c_int16()
     right = c_int16()
     top = c_int16()
     bottom = c_int16()
     self._rect(self, i, ctypes.byref(left), ctypes.byref(right),
                ctypes.byref(top), ctypes.byref(bottom))
     return (left.value, right.value, top.value, bottom.value)
Esempio n. 22
0
 def _lowLevelIsReady(self):
     ready = c_int16()
     ready = self.lib.ps3000_ready(c_int16(self.handle))
     if ready > 0:
         return True
     elif ready == 0:
         return False
     else:
         raise IOError("ps3000_ready returned %d" % ready.value)
Esempio n. 23
0
    def _lowLevelSetSimpleTrigger(self, enabled, trigsrc, threshold_adc,
                                  direction, delay, timeout_ms):
        # TODO: Fix 'auto' which is where trigger occurs in block.
        # Delay is not used

        m = self.lib.ps3000_set_trigger(
            c_int16(self.handle), c_enum(trigsrc), c_int16(threshold_adc),
            c_enum(direction), c_int16(delay), c_int16(timeout_ms))
        self.checkResult(m)
Esempio n. 24
0
    def _lowLevelGetUnitInfo(self, info):
        s = create_string_buffer(256)

        m = self.lib.ps3000_get_unit_info(
            c_int16(self.handle), byref(s), c_int16(len(s)), c_enum(info))
        self.checkResult(m)

        # should this bee ascii instead?
        # I think they are equivalent...
        return s.value.decode('utf-8')
Esempio n. 25
0
 def _lowLevelRunBlock(self, numPreTrigSamples, numPostTrigSamples,
                       timebase, oversample, segmentIndex):
     timeIndisposedMs = c_int32()
     m = self.lib.ps6000RunBlock(
         c_int16(self.handle), c_uint32(numPreTrigSamples),
         c_uint32(numPostTrigSamples), c_uint32(timebase),
         c_int16(oversample), byref(timeIndisposedMs),
         c_uint32(segmentIndex), c_void_p(), c_void_p())
     self.checkResult(m)
     return timeIndisposedMs.value
Esempio n. 26
0
 def _lowLevelGetUnitInfo(self, info):
     s = create_string_buffer(256)
     m = self.lib.ps3000_get_unit_info(c_int16(self.handle), byref(s),
                                       c_int16(len(s)), c_enum(info))
     if m == 0:
         raise IOError('Error calling %s: parameter out of range' % (inspect.stack()[1][3]))
     else:
         print('%d bytes returned' % (m))
     # should this be ascii instead?
     # I think they are equivalent...
     return s.value.decode('utf-8')
Esempio n. 27
0
 def _lowLevelSetSigGenBuiltInSimple(self, offsetVoltage, pkToPk, waveType,
                                     frequency, shots, triggerType,
                                     triggerSource):
     m = self.lib.ps2000_set_sig_gen_built_in(
         c_int16(self.handle),
         c_int32(int(offsetVoltage * 1000000)),
         c_int32(int(pkToPk        * 1000000)),
         c_int16(waveType),
         c_float(frequency), c_float(frequency),
         c_float(0), c_float(0), c_enum(0), c_uint32(0))
     self.checkResult(m)
Esempio n. 28
0
 def _lowLevelSetChannel(self, chNum, enabled, coupling, VRange, VOffset,
                         BWLimited):
     m = self.lib.ps5000aSetChannel(c_int16(self.handle), c_enum(chNum),
                                   c_int16(enabled), c_enum(coupling),
                                   c_enum(VRange), c_float(VOffset))
     self.checkResult(m)
     if BWLimited:
         m = self.lib.ps5000aSetBandwidthFilter(c_int16(self.handle), c_enum(chNum), c_enum(1))
     else:
         m = self.lib.ps5000aSetBandwidthFilter(c_int16(self.handle), c_enum(chNum), c_enum(0))
     self.checkResult(m)
Esempio n. 29
0
    def _lowLevelOpenUnitProgress(self):
        complete = c_int16()
        progressPercent = c_int16()
        handle = c_int16()

        m = self.lib.ps4000OpenUnitProgress(byref(handle), byref(progressPercent), byref(complete))
        self.checkResult(m)

        # if we only wanted to return one value, we could do somethign like
        # progressPercent = progressPercent * (1 - 0.1 * complete)
        return (progressPercent, complete)
Esempio n. 30
0
 def _lowLevelGetValues(self, numSamples, startIndex, downSampleRatio,
                        downSampleMode, segmentIndex):
     numSamplesReturned = c_uint32()
     numSamplesReturned.value = numSamples
     overflow = c_int16()
     m = self.lib.ps4000aGetValues(
         c_int16(self.handle), c_uint32(startIndex),
         byref(numSamplesReturned), c_uint32(downSampleRatio),
         c_enum(downSampleMode), c_uint16(segmentIndex),
         byref(overflow))
     self.checkResult(m)
     return (numSamplesReturned.value, overflow.value)
Esempio n. 31
0
 def _lowLevelChangePowerSource(self, powerstate):
     m = self.lib.ps3000aChangePowerSource(
         c_int16(self.handle),
         c_enum(powerstate))
     self.checkResult(m)
Esempio n. 32
0
    def read_segment(self, import_neuroshare_segment=True, lazy=False):
        """
        Arguments:
            import_neuroshare_segment: import neuroshare segment as SpikeTrain
            with associated waveforms or not imported at all.
        """
        assert not lazy, 'Do not support lazy'

        seg = Segment(file_origin=os.path.basename(self.filename), )

        if sys.platform.startswith('win'):
            neuroshare = ctypes.windll.LoadLibrary(self.dllname)
        elif sys.platform.startswith('linux'):
            neuroshare = ctypes.cdll.LoadLibrary(self.dllname)
        neuroshare = DllWithError(neuroshare)

        # elif sys.platform.startswith('darwin'):

        # API version
        info = ns_LIBRARYINFO()
        neuroshare.ns_GetLibraryInfo(ctypes.byref(info), ctypes.sizeof(info))
        seg.annotate(neuroshare_version=str(info.dwAPIVersionMaj) + '.' +
                     str(info.dwAPIVersionMin))

        # open file
        hFile = ctypes.c_uint32(0)
        neuroshare.ns_OpenFile(ctypes.c_char_p(self.filename),
                               ctypes.byref(hFile))
        fileinfo = ns_FILEINFO()
        neuroshare.ns_GetFileInfo(hFile, ctypes.byref(fileinfo),
                                  ctypes.sizeof(fileinfo))

        # read all entities
        for dwEntityID in range(fileinfo.dwEntityCount):
            entityInfo = ns_ENTITYINFO()
            neuroshare.ns_GetEntityInfo(hFile, dwEntityID,
                                        ctypes.byref(entityInfo),
                                        ctypes.sizeof(entityInfo))

            # EVENT
            if entity_types[entityInfo.dwEntityType] == 'ns_ENTITY_EVENT':
                pEventInfo = ns_EVENTINFO()
                neuroshare.ns_GetEventInfo(hFile, dwEntityID,
                                           ctypes.byref(pEventInfo),
                                           ctypes.sizeof(pEventInfo))

                if pEventInfo.dwEventType == 0:  # TEXT
                    pData = ctypes.create_string_buffer(
                        pEventInfo.dwMaxDataLength)
                elif pEventInfo.dwEventType == 1:  # CVS
                    pData = ctypes.create_string_buffer(
                        pEventInfo.dwMaxDataLength)
                elif pEventInfo.dwEventType == 2:  # 8bit
                    pData = ctypes.c_byte(0)
                elif pEventInfo.dwEventType == 3:  # 16bit
                    pData = ctypes.c_int16(0)
                elif pEventInfo.dwEventType == 4:  # 32bit
                    pData = ctypes.c_int32(0)
                pdTimeStamp = ctypes.c_double(0.)
                pdwDataRetSize = ctypes.c_uint32(0)

                ea = Event(name=str(entityInfo.szEntityLabel), )

                times = []
                labels = []
                for dwIndex in range(entityInfo.dwItemCount):
                    neuroshare.ns_GetEventData(hFile, dwEntityID, dwIndex,
                                               ctypes.byref(pdTimeStamp),
                                               ctypes.byref(pData),
                                               ctypes.sizeof(pData),
                                               ctypes.byref(pdwDataRetSize))
                    times.append(pdTimeStamp.value)
                    labels.append(str(pData.value))
                ea.times = times * pq.s
                ea.labels = np.array(labels, dtype='S')

                seg.events.append(ea)

            # analog
            if entity_types[entityInfo.dwEntityType] == 'ns_ENTITY_ANALOG':
                pAnalogInfo = ns_ANALOGINFO()

                neuroshare.ns_GetAnalogInfo(hFile, dwEntityID,
                                            ctypes.byref(pAnalogInfo),
                                            ctypes.sizeof(pAnalogInfo))
                dwIndexCount = entityInfo.dwItemCount

                pdwContCount = ctypes.c_uint32(0)
                pData = np.zeros((entityInfo.dwItemCount, ), dtype='float64')
                total_read = 0
                while total_read < entityInfo.dwItemCount:
                    dwStartIndex = ctypes.c_uint32(total_read)
                    dwStopIndex = ctypes.c_uint32(entityInfo.dwItemCount -
                                                  total_read)

                    neuroshare.ns_GetAnalogData(
                        hFile, dwEntityID, dwStartIndex, dwStopIndex,
                        ctypes.byref(pdwContCount),
                        pData[total_read:].ctypes.data_as(
                            ctypes.POINTER(ctypes.c_double)))
                    total_read += pdwContCount.value

                signal = pq.Quantity(pData,
                                     units=pAnalogInfo.szUnits,
                                     copy=False)

                # t_start
                dwIndex = 0
                pdTime = ctypes.c_double(0)
                neuroshare.ns_GetTimeByIndex(hFile, dwEntityID, dwIndex,
                                             ctypes.byref(pdTime))

                anaSig = AnalogSignal(
                    signal,
                    sampling_rate=pAnalogInfo.dSampleRate * pq.Hz,
                    t_start=pdTime.value * pq.s,
                    name=str(entityInfo.szEntityLabel),
                )
                anaSig.annotate(probe_info=str(pAnalogInfo.szProbeInfo))
                seg.analogsignals.append(anaSig)

            # segment
            if entity_types[
                    entityInfo.
                    dwEntityType] == 'ns_ENTITY_SEGMENT' and import_neuroshare_segment:

                pdwSegmentInfo = ns_SEGMENTINFO()
                if not str(entityInfo.szEntityLabel).startswith('spks'):
                    continue

                neuroshare.ns_GetSegmentInfo(hFile, dwEntityID,
                                             ctypes.byref(pdwSegmentInfo),
                                             ctypes.sizeof(pdwSegmentInfo))
                nsource = pdwSegmentInfo.dwSourceCount

                pszMsgBuffer = ctypes.create_string_buffer(" " * 256)
                neuroshare.ns_GetLastErrorMsg(ctypes.byref(pszMsgBuffer), 256)

                for dwSourceID in range(pdwSegmentInfo.dwSourceCount):
                    pSourceInfo = ns_SEGSOURCEINFO()
                    neuroshare.ns_GetSegmentSourceInfo(
                        hFile, dwEntityID, dwSourceID,
                        ctypes.byref(pSourceInfo), ctypes.sizeof(pSourceInfo))

                pdTimeStamp = ctypes.c_double(0.)
                dwDataBufferSize = pdwSegmentInfo.dwMaxSampleCount * pdwSegmentInfo.dwSourceCount
                pData = np.zeros((dwDataBufferSize), dtype='float64')
                pdwSampleCount = ctypes.c_uint32(0)
                pdwUnitID = ctypes.c_uint32(0)

                nsample = int(dwDataBufferSize)
                times = np.empty((entityInfo.dwItemCount), dtype='f')
                waveforms = np.empty(
                    (entityInfo.dwItemCount, nsource, nsample), dtype='f')
                for dwIndex in range(entityInfo.dwItemCount):
                    neuroshare.ns_GetSegmentData(
                        hFile, dwEntityID, dwIndex, ctypes.byref(pdTimeStamp),
                        pData.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
                        dwDataBufferSize * 8, ctypes.byref(pdwSampleCount),
                        ctypes.byref(pdwUnitID))

                    times[dwIndex] = pdTimeStamp.value
                    waveforms[dwIndex, :, :] = pData[:nsample *
                                                     nsource].reshape(
                                                         nsample,
                                                         nsource).transpose()

                sptr = SpikeTrain(
                    times=pq.Quantity(times, units='s', copy=False),
                    t_stop=times.max(),
                    waveforms=pq.Quantity(waveforms,
                                          units=str(pdwSegmentInfo.szUnits),
                                          copy=False),
                    left_sweep=nsample / 2. /
                    float(pdwSegmentInfo.dSampleRate) * pq.s,
                    sampling_rate=float(pdwSegmentInfo.dSampleRate) * pq.Hz,
                    name=str(entityInfo.szEntityLabel),
                )
                seg.spiketrains.append(sptr)

            # neuralevent
            if entity_types[
                    entityInfo.dwEntityType] == 'ns_ENTITY_NEURALEVENT':
                pNeuralInfo = ns_NEURALINFO()
                neuroshare.ns_GetNeuralInfo(hFile, dwEntityID,
                                            ctypes.byref(pNeuralInfo),
                                            ctypes.sizeof(pNeuralInfo))

                pData = np.zeros((entityInfo.dwItemCount, ), dtype='float64')
                dwStartIndex = 0
                dwIndexCount = entityInfo.dwItemCount
                neuroshare.ns_GetNeuralData(
                    hFile, dwEntityID, dwStartIndex, dwIndexCount,
                    pData.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))
                times = pData * pq.s
                t_stop = times.max()

                sptr = SpikeTrain(
                    times,
                    t_stop=t_stop,
                    name=str(entityInfo.szEntityLabel),
                )
                seg.spiketrains.append(sptr)

        # close
        neuroshare.ns_CloseFile(hFile)

        seg.create_many_to_one_relationship()
        return seg
Esempio n. 33
0
 def _lowLevelClearDataBuffers(self, channel):
     m = self.lib.ps6000SetDataBuffers(c_int16(self.handle),
                                       c_enum(channel), c_void_p(),
                                       c_void_p(), c_uint32(0), c_enum(0))
     self.checkResult(m)
Esempio n. 34
0
 def release_card(self):
     releaseErr = ctypes.c_int16(self.dll.Release_Card(self.card_id))
     if releaseErr.value != 0:
         self.log(message="Release_Card: Non-zero status code:" +
                  str(releaseErr.value))
     return
Esempio n. 35
0
 def _lowLevelClearDataBuffer(self, channel, segmentIndex):
     """Clear the data in the picoscope."""
     m = self.lib.ps2000aSetDataBuffer(
         c_int16(self.handle), c_enum(channel),
         c_void_p(), c_uint32(0), c_uint32(segmentIndex), c_enum(0))
     self.checkResult(m)
 def awaitCaptureComplete(self):
     ready = ctypes.c_int16(0)
     check = ctypes.c_int16(0)
     while ready.value == check.value:
         self.status["isReady"] = ps.ps5000aIsReady(self.chandle,
                                                    ctypes.byref(ready))
Esempio n. 37
0
import numpy as np
from picosdk.usbtc08 import usbtc08 as tc08
from picosdk.functions import assert_pico2000_ok
import sys

from time import sleep

import time
import datetime

#from pylab import *

filename = sys.argv[1]

# Create chandle and status ready for use
chandle = ctypes.c_int16()
status = {}

# open unit
status["open_unit"] = tc08.usb_tc08_open_unit()
assert_pico2000_ok(status["open_unit"])
chandle = status["open_unit"]

# set mains rejection to 50 Hz
status["set_mains"] = tc08.usb_tc08_set_mains(chandle, 0)
assert_pico2000_ok(status["set_mains"])

# set up channel
# therocouples types and int8 equivalent
# B=66 , E=69 , J=74 , K=75 , N=78 , R=82 , S=83 , T=84 , ' '=32 , X=88
f = open(filename, "w+")
Esempio n. 38
0
 def _lowLevelClearDataBuffer(self, channel, segmentIndex):
     """data should be a numpy array."""
     m = self.lib.ps4000SetDataBuffer(c_int16(self.handle), c_enum(channel),
                                      c_void_p(), c_uint32(0), c_enum(0))
     self.checkResult(m)
Esempio n. 39
0
preTriggerFraction = 0.3
samples = int(1E6)
# samples = preTriggerSamples + postTriggerSamples
preTriggerSamples = int(samples * preTriggerFraction)
postTriggerSamples = samples - preTriggerSamples

# First, we are going to create the folder if it isn't there already
# The external drive folder
mydir = "/mnt/extdrive"
mydir = os.path.join(mydir, datetime.now().strftime('%Y-%m-%d'))
#mydir = os.path.join( os.getcwd(), datetime.now().strftime('%Y-%m-%d'))
if not os.path.isdir(mydir): os.makedirs(mydir)

# Create handle and status ready for use
status = {}
handle = ctypes.c_int16()  # Actually c-handle

# Opens the device
status["openunit"] = ps.ps2000aOpenUnit(ctypes.byref(handle), None)

try:
    assert_pico_ok(status["openunit"])
except:

    # powerstate becomes the status number of openunit
    powerstate = status["openunit"]

    # If powerstate is the same as 282 then it will run this if statement
    if powerstate == 282:
        # Changes the power input to "PICO_POWER_SUPPLY_NOT_CONNECTED"
        status["ChangePowerSource"] = ps.ps2000aChangePowerSource(handle, 282)
Esempio n. 40
0
 def _lowLevelStop(self):
     m = self.lib.ps3000aStop(c_int16(self.handle))
     self.checkResult(m)
Esempio n. 41
0
 def _lowLevelCloseUnit(self):
     m = self.lib.ps3000aCloseUnit(c_int16(self.handle))
     self.checkResult(m)
Esempio n. 42
0
 def _lowLevelFlashLed(self, times):
     m = self.lib.ps3000aFlashLed(c_int16(self.handle), c_int16(times))
     self.checkResult(m)
Esempio n. 43
0
 def _lowLevelSetNoOfCaptures(self, numCaptures):
     m = self.lib.ps3000aSetNoOfCaptures(c_int16(self.handle),
                                         c_uint16(numCaptures))
     self.checkResult(m)
Esempio n. 44
0
 def _lowLevelSigGenSoftwareControl(self, triggerType):
     m = self.lib.ps3000aSigGenSoftwareControl(
         c_int16(self.handle),
         c_enum(triggerType))
     self.checkResult(m)
Esempio n. 45
0
 def maximum_value(self, device):
     if not hasattr(self, '_maximum_value'):
         return (2**15) - 1
     max_adc = c_int16(0)
     self._maximum_value(c_int16(device.handle), byref(max_adc))
     return max_adc.value
Esempio n. 46
0
 def state(self, val=None):
     if val == None: return Inp32(ctypes.c_int16(self.port))
     else: Out32(ctypes.c_int16(self.port), ctypes.c_int16(val))
Esempio n. 47
0
 def _python_close_unit(self, handle):
     return self._close_unit(c_int16(handle))
Esempio n. 48
0
#
# PicoScope 5000 (A API) Signal Generator Example
# This example demonstrates how to use the PicoScope 5000 Series (ps5000a) driver API functions to set up the signal generator to do the following:
# 
# 1. Output a sine wave 
# 2. Output a square wave 
# 3. Output a sweep of a square wave signal

import ctypes
from picosdk.ps5000a import ps5000a as ps
import time
from picosdk.functions import assert_pico_ok


status = {}
chandle = ctypes.c_int16()

# Open the device
status["openUnit"] = ps.ps5000aOpenUnit(ctypes.byref(chandle), None, 1)


try:
    assert_pico_ok(status["openUnit"])
except: # PicoNotOkError:

    powerStatus = status["openUnit"]

    if powerStatus == 286:
        status["changePowerSource"] = ps.ps5000aChangePowerSource(chandle, powerStatus)
    elif powerStatus == 282:
        status["changePowerSource"] = ps.ps5000aChangePowerSource(chandle, powerStatus)
Esempio n. 49
0
 def _lowLevelFlashLed(self, times):
     m = self.lib.ps2000_flash_led(c_int16(self.handle))
     self.checkResult(m)
Esempio n. 50
0
 def getAccelZ(self):
     data = ctypes.c_int16(self.bus.read_word_data(
         MPU60X0.ACCEL_ZOUT)).value
     return data / self.accel_scale
Esempio n. 51
0
 def __new__(cls, val):
     val = ctypes.c_int16(val).value
     return super().__new__(cls, val)
Esempio n. 52
0
 def getTemp(self):
     data = ctypes.c_int16(self.bus.read_word_data(MPU60X0.TEMP_OUT)).value
     return data / self.temp_scale + self.temp_offset
Esempio n. 53
0
    def asynchronous_double_buffered_analog_input_read(self,
                                                       sample_freq,
                                                       sample_count,
                                                       card_buffer_size=500000,
                                                       verbose=False,
                                                       channel=0):
        '''
		Non-Triggered Double-Buffered Asynchronous  Analog Input Continuous Read
		Steps: [Adlink PCIS-DASK manual,page 47]

		1. AI_XXXX_Config
			Configure the card for the asynchronous mode

		2. AI_AsyncDblBufferMode 
			Enable double buffered mode

		3. AI_ContReadChannel
			Read from a single channel (=0)

		4. while not stop:

			4.1 if (AI_AsyncDblBufferHaldReady):   #Check if buffer is half full]
				
				4.1.1 AI_AsyncDblBufferTransfer	   #Transfer data from card buffer into user buffer
			
		5. AI_AsyncClear
		6. Convert all data to volts and return

		'''

        #AI_AsyncDblBufferMode - initialize Double Buffer Mode
        buffModeErr = ctypes.c_int16(
            self.dll.AI_AsyncDblBufferMode(c_ushort(self.card_id),
                                           ctypes.c_bool(1)))
        if verbose or buffModeErr.value != 0:
            self.log(message="AI_AsyncDblBufferMode: Non-zero status code" +
                     str(buffModeErr.value))

        #card buffer
        cardBuffer = (c_ushort * card_buffer_size)()

        #user buffers
        user_buffer_size = old_div(
            card_buffer_size, 2)  #half due to being full when buffer is read
        nbuff = int(math.ceil(sample_count / float(user_buffer_size)))

        # uBs = [(c_double*user_buffer_size)()]*nbuff
        uBs = []
        print(uBs)
        # oBs = [(c_double*user_buffer_size)()]*nbuff
        oBs = []
        if verbose:
            self.log(message="Number of user buffers:" + str(nbuff))

        #AI_ContReadChanne

        readErr = ctypes.c_int16(
            self.dll.AI_ContReadChannel(
                c_ushort(self.card_id),  #CardNumber
                c_ushort(channel),  #Channel
                c_ushort(adlink9812_constants.AD_B_1_V),  #AdRange
                cardBuffer,  #Buffer
                c_uint32(card_buffer_size),  #ReadCount
                c_double(sample_freq),  #SampleRate (Hz)
                c_ushort(
                    adlink9812_constants.ASYNCH_OP)  #SyncMode - Asynchronous
            ))

        if verbose or readErr.value != 0:
            self.log(message="AI_ContReadChannel: Non-zero status code" +
                     str(readErr.value))

        #AI_AsyncDblBufferHalfReader
        #I16 AI_AsyncDblBufferHalfReady (U16 CardNumber, BOOLEAN *HalfReady,BOOLEAN *StopFlag)

        for i in range(nbuff):
            currentBuffer = (c_double * user_buffer_size)()
            halfReady = c_bool(0)
            stopFlag = c_bool(0)
            while halfReady.value != True:
                buffReadyErr = ctypes.c_int16(
                    self.dll.AI_AsyncDblBufferHalfReady(
                        c_ushort(self.card_id), ctypes.byref(halfReady),
                        ctypes.byref(stopFlag)))
                if buffReadyErr.value != 0:
                    self.log(message="buffReadErr:" + str(buffReadyErr.value))
                    self.log(message="HalfReady:" + str(halfReady.value))

            #AI_AsyncDblBufferTransfer
            #I16 AI_AsyncDblBufferTransfer (U16 CardNumber, U16 *Buffer)
            buffTransferErr = ctypes.c_int16(
                self.dll.AI_AsyncDblBufferTransfer(c_ushort(
                    self.card_id), ctypes.byref(currentBuffer)))
            uBs.append(currentBuffer)
            if buffTransferErr.value != 0:
                self.log(message="buffTransferErr:" +
                         str(buffTransferErr.value))

        accessCnt = ctypes.c_int32(0)
        clearErr = ctypes.c_int16(
            self.dll.AI_AsyncClear(self.card_id, ctypes.byref(accessCnt)))
        if verbose:
            self.log(message="AI_AsyncClear,AccessCnt:" + str(accessCnt.value))

        #concatenate user buffer onto existing numpy array
        #reinitialize user buffer

        for i in range(nbuff):
            oB = (c_double * user_buffer_size)()
            convertErr = ctypes.c_int16(
                self.dll.AI_ContVScale(
                    c_ushort(self.card_id),  #CardNumber
                    c_ushort(adlink9812_constants.AD_B_1_V),  #AdRange
                    uBs[i],  #DataBuffer   - array storing raw 16bit A/D values
                    oB,  #VoltageArray - reference to array storing voltages
                    c_uint32(
                        user_buffer_size
                    )  #Sample count - number of samples to be converted
                ))
            oBs.append(oB)
            if convertErr.value != 0:
                self.log(message="AI_ContVScale: Non-zero status code:" +
                         str(convertErr.value))
        return np.concatenate(oBs)
Esempio n. 54
0
    def process_qmsg(self, msg):
        m_type = ctypes.c_int16(msg.type() & 0xffff).value  # lower 16 bits of msg.type() is signed message type
        m_slot = int(msg.arg1()) & 0x1                      # message slot id
        m_ts   = float(msg.arg2())                          # message sender timestamp
        m_buf = msg.to_string()                             # message data

        if m_type == -1:    # Sync Timeout
            if self.debug >= 9:
                sys.stderr.write("%s [%d] Timeout waiting for sync sequence\n" % (log_ts.get(), self.msgq_id))

            if self.msgq_id == 0: # primary/control channel
                self.cc_timeouts += 1
                if self.cc_timeouts >= CC_HUNT_TIMEOUTS:
                    self.cc_timeouts = 0
                    self.current_state = self.states.IDLE
                    self.tune_next_chan()
                    return
            else:                 # secondary/voice channel
                pass

        elif m_type >= 0:   # Receiving a PDU means sync must be present
            if self.msgq_id == 0:
                self.cc_timeouts = 0

        # If voice channel not identified, begin LCN search
        if (self.msgq_id > 0) and (self.current_state == self.states.SRCH) and (self.tune_time + VC_SRCH_TIME < time.time()):
            self.tune_next_chan()

        # log received message
        if self.debug >= 10:
            d_buf = "0x"
            for byte in m_buf:
                d_buf += format(get_ordinals(byte),"02x")
            sys.stderr.write("%s [%d] DMR PDU: lcn(%d), state(%d), type(%d), slot(%d), data(%s)\n" % (log_ts.get(), self.msgq_id, self.chan_list[self.current_chan], self.current_state, m_type, m_slot, d_buf))

        if m_type == 0:   # CACH SLC
            self.rx_CACH_SLC(m_buf)
        elif m_type == 1: # CACH CSBK
            pass
        elif m_type == 2: # SLOT PI
            self.rx_SLOT_PI(m_slot, m_buf)
        elif m_type == 3: # SLOT VLC
            self.rx_SLOT_VLC(m_slot, m_buf)
        elif m_type == 4: # SLOT TLC
            self.rx_SLOT_TLC(m_slot, m_buf)
        elif m_type == 5: # SLOT CSBK
            self.rx_SLOT_CSBK(m_slot, m_buf)
        elif m_type == 6: # SLOT MBC
            pass
        elif m_type == 7: # SLOT ELC
            self.rx_SLOT_ELC(m_slot, m_buf)
        elif m_type == 8: # SLOT ERC
            pass
        elif m_type == 9: # SLOT ESB
            pass
        else:             # Unknown Message
            return

        # If this is Capacity Plus, try to keep the first receiver tuned to a control channel
        if (self.current_type == 1) and (self.msgq_id == 0) and (self.current_state > self.states.CC):
            if self.debug >= 1:
                sys.stderr.write("%s [%d] Looking for control channel\n" % (log_ts.get(), self.msgq_id))
            self.cc_timeouts = 0
            self.current_state = self.states.IDLE
            self.tune_next_chan()
MOT_LimitSwitchMakeOnHomeSwapped = c_word(0x84)
MOT_LimitSwitchBreakOnHomeSwapped = c_word(0x85)
MOT_LimitSwitchModes = c_word

# enum MOT_LimitSwitchSWModes
MOT_LimitSwitchSWModeUndefined = c_word(0x00)
MOT_LimitSwitchIgnored = c_word(0x01)
MOT_LimitSwitchStopImmediate = c_word(0x02)
MOT_LimitSwitchStopProfiled = c_word(0x03)
MOT_LimitSwitchIgnored_Rotational = c_word(0x81)
MOT_LimitSwitchStopImmediate_Rotational = c_word(0x82)
MOT_LimitSwitchStopProfiled_Rotational = c_word(0x83)
MOT_LimitSwitchSWModes = c_word

# enum MOT_LimitsSoftwareApproachPolicy
DisallowIllegalMoves = c_int16(0)
AllowPartialMoves = c_int16(1)
AllowAllMoves = c_int16(2)
MOT_LimitsSoftwareApproachPolicy = c_int16

# enum MOT_PID_LoopMode
MOT_PIDLoopModeDisabled = c_word(0x00)
MOT_PIDOpenLoopMode = c_word(0x01)
MOT_PIDClosedLoopMode = c_word(0x02)
MOT_PID_LoopMode = c_word

# enum MOT_MovementModes
LinearRange = c_int(0x00)
RotationalUnlimited = c_int(0x01)
RotationalWrapping = c_int(0x02)
MOT_MovementModes = c_int
Esempio n. 56
0
message = create_string_buffer(1024)
tlPM.getCalibrationMsg(message)
print(c_char_p(message.raw).value)

time.sleep(0.5)

power_measurements = []
times = []
count = 0
powers = (c_double * 20)()
timestamps = (c_uint16 * 20)()
flag = c_uint16(1)
wavelength = c_double(470)
print(wavelength.value)
print(tlPM.setWavelength(wavelength))
print(tlPM.getWavelength(c_int16(0), byref(wavelength)))
print(wavelength.value)
print(tlPM.setArrMeasurement(flag))
print(tlPM.getArrMeasurement(byref(flag)))
print(flag)
count = c_uint16(20)
#interval = c_uint16(10000)
print(count.value)
tlPM.getPowerArrayMeasurement(byref(count), byref(timestamps), byref(powers))
#tlPM.getPowerMeasurementSequence(count,interval,powers)
print(count.value)
for i in range(20):
    print(timestamps[i], powers[i])
    #print(powers.value)

tlPM.close()
Esempio n. 57
0
 def _lowLevelSetNoOfCaptures(self, nCaptures):
     m = self.lib.ps6000SetNoOfCaptures(c_int16(self.handle),
                                        c_uint32(nCaptures))
     self.checkResult(m)
Esempio n. 58
0
 def _lowLevelSetChannel(self, chNum, enabled, coupling, VRange, VOffset,
                         BWLimited):
     m = self.lib.ps3000_set_channel(c_int16(self.handle), c_enum(chNum),
                                     c_int16(enabled), c_enum(coupling),
                                     c_enum(VRange))
     self.checkResult(m)
Esempio n. 59
0
 def _lowlevelPingUnit(self):
     m = self.lib.ps3000aPingUnit(c_int16(self.handle))
     return m
Esempio n. 60
0
 def _lowLevelGetMaxSegments(self):
     maxSegments = c_int16()
     m = self.lib.ps3000aGetMaxSegments(c_int16(self.handle),
                                        byref(maxSegments))
     self.checkResult(m)
     return maxSegments.value