Linux Python USB-CTR04 Counting Example


This is a product specific example that demonstrates how to use the USB-CTR04 or USB-CTR08 counter options. Counter 0 is configured for range counting and will count continuously from 0 to 9999. Gating and counter output is also demonstrated. The gate when high allows counting and the output will toggle when the count reaches 5000 and Counter 1 is used to count the transitions. The Timer output is used as a test signal. To use this example, wire TMR0 to C0IN; wire DIO0 to C0GT and wire C0O over to C1IN.

Python code file attached...

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

"""
UL call demonstrated:             CtrDevice.c_config_scan()

Purpose:                          configures counter to COUNT;
                                  enable gating on first counter;
                                  enable output on first counter;
                                  specify range counting with output;
                                  second counter merely counts output transitions
                                  from first counter

Demonstration:                    Displays the event counter data for
                                  the specified encoders

"""
from __future__ import print_function
from time import sleep
from os import system
from sys import stdout


from uldaq import (get_daq_device_inventory, InterfaceType, ScanStatus,
                   ScanOption, CInScanFlag, CounterMeasurementType,
                   CounterMeasurementMode, CounterEdgeDetection,
                   CounterTickSize, CounterDebounceMode, CounterDebounceTime,CounterRegisterType,
                   CConfigScanFlag, create_int_buffer, DaqDevice,
                   TmrIdleState, PulseOutOption, DigitalDirection, DigitalPortType)


