Пример #1
0
 def run(self):
     self.status['run'] = ps.ps5000aRunBlock(self.chandle,
                                             self.preTrigger_samples,
                                             self.postTrigger_samples,
                                             self.timebase, None, 0, None,
                                             None)
     assert_pico_ok(self.status['run'])
 def runBlock(self,**kwargs): 
     '''
     arms the trigger, block mode is close to repeat (with re-arm) or single mode (without re-arm)
     rapid block accumulates several events (similar to fast frame modes on other scopes)
     arguments: none
     keyword arguments (defaults in self.trigger.settings):
         preTrigger: fraction of samples before the trigger occurs (0 to 1)
         segmentIndex: scope memory segment to store the run result
     after successfully arming the trigger, self.trigger.settings is updated
     after triggering, the channel records the noSamples and then stops (until re-arming) 
     '''
     settings = {}
     for key,current_value in self.settings.items():
         settings[key] = kwargs[key] if key in kwargs else current_value
     check_kwargs_scope(**kwargs) 
     
     
     cmaxSamples = ctypes.c_int32(self.scope.settings['noSamples'])
     self.status["MemorySegments"] = ps.ps5000aMemorySegments(self.chandle, settings['nSegments'], ctypes.byref(cmaxSamples))
     assert_pico_ok(self.status["MemorySegments"])
     
     # sets number of captures
     self.status["SetNoOfCaptures"] = ps.ps5000aSetNoOfCaptures(self.chandle, settings['nSegments'])
     assert_pico_ok(self.status["SetNoOfCaptures"])
      
     _preTriggerSamples = int(self.scope.settings['noSamples']*settings['preTrigger'])
     _postTriggerSamples = self.scope.settings['noSamples'] - _preTriggerSamples
     _timebase = self.scope.settings['timebase']
     _timeIndisposeMs = ctypes.c_int32()
     _segmentIndex = settings['segmentIndex']
     #additional callback options here, use isready instead
     self.status["runBlock"] = ps.ps5000aRunBlock(self.chandle, _preTriggerSamples, _postTriggerSamples, 
                                             _timebase, ctypes.byref(_timeIndisposeMs), _segmentIndex, None, None)
     assert_pico_ok(self.status["runBlock"])
     self.settings = settings
