Exemple #1
0
    def getChannelValues(self, channel):
        _channel = ps.PS5000A_CHANNEL['PS5000A_CHANNEL_' + channel.upper()]
        buf = (ctypes.c_int16 * self.noSamples)()
        self.status['setBuffer_' + channel.upper()] = ps.ps5000aSetDataBuffer(
            self.chandle, _channel, ctypes.byref(buf), self.noSamples, 0, 0)
        assert_pico_ok(self.status['setBuffer_' + channel.upper()])

        overflow = ctypes.c_int16()
        cnoSamples = ctypes.c_int32(self.noSamples)

        self.status['getChannelValues' +
                    channel.upper()] = ps.ps5000aGetValues(
                        self.chandle, 0, ctypes.byref(cnoSamples), 0, 0, 0,
                        ctypes.byref(overflow))
        assert_pico_ok(self.status['getChannelValues' + channel.upper()])

        maxADC = ctypes.c_int16()
        self.status['maximumValue'] = ps.ps5000aMaximumValue(
            self.chandle, ctypes.byref(maxADC))
        assert_pico_ok(self.status['maximumValue'])
        _voltage_range = ps.PS5000A_RANGE[
            'PS5000A_' + self.channel_info[channel.upper()]['voltage_range']]
        buf_mV = adc2mV(buf, _voltage_range, maxADC)

        return buf_mV
 def read_data(self, cmaxSamples, overflow):
     # Retried data from scope to buffers assigned above (at the computer)
     # handle = self.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(cmaxSamples), 0, 0, 0, ctypes.byref(overflow))
    def retrieveCaptureData(self, channels):
        segment_index = 0
        ratio_move = 0  #PS5000A_RATIO_MODE_NONE
        if self.channela in channels:
            self.status["setDataBuffersA"] = ps.ps5000aSetDataBuffers(
                self.chandle, self.channela, ctypes.byref(self.bufferAMax),
                ctypes.byref(self.bufferAMin), self.totalSamples,
                segment_index, ratio_move)
            assert_pico_ok(self.status["setDataBuffersA"])
        if self.channelb in channels:
            self.status["setDataBuffersB"] = ps.ps5000aSetDataBuffers(
                self.chandle, self.channelb, ctypes.byref(self.bufferBMax),
                ctypes.byref(self.bufferBMin), self.totalSamples,
                segment_index, ratio_move)
            assert_pico_ok(self.status["setDataBuffersB"])
        if len(channels) < 1 or (self.channela not in channels
                                 and self.channelb not in channels):
            raise ValueError("Missing or unrecognised channel(s) requested")

        # create overflow loaction
        overflow = ctypes.c_int16()
        # create converted type maxSamples
        cmaxSamples = ctypes.c_int32(self.totalSamples)

        # Retried data from scope to buffers assigned above
        start_index = 0
        downsample_ratio = 0
        downsample_mode = 0  #PS5000A_RATIO_MODE_NONE
        segment_index = 0
        self.status["getValues"] = ps.ps5000aGetValues(
            self.chandle, start_index, ctypes.byref(cmaxSamples),
            downsample_ratio, downsample_mode, segment_index,
            ctypes.byref(overflow))
        assert_pico_ok(self.status["getValues"])

        # convert ADC counts data to mV
        adc2mVMaxChA, adc2mVMaxChB = None, None
        if self.channela in channels:
            adc2mVMaxChA = adc2mV(self.bufferAMax, self.channela_range,
                                  self.maxADC)
        if self.channelb in channels:
            adc2mVMaxChB = adc2mV(self.bufferBMax, self.channelb_range,
                                  self.maxADC)

        return [adc2mVMaxChA, adc2mVMaxChB]
Exemple #4
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
Exemple #5
0
    def flush(self):
        buf = (ctypes.c_int16 * self.noSamples)()
        overflow = ctypes.c_int16()
        cnoSamples = ctypes.c_int32(self.noSamples)
        for channel in self.channel_info.keys():
            if self.channel_info[channel]['enabled']:
                _channel = ps.PS5000A_CHANNEL['PS5000A_CHANNEL_' +
                                              channel.upper()]
                self.status['setBuffer_' +
                            channel.upper()] = ps.ps5000aSetDataBuffer(
                                self.chandle, _channel, ctypes.byref(buf),
                                self.noSamples, 0, 0)
                assert_pico_ok(self.status['setBuffer_' + channel.upper()])

                flush_done = False
                while (not flush_done):
                    status = ps.ps5000aGetValues(self.chandle, 0,
                                                 ctypes.byref(cnoSamples), 0,
                                                 0, 0, ctypes.byref(overflow))
                    flush_done = status == PICO_STATUS[
                        'PICO_NO_SAMPLES_AVAILABLE']
    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
Exemple #7
0
# Checks data collection to finish the capture
ready = ctypes.c_int16(0)
check = ctypes.c_int16(0)

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

