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, 
                   DaqInChanType, 
                   DaqInChanDescriptor,
                   DaqInScanFlag, 
                   CounterMeasurementType,
                   CounterMeasurementMode, 
                   CounterEdgeDetection,
                   CConfigScanFlag,
                   CounterTickSize, 
                   CounterDebounceMode, 
                   CounterDebounceTime,
                   CounterRegisterType,
                   Range, 
                   ScanOption, 
                   ScanStatus,
                   TmrIdleState, 
                   PulseOutOption, 
                   DigitalDirection, 
                   DigitalPortType,
                   get_daq_device_inventory, 
                   DaqDevice, 
                   create_float_buffer)



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

    try:
        # 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
                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])
        
        # 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 '
                               'subsystem') 

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

        # 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      
        ctr_device.c_config_scan(ctr0, 
                                 CounterMeasurementType.COUNT,
                                 mode,
                                 CounterEdgeDetection.RISING_EDGE,
                                 CounterTickSize.TICK_20PT83ns, #parameter ignored
                                 CounterDebounceMode.NONE,  
                                 CounterDebounceTime.DEBOUNCE_0ns,
                                 CConfigScanFlag.DEFAULT)
        #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
        ctr_device.c_config_scan(ctr1, 
                                 CounterMeasurementType.COUNT,
                                 CounterMeasurementMode.GATING_ON,
                                 CounterEdgeDetection.RISING_EDGE,
                                 CounterTickSize.TICK_20PT83ns, #parameter ignored
                                 CounterDebounceMode.TRIGGER_AFTER_STABLE,
                                 CounterDebounceTime.DEBOUNCE_500ns,
                                 CConfigScanFlag.DEFAULT)

        #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,
                                                     PulseOutOption.DEFAULT)
        
        # 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)

        system('clear')

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

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

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

                    sleep(0.1)
                except (ValueError, NameError, SyntaxError):
                    break
        except KeyboardInterrupt:
            pass
        #stop time
        tmr_device.pulse_out_stop(timer_number)
        #set counter #1 gate low to prevent counting
        dio_device.d_bit_out(DigitalPortType.AUXPORT, 0, 0)

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

    finally:
        if daq_device:
            # Stop the scan if it is still running.
            if status == ScanStatus.RUNNING:
                daqi_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')


def clear_eol():
    """Clear all characters to the end of the line."""
    stdout.write('\x1b[2K')


if __name__ == '__main__':
    main()





Rate this Article:

Attachments


daq_in_scan_ctr04.py daq_in_scan_ctr04.py (10.10 KB, 22 views)

Add Your Comments


For comments email TechSupport@mccdaq.com.

Details
Article ID: 50854

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

Article has been viewed 168 times.

Options