Пример #3
0
    def block(self):
        self.data_mVRay.clear()
        self.time = {}
        self.status["runblock"] = ps.ps5000aRunBlock(self.chandle,
                                                     self.preTriggerSamples,
                                                     self.postTriggerSamples,
                                                     self.timebase, None, 0,
                                                     None, None)
        assert_pico_ok(self.status["runblock"])

        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))

        self.status["GetValuesBulk"] = ps.ps5000aGetValuesBulk(
            self.chandle, ctypes.byref(self.cmaxSamples), 0, self.blocks - 1,
            0, 0, ctypes.byref(self.overflow))
        assert_pico_ok(self.status["GetValuesBulk"])
        for i in range(self.blocks):
            self.data_mVRay.append(
                adc2mV(self.bufferMaxRay[i], self.chARange, self.maxADC))
            #self.data_mVRay.append(np.asarray(self.bufferMaxRay[i], dtype=int) * self.chARange / self.maxADC.value)
        self.createTimeAxis()
 def runRapidBlock(self,**kwargs):
     '''
     arms the trigger, block mode is close to repeat (with re-arm) or single mode (without re-arm)
     rapid block accumulates several events (similar to fast frame modes on other scopes)
     arguments: none
     keyword arguments (defaults in self.trigger.settings):
         preTrigger: fraction of samples before the trigger occurs (0 to 1)
         segmentIndex: scope memory segment to store the run result
         nSegments: number of samples to capture
     after successfully arming the trigger, self.trigger.settings is updated
     after triggering, the channel records the noSamples and then stops (until re-arming) 
     '''
     settings = {}
     for key,current_value in self.settings.items():
         settings[key] = kwargs[key] if key in kwargs else current_value
     check_kwargs_scope(**kwargs)  
     # Handle = Chandle
     # nSegments = 10
     # nMaxSamples = ctypes.byref(cmaxSamples)
     cmaxSamples = ctypes.c_int32(self.scope.settings['noSamples'])
     self.status["MemorySegments"] = ps.ps5000aMemorySegments(self.chandle, settings['nSegments'], ctypes.byref(cmaxSamples))
     assert_pico_ok(self.status["MemorySegments"])
     
     # sets number of captures
     self.status["SetNoOfCaptures"] = ps.ps5000aSetNoOfCaptures(self.chandle, settings['nSegments'])
     assert_pico_ok(self.status["SetNoOfCaptures"])
     
     # Starts the block capture
     # Handle = chandle
     # Number of prTriggerSamples
     # Number of postTriggerSamples
     # Timebase = 2 = 4ns (see Programmer's guide for more information on timebases)
     # time indisposed ms = None (This is not needed within the example)
     # Segment index = 0
     # LpRead = None
     # pParameter = None
     _preTriggerSamples = int(self.scope.settings['noSamples']*settings['preTrigger'])
     _postTriggerSamples = self.scope.settings['noSamples'] - _preTriggerSamples
     _timebase = self.scope.settings['timebase']
     _timeIndisposeMs = ctypes.c_int32()
     _segmentIndex = settings['segmentIndex']
     self.status["runblock"] = ps.ps5000aRunBlock(self.chandle, _preTriggerSamples, _postTriggerSamples, 
                                             _timebase, ctypes.byref(_timeIndisposeMs), _segmentIndex, None, None)
     assert_pico_ok(self.status["runblock"])
     self.settings = settings
    def runBlockCapture(self):
        # Create buffers ready for assigning pointers for data collection
        self.bufferAMax = (ctypes.c_int16 * self.totalSamples)()
        self.bufferAMin = (ctypes.c_int16 * self.totalSamples)(
        )  # used for downsampling which isn't in the scope of this example
        self.bufferBMax = (ctypes.c_int16 * self.totalSamples)()
        self.bufferBMin = (ctypes.c_int16 * self.totalSamples)(
        )  # used for downsampling which isn't in the scope of this example

        time_indisposed_ms = None
        segment_index = 0
        lpReady = None  #might be callback function, if not using polling?
        pParameter = None
        self.status["runBlock"] = ps.ps5000aRunBlock(
            self.chandle, self.preTriggerSamples, self.postTriggerSamples,
            self.timebase, time_indisposed_ms, segment_index, lpReady,
            pParameter)
        assert_pico_ok(self.status["runBlock"])
Пример #6
0
def readVoltage():

    maxSamples = 10000
    preTriggerSamples = 100
    status["runBlock"] = ps.ps5000aRunBlock(chandle, preTriggerSamples,
                                            maxSamples, timebase, None, 0,
                                            None, None)
    assert_pico_ok(status["runBlock"])

    ready = c_int16(0)
    check = c_int16(0)
    while ready.value == check.value:
        status["isReady"] = ps.ps5000aIsReady(chandle, byref(ready))

    bufferA = (c_int16 * 2)()
    source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_A"]
    downSampleTatioMode = ps.PS5000A_RATIO_MODE["PS5000A_RATIO_MODE_AVERAGE"]
    status["setDataBufferA"] = ps.ps5000aSetDataBuffer(chandle, source,
                                                       byref(bufferA), 2, 0,
                                                       downSampleTatioMode)
    assert_pico_ok(status["setDataBufferA"])

    maxDownSampleRatio = c_uint32()
    status["dwonSample"] = ps.ps5000aGetMaxDownSampleRatio(
        chandle, maxSamples, byref(maxDownSampleRatio), downSampleTatioMode, 0)
    assert_pico_ok(status["dwonSample"])

    overflow = c_int16()
    cmaxSamples = c_uint32(maxSamples)
    status["getValues"] = ps.ps5000aGetValues(chandle, 0, byref(cmaxSamples),
                                              maxDownSampleRatio,
                                              downSampleTatioMode, 0,
                                              byref(overflow))
    assert_pico_ok(status["getValues"])

    maxADC = c_int16()
    status["maximumValue"] = ps.ps5000aMaximumValue(chandle, byref(maxADC))
    assert_pico_ok(status["maximumValue"])

    adc2mVChA = adc2mV(bufferA, chARange, maxADC)
    avg = adc2mVChA[0]
    return avg
    def start_run(self,
                  num_pre_samples,
                  num_post_samples,
                  timebase=4,
                  num_captures=1,
                  callback=None):
        """Start a run in (rapid) block mode.

        Start a data collection run in 'rapid block mode' and collect a number
        of captures. Unlike the :method:`measure` and
        :method:`measure_adc_values`, which handle all details for you, this
        method returns immediately, while the device captures the requested
        data. Make sure that you *first* run :method:`set_up_buffers` to set up
        the device's memory buffers. You can supply a C-style callback to be
        notified when the device is ready, or call :method:`wait_for_data:.
        When the data is ready, call :method:`get_data` or
        :method:`get_adc_data`. When done measuring data, make sure to call
        :method:`stop`.

        :param num_pre_samples: number of samples before the trigger
        :param num_post_samples: number of samples after the trigger
        :param timebase: timebase setting (see programmers guide for reference)
        :param num_captures: number of captures to take

        :returns: data
        """
        # save samples and captures for reference
        self._num_samples = num_pre_samples + num_post_samples
        self._timebase = timebase
        self._num_captures = num_captures

        if callback is None:
            callback = self._callback
        self.data_is_ready.clear()

        assert_pico_ok(ps.ps5000aSetNoOfCaptures(self._handle, num_captures))
        assert_pico_ok(
            ps.ps5000aRunBlock(self._handle, num_pre_samples, num_post_samples,
                               timebase, None, 0, callback, None))