def main():
    """Counter input scan with encoder example."""
    daq_device = None
    ctr_device = None
    status = ScanStatus.IDLE

    interface_type = InterfaceType.USB
    FirstChannel = 0
    SecondChannel = 1

    ChannelCount = 2
    sample_rate = 100.0  # Hz
    samples_per_channel = 100
    scan_options = ScanOption.CONTINUOUS
    scan_flags = CInScanFlag.DEFAULT + CInScanFlag.CTR32_BIT

    
    timer_number = 0
    frequency = 10000.0  # Hz
    duty_cycle = 0.5  # 50 percent
    pulse_count = 0  # Continuous 
    initial_delay = 0.0
    idle_state = TmrIdleState.LOW
    options = PulseOutOption.DEFAULT
 
    try:
        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(interface_type)
        number_of_devices = len(devices)
        if number_of_devices == 0:
            raise RuntimeError('Error: No DAQ devices found')
        
        descriptor_index = 99
        print('Found', number_of_devices, 'DAQ device(s):') 
        for i in range(number_of_devices):
            if devices[i].product_name == "USB-CTR04":
                descriptor_index = i
                break
  
        descriptor_index = int(descriptor_index)
        if descriptor_index not in range(number_of_devices):
            raise RuntimeError('Error: Invalid descriptor index')

        # Create the DAQ device from the descriptor at the specified index.
        daq_device = DaqDevice(devices[descriptor_index])

        # Establish a connection to the DAQ device.
        descriptor = daq_device.get_descriptor()
        print('\nConnecting to', descriptor.dev_string, '- please wait...')
        daq_device.connect(connection_code=0)

        # Get the CtrDevice object and verify that it is valid.
        ctr_device = daq_device.get_ctr_device()
             
        mode = CounterMeasurementMode.GATING_ON | CounterMeasurementMode.OUTPUT_ON | CounterMeasurementMode.RANGE_LIMIT_ON
        # configure counter 0 for encoder      
        ctr_device.c_config_scan(FirstChannel, 
                                 CounterMeasurementType.COUNT,
                                 mode,
                                 CounterEdgeDetection.RISING_EDGE,
                                 CounterTickSize.TICK_20PT83ns,
                                 CounterDebounceMode.NONE,
                                 CounterDebounceTime.DEBOUNCE_0ns,
                                 CConfigScanFlag.DEFAULT)
        #counter will count 0 to 9999
        ctr_device.c_load(FirstChannel,CounterRegisterType.MIN_LIMIT, 0)
        ctr_device.c_load(FirstChannel,CounterRegisterType.MAX_LIMIT, 9999)
        #counter output line will go high from  0 to 4999 then low from 5000 to 9999
        ctr_device.c_load(FirstChannel,CounterRegisterType.OUTPUT_VAL0, 0)      
        ctr_device.c_load(FirstChannel,CounterRegisterType.OUTPUT_VAL1, 4999)  
        
        # configure counter 1 for period to count output transitions from counter 0
        # wire C1IN to C0O
        ctr_device.c_config_scan(SecondChannel, 
                                 CounterMeasurementType.COUNT,
                                 CounterMeasurementMode.DEFAULT,
                                 CounterEdgeDetection.RISING_EDGE,
                                 CounterTickSize.TICK_20PT83ns,
                                 CounterDebounceMode.TRIGGER_AFTER_STABLE,
                                 CounterDebounceTime.DEBOUNCE_500ns,
                                 CConfigScanFlag.DEFAULT)

        #wire TMR0 to C0IN - this your test signal
        tmr_device = daq_device.get_tmr_device()
        (frequency,duty_cycle,initial_delay) = tmr_device.pulse_out_start(timer_number, frequency,
                                                     duty_cycle, pulse_count,
                                                     initial_delay, idle_state,
                                                     options)
        
        dio_device = daq_device.get_dio_device()
        dio_device.d_config_bit(DigitalPortType.AUXPORT, 0, DigitalDirection.OUTPUT)
        #wire DIO0 to C0GT - set bit high to enable counting
        dio_device.d_bit_out(DigitalPortType.AUXPORT, 0, 1)
        
        
        # Allocate a buffer to receive the data.
        data = create_int_buffer(ChannelCount, samples_per_channel)

        print('\n', descriptor.dev_string, ' ready', sep='')
        print('    Function demonstrated: ctr_device.c_config_scan()')
        print('    Counter(s):', FirstChannel, '-', SecondChannel)
        print('    Sample rate:', sample_rate, 'Hz')
 
        # Start the scan
        ctr_device.c_in_scan(FirstChannel, 
                             SecondChannel, 
                             samples_per_channel,
                             sample_rate, 
                             scan_options, 
                             scan_flags, 
                             data)
        sleep(0.5)

        system('clear')

        try:
            while True:
                try:
                    status, transfer_status = ctr_device.get_scan_status()
                    reset_cursor()
                    print('Please enter CTRL + C to terminate the process\n')
                    print('Active DAQ device: ', descriptor.dev_string, ' (',
                          descriptor.unique_id, ')\n', sep='')

                    print('actual scan rate = ', '{:.6f}'.format(sample_rate),
                          'Hz\n')

                    index = transfer_status.current_index
                    print('currentScanCount = ',
                          transfer_status.current_scan_count)
                    print('currentTotalCount = ',
                          transfer_status.current_total_count)
                    print('currentIndex = ', index, '\n')
                    
 
                    print('chan =', (0), ': ', '{:d}'.format(data[index]))
                    print('chan =', (1), ': ', '{:d}'.format(data[index+1]))


                    sleep(0.1)
                    if status != ScanStatus.RUNNING:
                        break
                except (ValueError, NameError, SyntaxError):
                    break
        except KeyboardInterrupt:
            pass

        tmr_device.pulse_out_stop(timer_number)
        
    except RuntimeError as error:
        print('\n', error)

    finally:
 
        if daq_device:
            if status == ScanStatus.RUNNING:
                ctr_device.scan_stop()
            if daq_device.is_connected():
                daq_device.disconnect()
            daq_device.release()

def reset_cursor():
    """Reset the cursor in the terminal window."""
    stdout.write('\033[1;1H')


if __name__ == '__main__':
    main()


Posted 10/4/2021 8:19:02 AM by Administrator
https://kb.mccdaq.com/KnowledgebaseArticle50853.aspx