Example #1
0
def main():
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser(description='Process some integers.')

    p201 = P201Card()
    try:
        go(p201)
    except KeyboardInterrupt:
        print("\nCtrl-C: Bailing out")
    finally:
        clean_up(p201)
Example #2
0
def main():

    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument(
        '--log-level',
        type=str,
        default='info',
        help='log level (debug, info, warning, error) [default: info]')
    parser.add_argument('--counter',
                        type=int,
                        help='counter number',
                        default=1)
    parser.add_argument('--value',
                        type=int,
                        default=1000 * 1000,
                        help='count until value')

    args = parser.parse_args()

    logging.basicConfig(
        level=getattr(logging, args.log_level.upper()),
        format="%(asctime)s %(levelname)s %(name)s: %(message)s")

    counter = args.counter
    value = args.value

    p201 = P201Card()
    p201.request_exclusive_access()
    p201.disable_interrupts()
    p201.reset()
    p201.software_reset()
    p201.enable_interrupts(100)

    poll = select.epoll()
    poll.register(p201, select.EPOLLIN | select.EPOLLHUP | select.EPOLLERR)
    poll.register(sys.stdin, select.EPOLLIN)

    stop = False
    loop = 0
    out("Ready to accept commands (start, stop, Ctrl-D to abort!\n> ")
    try:
        while not stop:
            loop += 1
            events = poll.poll()
            for fd, event in events:
                if fd == sys.stdin.fileno():
                    handle = handle_cmd
                elif fd == p201.fileno():
                    handle = handle_card
                result, cont = handle(p201, counter, value, fd, event)
                if result:
                    stop = True
                    break
                else:
                    if not cont:
                        out("> ")

    except KeyboardInterrupt:
        print("\rCtrl-C pressed. Bailing out!")
    finally:
        print("Clean up!")
        p201.disable_interrupts()
        p201.reset()
        p201.software_reset()

    stats = numpy.array(p201._interrupt_delay_stats)
    avg = numpy.average(stats)
    mi, ma = numpy.min(stats), numpy.max(stats)
    print("Interrupt delay stats:")
    print("nb samples: %d, avg: %.3f us, min: %.3f us, max: %.3f us" % \
              (len(stats), avg, mi, ma))
Example #3
0
def main():
    #logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('--counter',
                        type=int,
                        help='counter number',
                        default=1)
    parser.add_argument('--value',
                        type=int,
                        default=10000 * 1000,
                        help='count until value')

    args = parser.parse_args()
    counter = args.counter
    value = args.value

    def out(msg):
        sys.stdout.write(msg)
        sys.stdout.flush()

    p201 = P201Card()
    p201.request_exclusive_access()
    p201.reset()
    p201.software_reset()

    # internal clock 100 Mhz
    p201.set_clock(Clock.CLK_100_MHz)

    # channel 10 output: counter 10 gate envelop
    p201.set_output_channels_level({counter: Level.TTL})

    # no 50 ohm adapter
    p201.set_input_channels_50ohm_adapter({})

    # channel 9 and 10: no filter, no polarity
    p201.set_output_channels_filter({})

    # channel N output: counter N gate envelop
    ct_N_gate = getattr(OutputSrc, "CT_%d_GATE" % counter)
    p201.set_output_channels_source({counter: ct_N_gate})

    # Internal clock to 1 Mhz [1us], Gate=1, Soft Start, HardStop on CMP,
    # Reset on Hard/SoftStop, Stop on HardStop
    hard_stop = getattr(CtHardStopSrc, "CT_{0}_EQ_CMP_{0}".format(counter))
    ct_config = CtConfig(clock_source=CtClockSrc.CLK_1_MHz,
                         gate_source=CtGateSrc.GATE_CMPT,
                         hard_start_source=CtHardStartSrc.SOFTWARE,
                         hard_stop_source=hard_stop,
                         reset_from_hard_soft_stop=True,
                         stop_from_hard_stop=True)
    p201.set_counter_config(counter, ct_config)

    # Latch N on Counter N HardStop
    p201.set_counters_latch_sources({counter: counter})

    # Counter N will count V/1000*1000 sec
    p201.set_counter_comparator_value(counter, value)

    started, start_count = False, 0
    while not started:
        # SoftStart on Counter N
        start_count += 1
        if start_count > 10:
            print("failed to start after 10 atempts")
            break
        p201.set_counters_software_start_stop({counter: True})
        status = p201.get_counters_status()
        started = status[counter].run

    if start_count > 1:
        logging.warning("took %d times to start", start_count)

    if started:
        print("Started!")
        import time
        while True:
            try:
                time.sleep(0.1)
                counter_value = p201.get_counter_value(counter)
                latch_value = p201.get_latch_value(counter)
                status = p201.get_counters_status()
                if not status[counter].run:
                    break
                msg = "\r%07d %07d" % (counter_value, latch_value)
                out(msg)
            except KeyboardInterrupt:
                p201.trigger_counters_software_latch((counter, ))
        print("\n%07d %07d" % (counter_value, latch_value))

    p201.disable_counters_software((counter, ))

    pprint.pprint(p201.get_counters_status())
    p201.relinquish_exclusive_access()

    return p201