Пример #8
0
 def get_block(self, Samples, SamplesBeforeTrigger, Timebase):
     # Run block capture
     # handle = self.chandle
     # number of pre-trigger samples = preTriggerSamples
     # number of post-trigger samples = PostTriggerSamples
     # timebase = 8 = 80 ns (see Programmer's guide for mre information on timebases)
     # time indisposed ms = None (not needed in the example)
     # segment index = 0
     # lpReady = None (using ps5000aIsReady rather than ps5000aBlockReady)
     # pParameter = None
     '''
     starttime = time()
     self.status["runBlock"] = ps.ps5000aRunStreaming(self.chandle, ctypes.byref(ctypes.c_int32(100)), 2, SamplesBeforeTrigger, Samples-SamplesBeforeTrigger, 1, 0, 1, 0) #self.status["runBlock"] = ps.ps5000aRunBlock(self.chandle, SamplesBeforeTrigger, Samples-SamplesBeforeTrigger, Timebase, None, 0, None, None) # trigger['PreSamp'], trigger['PostSamp']
     print('Time to send a runblock command is: ', time() - starttime, ' s')
     self.status["isReady"] = ps.ps5000aGetStreamingLatestValues(self.chandle, ps.ps5000aStreamingReady(self.chandle, Samples, 0, ), ctypes.byref(ctypes.c_void_p())
     '''
     self.status["runBlock"] = ps.ps5000aRunBlock(self.chandle, SamplesBeforeTrigger, Samples-SamplesBeforeTrigger, Timebase, None, 0, None, None) # trigger['PreSamp'], trigger['PostSamp']
     # Check for data collection to finish using ps5000aIsReady
     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))  # As soon as the sampling is done ready is set to 1
Пример #9
0
    def runTestBlock(self):
        self.status["runBlock"] = ps.ps5000aRunBlock(self.chandle,
                                                     self.preTriggerSamples,
                                                     self.postTriggerSamples,
                                                     self.timebase, None, 0,
                                                     None, None)
        assert_pico_ok(self.status["runBlock"])

        # Check for data collection to finish using ps5000aIsReady
        self.ready = ctypes.c_int16(0)
        self.check = ctypes.c_int16(0)
        while self.ready.value == self.check.value:
            self.status["isReady"] = ps.ps5000aIsReady(
                self.chandle, ctypes.byref(self.ready))
        # create overflow loaction

        # Retried data from scope to buffers assigned above
        # handle = chandle
        # start index = 0
        # pointer to number of samples = ctypes.byref(cmaxSamples)
        # downsample ratio = 0
        # downsample ratio mode = PS5000A_RATIO_MODE_NONE
        # pointer to overflow = ctypes.byref(overflow))
        self.status["getValues"] = ps.ps5000aGetValues(
            self.chandle, 0, ctypes.byref(self.cmaxSamples), 0, 0, 0,
            ctypes.byref(self.overflow))
        assert_pico_ok(self.status["getValues"])
        for index in range(0, self.numberOfChannels):
            self.returnData[index, :] = adc2mV(self.bufferMax[index],
                                               self.chRange[index],
                                               self.maxADC)

        self.time = np.linspace(0, (self.cmaxSamples.value) *
                                self.timeIntervalns.value,
                                self.cmaxSamples.value)
        return self.returnData, self.time
