Measurement Computing   Easy to Use | Easy to Integrate | Easy to Support catalog banner

Linux Python USB-CTR04 Counting Example

Expand / Collapse

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
        # 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
        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...')

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

        #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,
        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


            while True:
                    status, transfer_status = ctr_device.get_scan_status()
                    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),

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

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

    except RuntimeError as error:
        print('\n', error)

        if daq_device:
            if status == ScanStatus.RUNNING:
            if daq_device.is_connected():

def reset_cursor():
    """Reset the cursor in the terminal window."""

if __name__ == '__main__':

Rate this Article:

Attachments (7.76 KB, 233 views)

Add Your Comments

For comments email [email protected].

Article ID: 50853

Last Modified:10/4/2021 1:29:49 PM

Article has been viewed 2,366 times.