Example #4
0
def main():
    def to_str(values, fmt="9d"):
        fmt = "%" + fmt
        return "[" + "".join([fmt % value for value in values]) + "]"

    def out(msg=""):
        sys.stdout.write(msg)
        sys.stdout.flush()

    channels = {
        "I0": 1,
        "V2F": 5,
        "SCA": 7,
        "SCA2": 8,
    }

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        '--log-level',
        type=str,
        default='info',
        help='log level (debug, info, warning, error) [default: info]')
    parser.add_argument('--nb-points',
                        type=int,
                        help='number of points',
                        default=10)
    parser.add_argument('--acq-time',
                        type=float,
                        default=1,
                        help='acquisition time')
    parser.add_argument('--nb-acq',
                        type=int,
                        default=1,
                        help='number of acquisitions')

    args = parser.parse_args()

    logging.basicConfig(
        level=getattr(logging, args.log_level.upper()),
        format="%(asctime)s %(levelname)s %(name)s: %(message)s")

    nb_points = args.nb_points
    acq_time = args.acq_time
    nb_acq = args.nb_acq

    device = P201Card()

    configure(device, channels)
    prepare_master(device, acq_time, nb_points)
    prepare_slaves(device, acq_time, nb_points, channels, accumulate=False)

    loop = 0
    try:
        while loop < nb_acq:
            print("Acquisition #{0}".format(loop))
            go(device, channels)
            loop += 1
    except KeyboardInterrupt:
        print("\rCtrl-C pressed. Bailing out!")
    except:
        sys.excepthook(*sys.exc_info())
    finally:
        print("Clean up!")
        device.disable_interrupts()
        device.reset()
        device.software_reset()
        device.relinquish_exclusive_access()
Example #5
0
def main():

    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument(
        '--log-level',
        type=str,
        default='info',
        help='log level (debug, info, warning, error) [default: info]')
    parser.add_argument('--counter',
                        type=int,
                        help='counter number',
                        default=1)
    parser.add_argument('--value',
                        type=int,
                        default=1000 * 1000,
                        help='count until value')
    parser.add_argument('--acq-len',
                        type=float,
                        default=10,
                        help='measurement length')
    parser.add_argument('--use-mmap',
                        type=int,
                        default=0,
                        help='use mmap(2) to read FIFO')

    args = parser.parse_args()

    counter = args.counter
    value = args.value
    acq_len = args.acq_len
    use_mmap = args.use_mmap

    if counter > 9:
        print("Can only use counters 1 to 9")
        sys.exit()

    logging.basicConfig(
        level=getattr(logging, args.log_level.upper()),
        format="%(asctime)s %(levelname)s %(name)s: %(message)s")

    p201 = P201Card()
    p201.request_exclusive_access()
    p201.disable_interrupts()
    p201.reset()
    p201.software_reset()
    p201.reset_FIFO_error_flags()
    p201.enable_interrupts(100)

    poll = select.epoll()
    poll.register(p201, select.EPOLLIN | select.EPOLLHUP | select.EPOLLERR)
    poll.register(sys.stdin, select.EPOLLIN)

    context = TestContext(card=p201,
                          counter=counter,
                          value=value,
                          acq_len=acq_len,
                          use_mmap=use_mmap)

    stop = False
    loop = 0
    out("Ready to accept commands (start, stop, Ctrl-D to abort!\n> ")
    try:
        while not stop:
            loop += 1
            events = poll.poll()
            for fd, event in events:
                if fd == sys.stdin.fileno():
                    handle = handle_cmd
                elif fd == p201.fileno():
                    handle = handle_card
                result, cont = handle(context, fd, event)
                if result:
                    stop = True
                    break
                else:
                    if not cont:
                        out("> ")

    except KeyboardInterrupt:
        print("\rCtrl-C pressed. Bailing out!")
    except:
        sys.excepthook(*sys.exc_info())
    finally:
        print("Clean up!")
        p201.disable_interrupts()
        p201.reset()
        p201.software_reset()