Пример #10
0
print ("Starting data collection...")

# Starts the block capture
# handle = chandle
# Number of preTriggerSamples
# Number of postTriggerSamples
# Timebase = 1252 = 10000 ns (see Programmer's guide for more information on timebases)
# time indisposed ms = None (This is not needed within the example)
# Segment index = 0
# LpRead = None
# pParameter = None
status["runblock"] = ps.ps5000aRunBlock(chandle,
                                        preTriggerSamples,
                                        postTriggerSamples,
                                        timebase,
                                        None,
                                        0,
                                        None,
                                        None)
assert_pico_ok(status["runblock"])

# Creates a overflow location for data
overflow = (ctypes.c_int16 * 10)()
# Creates converted types totalSamples
cTotalSamples = ctypes.c_int32(totalSamples)

# Checks data collection to finish the capture
ready = ctypes.c_int16(0)
check = ctypes.c_int16(0)

while ready.value == check.value:
Пример #11
0
def autoRange():
    global chARange
    maxSamples = 100
    while chARange < max(psVoltageRange.keys()):
        overrange = False
        preTriggerSamples = 100
        status["runBlock"] = ps.ps5000aRunBlock(chandle, preTriggerSamples,
                                                maxSamples, timebase, None, 0,
                                                None, None)
        assert_pico_ok(status["runBlock"])

        ready = c_int16(0)
        check = c_int16(0)
        while ready.value == check.value:
            status["isReady"] = ps.ps5000aIsReady(chandle, byref(ready))

        bufferA = (c_int16 * maxSamples)()
        source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_A"]
        status["setDataBufferA"] = ps.ps5000aSetDataBuffer(
            chandle, source, byref(bufferA), maxSamples, 0, 0)
        assert_pico_ok(status["setDataBufferA"])

        overflow = c_int16()
        cmaxSamples = c_uint32(maxSamples)
        status["getValues"] = ps.ps5000aGetValues(chandle, 0,
                                                  byref(cmaxSamples), 0, 0, 0,
                                                  byref(overflow))
        assert_pico_ok(status["getValues"])

        maxADC = c_int16()
        status["maximumValue"] = ps.ps5000aMaximumValue(chandle, byref(maxADC))
        assert_pico_ok(status["maximumValue"])

        if max(map(abs, adc2mV(bufferA, chARange,
                               maxADC))) == psVoltageRange[chARange]:
            overrange = True

        if overrange:
            chARange += 1
            status["setChA"] = ps.ps5000aSetChannel(
                chandle, channel, 1, coupling_type, chARange,
                0)  #enabled = 1, analogue offset = 0 V
            assert_pico_ok(status["setChA"])
        else:
            break

    while chARange > min(psVoltageRange.keys()):
        toosmall = False
        status["setChA"] = ps.ps5000aSetChannel(
            chandle, channel, 1, coupling_type, chARange - 1,
            0)  #enabled = 1, analogue offset = 0 V
        assert_pico_ok(status["setChA"])
        preTriggerSamples = 100
        status["runBlock"] = ps.ps5000aRunBlock(chandle, preTriggerSamples,
                                                maxSamples, timebase, None, 0,
                                                None, None)
        assert_pico_ok(status["runBlock"])

        ready = c_int16(0)
        check = c_int16(0)
        while ready.value == check.value:
            status["isReady"] = ps.ps5000aIsReady(chandle, byref(ready))

        bufferA = (c_int16 * maxSamples)()
        source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_A"]
        status["setDataBufferA"] = ps.ps5000aSetDataBuffer(
            chandle, source, byref(bufferA), maxSamples, 0, 0)
        assert_pico_ok(status["setDataBufferA"])

        overflow = c_int16()
        cmaxSamples = c_uint32(maxSamples)
        status["getValues"] = ps.ps5000aGetValues(chandle, 0,
                                                  byref(cmaxSamples), 0, 0, 0,
                                                  byref(overflow))
        assert_pico_ok(status["getValues"])

        maxADC = c_int16()
        status["maximumValue"] = ps.ps5000aMaximumValue(chandle, byref(maxADC))
        assert_pico_ok(status["maximumValue"])

        if max(map(abs, adc2mV(bufferA, chARange,
                               maxADC))) < psVoltageRange[chARange]:
            toosmall = True
        if toosmall:
            chARange = chARange - 1
        else:
            status["setChA"] = ps.ps5000aSetChannel(
                chandle, channel, 1, coupling_type, chARange,
                0)  #enabled = 1, analogue offset = 0 V
            assert_pico_ok(status["setChA"])
            break