# Handle = chandle
# start index = 0
# noOfSamples = ctypes.byref(cTotalSamples)
# DownSampleRatio = 1
# DownSampleRatioMode = 0
# SegmentIndex = 0
# Overflow = ctypes.byref(overflow)

status["GetValues"] = ps.ps5000aGetValues(chandle, 0, ctypes.byref(cTotalSamples), 1, 0, 0, ctypes.byref(overflow))
assert_pico_ok(status["GetValues"])

print ("Data collection complete.")

# Obtain binary for Digital Port 0
# The tuple returned contains the channels in order (D7, D6, D5, ... D0).
bufferDPort0 = splitMSODataFast(cTotalSamples, bufferDPort0Max)

# Creates the time data
time = np.linspace(0, cTotalSamples.value * timeIntervalNs.value, cTotalSamples.value)

print ("Plotting data...")

# Plot the data from digital channels onto a graph
    def read(self,**kwargs):
        '''
        reads the scope results:
        arguments: none
        keyword arguments (defaults in scope.settings):
            source: the channel(s) to read. If no channels are given, all the channels are read,
            startIndex: the sample to start reading,
            down_sample_blocksize: the number of samples to group for the data reduction (see Channel()._setDataBuffers),
            reduction_mode: the reduction_mode for the data reduction (see Channel()._setDataBuffers),
        the results (in V) are stored in scope.channels['channe_name'].data_max and scope.channels['channe_name'].data_min
        a results structure is returned:
            time:                   the time (in s)
            channel+' (V)':          channel voltage (in V)
        ***in reduction_mode == aggregate, two keys are returned instead:***
            channel+'_{max} (V)':   channel max voltage (in V)
            channel+'_{min} (V)':   channel min voltage (in V)
        channel voltage (including max/min) are returned as noSamples*nSegments arrays 
        '''
        #handles default values
        settings = {}
        for key,current_value in self.settings.items():
            settings[key] = kwargs[key] if key in kwargs else current_value
        if not 'source' in kwargs:
            settings['source'] = self.enabledChannels
        for channel in settings['source']:
            self.channels[channel]._setDataBuffers(reduction_mode = settings['reduction_mode'])
        check_kwargs_scope(**kwargs)  
        # create overflow loaction
        overflow = (ctypes.c_int16 *self.trigger.settings['nSegments'])()
        # create converted type maxSamples
        cmaxSamples = ctypes.c_int32(self.settings['noSamples'])
        _ratio_mode = ratio_mode_index[settings['reduction_mode']]
        _segmentIndex = ctypes.c_uint32(self.settings['segmentIndex'])
        # 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))
        if self.trigger.settings['nSegments']==1:
            self.status["getValues"] = ps.ps5000aGetValues(self.chandle, settings['startIndex'], ctypes.byref(cmaxSamples), 
                                                           settings['down_sample_blocksize'], _ratio_mode, _segmentIndex, ctypes.byref(overflow))
            assert_pico_ok(self.status["getValues"])
        else:
            _fromSegmentIndex = self.trigger.settings['segmentIndex']
            _toSegmentIndex = _fromSegmentIndex+self.trigger.settings['nSegments']-1
            self.status["getValuesBulk"] = ps.ps5000aGetValuesBulk(self.chandle, ctypes.byref(cmaxSamples), 
                                                                   _fromSegmentIndex,_toSegmentIndex,
                                                           settings['down_sample_blocksize'], _ratio_mode,
                                                           ctypes.byref(overflow))
            assert_pico_ok(self.status["getValuesBulk"])
        self.settings = settings
        
        # Create time data
        time = np.linspace(0, (cmaxSamples.value) * self.settings['timeIntervalSeconds'], cmaxSamples.value)

        results = {'time (s)':time}
        # convert ADC counts data to mV
        for channel in settings['source']:
            if self.channels[channel].settings['reduction_mode']=='aggregate':
                results[channel+'_{max} (V)']=self.channels[channel].data_max
                results[channel+'_{min} (V)']=self.channels[channel].data_min
            else:
                results[channel+' (V)']=self.channels[channel].data_max
        return results
assert_pico_ok(status["setDataBuffersB"])

# create overflow loaction
overflow = ctypes.c_int16()
# create converted type maxSamples
cmaxSamples = ctypes.c_int32(maxSamples)

# 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))
status["getValues"] = ps.ps5000aGetValues(chandle, 0,
                                          ctypes.byref(cmaxSamples), 0, 0, 0,
                                          ctypes.byref(overflow))
assert_pico_ok(status["getValues"])

# convert ADC counts data to mV
adc2mVChAMax = adc2mV(bufferAMax, chARange, maxADC)
adc2mVChBMax = adc2mV(bufferBMax, chBRange, maxADC)

# Create time data
time = np.linspace(0, (cmaxSamples.value) * timeIntervalns.value,
                   cmaxSamples.value)

# plot data from channel A and B
plt.plot(time, adc2mVChAMax[:])
plt.plot(time, adc2mVChBMax[:])
plt.xlabel('Time (ns)')
Exemple #10
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
Exemple #11
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]
Exemple #12
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
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()