Example #6
0
def main():
    def to_str(values, fmt="9d"):
        fmt = "%" + fmt
        return "[" + "".join([fmt % value for value in values]) + "]"

    def out(msg=""):
        sys.stdout.write(msg)
        sys.stdout.flush()

    channels = {
        "I0": 3,
        "V2F": 5,
        "SCA": 6,
    }

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        '--log-level',
        type=str,
        default='info',
        help='log level (debug, info, warning, error) [default: info]')
    parser.add_argument('--nb-points',
                        type=int,
                        help='number of points',
                        default=10)
    parser.add_argument('--acq-time',
                        type=float,
                        default=1,
                        help='acquisition time')

    args = parser.parse_args()

    logging.basicConfig(
        level=getattr(logging, args.log_level.upper()),
        format="%(asctime)s %(levelname)s %(name)s: %(message)s")

    nb_points = args.nb_points
    acq_time = args.acq_time

    device = P201Card()

    configure(device, channels)

    prepare_master(device, acq_time, nb_points)
    prepare_slaves(device, acq_time, nb_points, channels)

    # start counting...
    nap = 0.1
    start_time = time.time()

    device.set_counters_software_start(channels.values() + [11, 12])

    while True:
        time.sleep(nap)
        counter_values = device.get_counters_values()
        latch_values = device.get_latches_values()
        status = device.get_counters_status()
        if not status[12].run:
            stop_time = time.time()
            break
        msg = "\r{0} {1}".format(to_str(counter_values), to_str(latch_values))
        out(msg)
    print("\n{0} {1}".format(to_str(counter_values), to_str(latch_values)))
    print("Took ~{0}s (err: {1}s)".format(stop_time - start_time, nap))
    pprint.pprint(device.get_counters_status())

    device.relinquish_exclusive_access()
Example #7
0
def main():

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--log-level', type=str, default='info',
                        help='log level (debug, info, warning, error) [default: info]')
    parser.add_argument('--value', type=int, default=10000,
                        help='count until value')
    parser.add_argument('--nb_counters', type=int, default=5,
                        help='use first n counters (max=6)')

    args = parser.parse_args()

    logging.basicConfig(level=getattr(logging, args.log_level.upper()),
                        format="%(asctime)s %(levelname)s %(name)s: %(message)s")
    
    value = args.value
    nb_counters = args.nb_counters

    if nb_counters > 6:
        print("Can only use first 6 counters")
        sys.exit(1)

    counters = tuple(range(1, nb_counters+1))

    card = P201Card()
    card.request_exclusive_access()
    card.reset()
    card.software_reset()

    # internal clock 100 Mhz
    card.set_clock(Clock.CLK_100_MHz)

    ct_config = CtConfig(clock_source=CtClockSrc.CLK_100_MHz,
                         gate_source=CtGateSrc.GATE_CMPT,
                         hard_start_source=CtHardStartSrc.SOFTWARE,
                         hard_stop_source=CtHardStopSrc.CT_1_EQ_CMP_1,
                         reset_from_hard_soft_stop=True,
                         stop_from_hard_stop=False)

    card.set_counter_config(1, ct_config)
    card.set_counter_comparator_value(1, value)

    for counter in counters[1:]:
        clock = getattr(CtClockSrc, "INC_CT_{0}_STOP".format(counter-1))
        hard_stop = getattr(CtHardStopSrc, "CT_{0}_EQ_CMP_{0}".format(counter))
        ct_config = CtConfig(clock_source=clock,
                             gate_source=CtGateSrc.GATE_CMPT,
                             hard_start_source=CtHardStartSrc.SOFTWARE,
                             hard_stop_source=hard_stop,
                             reset_from_hard_soft_stop=True,
                             stop_from_hard_stop=False)

        card.set_counter_config(counter, ct_config)
        v_ct = value/10**(counter-1)
        print(v_ct)
        card.set_counter_comparator_value(counter, v_ct)

    # Latch N on Counter N HardStop
    card.set_counters_latch_sources(dict([(counter, (counter,)) for counter in counters]))
    card.enable_counters_software(counters)

    # Start!
    card.set_counters_software_start(counters)

    print("Started!")
    while True:
        time.sleep(0.1)
        counters_values = card.get_counters_values()[:nb_counters]
        latches_values = card.get_latches_values()[:nb_counters]
        run = False
        for ct_status in card.get_counters_status().values():
            run = run or ct_status.run
        if not run:
            break
        out("\r{0} {1}".format(counters_values, latches_values))
    print("\n{0} {1}".format(counters_values.tolist(), latches_values.tolist()))

    pprint.pprint(card.get_counters_status())
    card.disable_counters_software((counter,))
    card.relinquish_exclusive_access()

    return card