Пример #12
0
def readAmplitude(binWidth, spectrumRange, checkRange, nmbOfAvg):

    spectrumRange = spectrumRange * 2
    requiredMeasureTime = 2 / binWidth
    requiredSamplingInterval = 1 / spectrumRange
    timebase = floor(requiredSamplingInterval * 62500000 + 3)
    timeInternalns = c_float()
    returnedMaxSamples = c_int32()
    maxSamples = ceil(spectrumRange / binWidth)
    status["getTimebase2"] = ps.ps5000aGetTimebase2(chandle, timebase,
                                                    maxSamples,
                                                    byref(timeInternalns),
                                                    byref(returnedMaxSamples),
                                                    0)
    assert_pico_ok(status["getTimebase2"])
    assert timeInternalns.value < requiredSamplingInterval * 1e9

    for i in range(nmbOfAvg):
        preTriggerSamples = 100
        status["runBlock"] = ps.ps5000aRunBlock(chandle, preTriggerSamples,
                                                maxSamples, timebase, None, 0,
                                                None, None)
        assert_pico_ok(status["runBlock"])

        ready = c_int16(0)
        check = c_int16(0)
        while ready.value == check.value:
            status["isReady"] = ps.ps5000aIsReady(chandle, byref(ready))

        bufferA = (c_int16 * maxSamples)()
        source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_A"]
        status["setDataBufferA"] = ps.ps5000aSetDataBuffer(
            chandle, source, byref(bufferA), maxSamples, 0, 0)
        assert_pico_ok(status["setDataBufferA"])

        overflow = c_int16()
        cmaxSamples = c_uint32(maxSamples)
        status["getValues"] = ps.ps5000aGetValues(chandle, 0,
                                                  byref(cmaxSamples), 0, 0, 0,
                                                  byref(overflow))
        assert_pico_ok(status["getValues"])

        maxADC = c_int16()
        status["maximumValue"] = ps.ps5000aMaximumValue(chandle, byref(maxADC))
        assert_pico_ok(status["maximumValue"])

        timeSignal = adc2mV(bufferA, chARange, maxADC)
        f, newPSD = signal.periodogram(timeSignal,
                                       1 / (timeInternalns.value / 1e9),
                                       window=signal.get_window(
                                           'blackman', len(timeSignal)))
        startIndex = f.searchsorted(checkRange[0]) - 1
        endIndex = f.searchsorted(checkRange[1]) + 1
        f = f[startIndex:endIndex]
        newPSD = newPSD[startIndex:endIndex]
        if i == 0:
            PSD = np.array(newPSD)
        else:
            PSD = PSD + newPSD

    PSD = PSD / nmbOfAvg

    PSD = 10 * np.log10(10 * PSD)
    PSD = PSD - PSD.mean()
    Index, _ = find_peaks(PSD, distance=PSD.size)
    return PSD[Index]
