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

Linux Python USB-CTR04 Read counter and digital port...

Expand / Collapse

Linux Python USB-CTR04 Read counter and digital port simultaneously

This is product specific example for the USB-CTR04. It will also work with the USB-CTR08 if you configure the device discovery to look for USB-CTR08 instead of USB-CTR04. This example is an extension of a previous article demonstrating the counting features of the USB-CTR04. However, this example uses the daq_in_scan function to read the counters and the digital port simultaneously. Not all devices support daq_in_scan. As of October 12th 2021, the USB-CTR04, USB-CTR08, USB-1808 and USB-1808X support daq_in_scan under UL for Linux.

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 low when the count reaches 9999 then back high from 0 to 9998. Counter 1 is used to count the output transitions from counter 0. The Timer output is used as a test signal. To see the counters in action, wire TMR0 to C0IN; wire DIO0 to C0GT and wire C0O over to C1IN

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

Wrapper call demonstrated:    daqi_device.daq_in_scan()

Purpose:                      Performs a continuous scan of the counter and digital port input subsystems

Demonstration:            Displays counter 0 & 1 and the digital port
                                data. Both subsystems are read simultaneously

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

from uldaq import (InterfaceType, 

def main():
    """Multi-subsystem simultaneous input scan example."""
    ctr0 = 0
    ctr1 = 1
    digital_port = 1
    daq_device = None
    daqi_device = None
    status = ScanStatus.IDLE
    #timer output (TMR0) used as signal source for ctr0 input
    timer_number = 0
    frequency = 2000.0  # Hz
    duty_cycle = 0.5  # 50 percent
    pulse_count = 0  # Continuous 
    initial_delay = 2.0
    idle_state = TmrIdleState.LOW

    samples_per_channel = 1000
    rate = 100.0
    options = ScanOption.DEFAULTIO | ScanOption.CONTINUOUS
    flags = DaqInScanFlag.DEFAULT

        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(InterfaceType.ANY)
        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):') 
        #search for USB-CTR04
        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])
        # Get the DaqiDevice object and verify that it is valid.
        daqi_device = daq_device.get_daqi_device()
        if daqi_device is None:
            raise RuntimeError('Error: The device does not support daq input '

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

        # wire DIO0 to C0GT - set bit high to enable counting        
        dio_device = daq_device.get_dio_device()
        # make half of the digital port output and the other half input
        dio_device.d_config_bit(DigitalPortType.AUXPORT, 0, DigitalDirection.OUTPUT)
        dio_device.d_config_bit(DigitalPortType.AUXPORT, 1, DigitalDirection.OUTPUT)
        dio_device.d_config_bit(DigitalPortType.AUXPORT, 2, DigitalDirection.OUTPUT)
        dio_device.d_config_bit(DigitalPortType.AUXPORT, 3, DigitalDirection.OUTPUT)
        dio_device.d_config_bit(DigitalPortType.AUXPORT, 4, DigitalDirection.INPUT)
        dio_device.d_config_bit(DigitalPortType.AUXPORT, 5, DigitalDirection.INPUT)
        dio_device.d_config_bit(DigitalPortType.AUXPORT, 6, DigitalDirection.INPUT)
        dio_device.d_config_bit(DigitalPortType.AUXPORT, 7, DigitalDirection.INPUT)
        # demonstrate how toset some lines on the digital port     
        dio_device.d_bit_out(DigitalPortType.AUXPORT, 0, 0)
        dio_device.d_bit_out(DigitalPortType.AUXPORT, 1, 1)
        dio_device.d_bit_out(DigitalPortType.AUXPORT, 2, 1)
        dio_device.d_bit_out(DigitalPortType.AUXPORT, 3, 1)

        # 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 COUNT mode      
                                 CounterTickSize.TICK_20PT83ns, #parameter ignored
        #counter will count 0 to 9999
        ctr_device.c_load(ctr0,CounterRegisterType.MIN_LIMIT, 0)
        ctr_device.c_load(ctr0,CounterRegisterType.MAX_LIMIT, 9999)
        #counter output line will go high from  0 to 9998 then low for one count
        ctr_device.c_load(ctr0,CounterRegisterType.OUTPUT_VAL0, 0)      
        ctr_device.c_load(ctr0,CounterRegisterType.OUTPUT_VAL1, 9999)  
        # configure counter 1 for period to count output transitions from counter 0
        # wire C1IN to C0O
                                 CounterTickSize.TICK_20PT83ns, #parameter ignored

        #get timer output object
        tmr_device = daq_device.get_tmr_device()
         #wire TMR0 to C0IN - this your test signal   
         #initial delay is set to 2 second.
        (frequency,duty_cycle,initial_delay) = tmr_device.pulse_out_start(timer_number, frequency,
                                                     duty_cycle, pulse_count,
                                                     initial_delay, idle_state,
        # Configure the input channels.
        channel_descriptors = []
        channel_descriptors.append( DaqInChanDescriptor(ctr0, DaqInChanType.CTR32, Range.BIP10VOLTS) )
        channel_descriptors.append( DaqInChanDescriptor(ctr1, DaqInChanType.CTR32, Range.BIP10VOLTS) ) 
        channel_descriptors.append( DaqInChanDescriptor(digital_port, DaqInChanType.DIGITAL, Range.BIP10VOLTS) )  

        number_of_scan_channels = len(channel_descriptors)
        # Allocate a buffer to receive the data
        data = create_float_buffer(number_of_scan_channels, samples_per_channel)


        # Start the acquisition.
        rate = daqi_device.daq_in_scan(channel_descriptors, 
        #wire DIO0 to C0GT - set bit high to enable counting
        dio_device.d_bit_out(DigitalPortType.AUXPORT, 0, 1)       
            while True:
                    # Get the status of the background operation
                    status, transfer_status = daqi_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(rate), 'Hz\n')

                    index = transfer_status.current_index
                    print('currentScanCount = ',
                    print('currentTotalCount = ',
                    print('currentIndex = ', index, '\n')

                    for i in range(number_of_scan_channels):
                        if (channel_descriptors[i].type
                              == DaqInChanType.DIGITAL):
                            print('(Di', channel_descriptors[i].channel, '): ',
                                  '{:d}'.format(int(data[index + i])))

                            print('(Ci', channel_descriptors[i].channel, '): ',
                                  '{:d}'.format(int(data[index + i])))

                except (ValueError, NameError, SyntaxError):
        except KeyboardInterrupt:
        #stop time
        #set counter #1 gate low to prevent counting
        dio_device.d_bit_out(DigitalPortType.AUXPORT, 0, 0)

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

        if daq_device:
            # Stop the scan if it is still running.
            if status == ScanStatus.RUNNING:
            if daq_device.is_connected():

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

def clear_eol():
    """Clear all characters to the end of the line."""

if __name__ == '__main__':

Rate this Article:

Attachments (10.10 KB, 7 views)

Add Your Comments

For comments email

Article ID: 50854

Last Modified:10/12/2021 1:04:01 PM

Article has been viewed 39 times.