Пример #13
0
    def getTimeSignal(self,
                      channel=None,
                      check=True,
                      trigger=None,
                      triggerThreshold=0,
                      reportOverflow=True):
        # get all channel data but only return required
        if check:
            nMaxSamples = c_long()
            ps.ps5000aMemorySegments(self.chandle, 1, byref(nMaxSamples))
            nMaxSamples.value = math.floor(nMaxSamples.value /
                                           self.nEnabledChannels())
            if self.maxSamples > nMaxSamples.value:
                raise Exception("samples will be larger than memory")

            self.status["getTimebase2"] = ps.ps5000aGetTimebase2(self.chandle, \
                self.timebase, self.maxSamples, byref(self.timeInternalns),\
                None, 0)
            assert_pico_ok(self.status["getTimebase2"])

        if trigger is not None:
            source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_{trigCh}".format(
                trigCh=trigger)]
            self.status["trigger"] = ps.ps5000aSetSimpleTrigger(
                self.chandle, 1, source, triggerThreshold, 2, 0, 0)
            assert_pico_ok(self.status["trigger"])
        else:
            source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_{trigCh}".format(
                trigCh='D')]
            self.status["trigger"] = ps.ps5000aSetSimpleTrigger(
                self.chandle, 0, source, triggerThreshold, 2, 0, 0)
            assert_pico_ok(self.status["trigger"])

        preTriggerSamples = 0
        self.status["runBlock"] = ps.ps5000aRunBlock(self.chandle, \
            preTriggerSamples, self.maxSamples, self.timebase, None, 0, None, None)
        assert_pico_ok(self.status["runBlock"])

        ready = c_int16(0)
        check = c_int16(0)
        while ready.value == check.value:
            self.status["isReady"] = ps.ps5000aIsReady(self.chandle,
                                                       byref(ready))
            time.sleep(1e-3)

        for key in self.chs:
            if self.chs[key].enabled:
                self.chs[key].buffer = (c_int16 * self.maxSamples)()
                self.status["setDataBuffer"+key] = ps.ps5000aSetDataBuffer(self.chandle, \
                    self.chs[key].channel, byref(self.chs[key].buffer), self.maxSamples, 0, 0)
                assert_pico_ok(self.status["setDataBuffer" + key])

        overflow = c_int16()
        cmaxSamples = c_uint32(self.maxSamples)
        self.status["getValues"] = ps.ps5000aGetValues(self.chandle, 0 , \
        byref(cmaxSamples), 0, 0, 0, byref(overflow))
        assert_pico_ok(self.status["getValues"])

        overflow = '{0:04b}'.format(overflow.value)
        chOF = [bool(int(i)) for i in overflow]
        self.chs['A'].overflow = chOF[-1]
        self.chs['B'].overflow = chOF[-2]
        self.chs['C'].overflow = chOF[-3]
        self.chs['D'].overflow = chOF[-4]
        channels = ['A', 'B', 'C', 'D']
        if reportOverflow:
            for i in range(4):
                if chOF[-(i + 1)]:
                    print('channel {0} overflow'.format(channels[i]))

        maxADC = c_int16()
        self.status["maximumValue"] = ps.ps5000aMaximumValue(
            self.chandle, byref(maxADC))
        assert_pico_ok(self.status["maximumValue"])

        for key in self.chs:
            if self.chs[key].enabled:
                self.chs[key].timeSignal = (np.array(self.chs[key].buffer) / maxADC.value) * \
                    self.psVoltageRange[self.chs[key].range] * 1e-3

        if channel is not None:
            return self.chs[channel].timeSignal
Пример #14
0
class BuildModel_M3_Single(object):
    if __name__ == "__main__":
        # Serial port communication: look this up in 'device manager'
        port = '/dev/ttyUSB0'  # Serial port
        step = 1000
        # Number of traces
        N = 5000 * 23
        # Number of samples
        samples = 1000
        # 2ns, sampling rate= 500MSa/s(p22 2.7 Timebase)
        timebase = 1
        # post-trigger or before-trigger
        post_trigger = True
        # trigger threshold(mV)
        threshold = 2000
        # trigger direction
        posedge_trigger = True
        # vertical offset
        vertical_offset = 0.1
        #delay
        delay = 0
        plain_len = 32  # byte length of the plaintext
        cipher_len = 32  # byte length of the ciphertext

        # Intiliazed random generator
        random.seed()
        # Open serial port
        ser = serial.Serial(port)
        # Wait for 200ms
        time.sleep(0.2)
        if (post_trigger):
            preTriggerSamples = 0
            postTriggerSamples = samples
        else:
            preTriggerSamples = samples
            postTriggerSamples = 0

            # Connect the scope
        chandle = ctypes.c_int16()
        status = ps.ps5000aOpenUnit(
            ctypes.byref(chandle), None,
            ps.PS5000A_DEVICE_RESOLUTION["PS5000A_DR_8BIT"])
        if status != PICO_STATUS['PICO_OK']:
            raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                PICO_STATUS_LOOKUP[status]))
        # Set up channel A
        status = ps.ps5000aSetChannel(chandle, ps.PICO_CHANNEL["A"], 1,
                                      ps.PICO_COUPLING['DC'],
                                      ps.PS5000A_RANGE["PS5000A_1V"],
                                      vertical_offset)
        if status != PICO_STATUS['PICO_OK']:
            raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                PICO_STATUS_LOOKUP[status]))
        # Set up channel B
        status = ps.ps5000aSetChannel(chandle, ps.PICO_CHANNEL["B"], 1,
                                      ps.PICO_COUPLING['DC'],
                                      ps.PS5000A_RANGE["PS5000A_5V"], 0)
        if status != PICO_STATUS['PICO_OK']:
            raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                PICO_STATUS_LOOKUP[status]))
        # Set up trigger
        if (posedge_trigger):
            status = ps.ps5000aSetSimpleTrigger(
                chandle, 1, ps.PICO_CHANNEL["B"],
                mV2adc(threshold, ps.PS5000A_RANGE["PS5000A_5V"],
                       ctypes.c_int16(32512)),
                ps.PS5000A_THRESHOLD_DIRECTION["PS5000A_RISING"], delay, 0)
        else:
            status = ps.ps5000aSetSimpleTrigger(
                chandle, 1, ps.PICO_CHANNEL["B"],
                mV2adc(threshold, ps.PS5000A_RANGE["PS5000A_5V"],
                       ctypes.c_int16(32512)),
                ps.PS5000A_THRESHOLD_DIRECTION["PS5000A_FALLING"], delay, 0)
        if status != PICO_STATUS['PICO_OK']:
            raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                PICO_STATUS_LOOKUP[status]))

        # Create buffers ready for assigning pointers for data collection
        Databuffer = (ctypes.c_int16 * samples)()
        status = ps.ps5000aSetDataBuffers(chandle, 0, ctypes.byref(Databuffer),
                                          None, samples, 0, 0)
        if status != PICO_STATUS['PICO_OK']:
            raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                PICO_STATUS_LOOKUP[status]))

        trs = TRS_TraceSet.TRS_TraceSet("BuildModel_M3_Single_1000Samples.trs")
        trs.write_header(N, samples, True, plain_len + cipher_len, 2E-9,
                         1 / 65536)
        for i in range(0, N):
            # Generate plaintext & mask
            plaintext = bytearray(
                [secrets.randbits(8) for j in range(0, plain_len)])
            plaintext[28] = int(i / 5000) + 1
            # Start
            status = ps.ps5000aRunBlock(chandle, preTriggerSamples,
                                        postTriggerSamples, timebase, None, 0,
                                        None, None)
            if status != PICO_STATUS['PICO_OK']:
                raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                    PICO_STATUS_LOOKUP[status]))
            # Send plaintext
            ser.write(plaintext)
            # Read out ciphertext
            ciphertext = bytearray(ser.read(cipher_len))
            # Check for data collection to finish using ps5000aIsReady
            ready = ctypes.c_int16(0)
            check = ctypes.c_int16(0)
            while ready.value == check.value:
                status = ps.ps5000aIsReady(chandle, ctypes.byref(ready))
            # Create overflow location
            overflow = ctypes.c_int16()
            # create converted type totalSamples
            cTotalSamples = ctypes.c_int32(samples)
            # Retried data from scope to buffers assigned above
            status = ps.ps5000aGetValues(chandle, 0,
                                         ctypes.byref(cTotalSamples), 0, 0, 0,
                                         ctypes.byref(overflow))
            if status != PICO_STATUS['PICO_OK']:
                raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                    PICO_STATUS_LOOKUP[status]))
            if (overflow.value != 0):
                print("overflow!")
            # Write trace
            trs.write_trace(plaintext, ciphertext, np.array(Databuffer), True)
            # print to screen
            if i % step == 0 and i > 0:
                print("i=" + str(i))
                print("Instr=" + str(plaintext[28]))
                print("plain=")
                PrintHexData(plaintext)
                print("cipher=")
                PrintHexData(ciphertext)
        trs.close()