Code Monkey home page Code Monkey logo

pydaqmx's Introduction

PyDAQmx

This package provides an interface in Python for the National Instruments DAQmx driver. It has been tested with different version of NI-DAQmx (starting from 8.01) and on Windows XP and Windows 7. It works with Python 2 (from 2.7) and Python 3.

Installation

To install this package:

  1. Install the NI-DAQmx driver.
  2. Run python setup.py install.

License

This software can be used under one of two licenses:

  1. The BSD license.
  2. Any other license, as long as it is obtained from the original author.

pydaqmx's People

Contributors

clade avatar davidbradway avatar eric-wieser avatar franciszekjuras avatar geraldebberinksaxion avatar mounte avatar petebachant avatar quigybo avatar stefand986 avatar timoml avatar untzag avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pydaqmx's Issues

Error in PyDAQmx setup command: use_2to3 is invalid

Hi there,
I have trouble in installing PyDAQmx with Python 3. When manually downloading the package and running python setup.py build from the terminal inside the package folder, I get the error that the command "use_2to3" is invalid.

Does anyone know how to fix this?

Task methods return None, so you can't get the size needed for a buffer.

The method versions in the Task class of the DAQmx functions don't return, which is generally OK, since PyDAQmx already takes care of errors or warnings, but that doesn't allow to get the size of the buffer for functions with data and bufferSize via catch_error_buffer.

import PyDAQmx
import ctypes
out=ctypes.create_string_buffer(256)
task=PyDAQmx.Task()
n=task.GetTaskName(None,0)
print(n)

None
n=PyDAQmx.GetTaskName(task.taskHandle,None,0)
print(n)

16

So both versions don't have the same behaviour, but if we give the buffer, both fill it properly:

n=task.GetTaskName(out,len(out))

print(n)
print(out.value.decode())

None
_unnamedTask<3>
n=PyDAQmx.DAQmxGetTaskName(task.taskHandle,out,len(out))

print(n)
print(out.value.decode())

0
_unnamedTask<3>

Therefore is more an issue of consistency, since if one changes code to the object oriented interface, it could be confusing to found that the behaviour changes. I don't know if a modification so the methods return the error code could generate issues downstream, but since right now they not return (return None) I don't really see any issues if that changes:

for function_name in task_function_list:
        name = function_name[5:] # remove the DAQmx in front of the name
        func = getattr(DAQmxFunctions, function_name)
        arg_names = function_dict[function_name]['arg_name']
        doc = 'T.%s(%s) -> error.' %(name, ', '.join(arg_names[1:]))
        cmd = """def {0}(self, {1}):
        "{3}"
        return {2}(self.taskHandle, {1})"""
        exec(cmd.format(name, ', '.join(arg_names[1:]), function_name, doc))    

instead of the current:

for function_name in task_function_list:
        name = function_name[5:] # remove the DAQmx in front of the name
        func = getattr(DAQmxFunctions, function_name)
        arg_names = function_dict[function_name]['arg_name']
        doc = 'T.%s(%s) -> error.' %(name, ', '.join(arg_names[1:]))
        cmd = """def {0}(self, {1}):
        "{3}"
        {2}(self.taskHandle, {1})"""
        exec(cmd.format(name, ', '.join(arg_names[1:]), function_name, doc))    

64 Bit Python?

Question: Is PyDAQmx compatible with 64-bit python (specifically 3.5)?

nameError: name 'PyDAQmx' is not defined

Hey there, i am currently trying to execute a simple example and i am getting the above mentioned error. The card i am trying to connect to is a PCI-DIO-96, i am running windows 7/ python 3.7.3 and using Pycharm. I have also installed the NI-DAQmx driver.

I found the example code here : https://pythonhosted.org/PyDAQmx/examples/digital_output.html

Code below:

from PyDAQmx import Task
import numpy as np

data = np.array([0,1,1,0,1,0,1,0], dtype=np.uint8)

task = Task()
task.CreateDOChan("/TestDevice/port0/line0:7","",PyDAQmx.DAQmx_Val_ChanForAllLines)
task.StartTask()
task.WriteDigitalLines(1,1,10.0,PyDAQmx.DAQmx_Val_GroupByChannel,data,None,None)
task.StopTask()

Error :

Traceback ( most recent call last):
File "C:/pycharm/prolog.py", line 11, in
task.CreateDOChan("/Dev2/port0/line0:7","",PyDAQmx,DAQmx_Val_ChanForAllLines)
NameError: name 'PyDAQmx' is not defined

Any idea what could be the problem?

Examples for digital output i/o

I was looking into the examples provided, and I did not find any to write digital outputs, read back the digital output written, and read digital input. Could you please share some code snippet to do the same.

Using PyDAQmx to read analog input with different Voltage Levels

Hello PyDAQmx experts, I am using PyDAQmx to read analog input with different voltage levels and meet some problem. I need to measure two channels (A and B) analog input voltage at the same time with PyDAQmx. The range of Channel A's input is (-0.1, 0.1). While Channel B is (-5.0, 5.0). We found the value from channel A is not accurate. BTW, the voltage channels set as below, is there someone meet the same issue? Thanks!

DAQmxCreateAIVoltageChan(taskHandle,"Dev1/ai16","",DAQmx_Val_Cfg_Default,-0.1,0.1,DAQmx_Val_Volts,NULL)
DAQmxCreateAIVoltageChan(taskHandle,"Dev1/ai24","",DAQmx_Val_Cfg_Default,-5.0,5.0,DAQmx_Val_Volts,NULL)

Remove DAQmx_ prefix from module attributes

That way instead of doing this and causing arbitrary namespace pollution:

from PyDAQmx import *

DAQmx_Some_Function(DAQmx_SomeConstant)

We can use the safer

import PyDAQmx

PyDAQmx.Some_Function(PyDAQmx.SomeConstant)

add tags for releases

It would be really handy to have tags for each release, rather than having to search through commits for the version numbers. This would also help with package management like MacPorts and homebrew.

Add use_2to3=True in setup.py

Adding the keyword argument use_2to3=True to setup in setup.py would simplify the installation of the package, as it is indeed already 2to3 compatible.

Unexpected exception following a Task example

Hi,

Following the Task example given at http://pythonhosted.org/PyDAQmx/usage.html#task-object, I am trying to do:

from PyDAQmx import *
analog_input = Task()
analog_input.CreateAIVoltageChan("Dev1/ai0", "", DAQmx_Val_Cfg_Default, -10.0, 10.0, DAQmx_Val_Volts, None)

Unfortunately, this results in an exception:

Traceback (most recent call last):
  File "C:\Users\sidney\Desktop\nidaq_error.py", line 4, in <module>
analog_input.CreateAIVoltageChan("Dev1/ai0", "", DAQmx_Val_Cfg_Default, -10.0, 10.0, DAQmx_Val_Volts, None)
  File "<string>", line 3, in CreateAIVoltageChan
  File "<string>", line 2, in function
  File "C:\WinPython-64bit-3.3.3.3\python-3.3.3.amd64\lib\site-packages\PyDAQmx\DAQmxFunctions.py", line 23, in mafunction
    error = f(*arg)
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type

What am I doing wrong?

I am using PyDAQmx on a 64-bit Python 3.3.3 in Windows 7. I installed PyDAQmx via "pip install PyDAQmx"; PyDAQmx.version says 1.2.5.2.

Please indicate status of Python 3 support on website

Hi,

A suggestion: it would be useful to have a brief statement concerning Python 3 support on the project's website.

The installation page currently says: "It has been reported that the package works on Python 3 using 2to3.". That suggests it may work, but making it work (and fixing problems) is not a priority. Is this correct? If so, it will be useful for potential users to be aware of this.

DAQmx configuration for Mac OS X

Hi ,
How can I update the DaqmxConfig.py for mac os x? I know the location of "NIDAQmxBase.h" file.

/Applications/National Instruments/NI-DAQmx Base/includes/NIDAQmxBase.h

When I run find_library('nidaqmxbase') , I got '/Library/Frameworks/nidaqmxbase.framework/nidaqmxbase'. Thanks,

Array type issue at import when using PyPy

Here is the traceback:
[PyPy 2.6.1 with MSC v.1500 32 bit] on win32
Type "help", "copyright", "credits" or "license" for more information.

import PyDAQmx
C:\Users\maco\virtualenvs\pypy\site-packages\numpy\linalg\lapack_lite.py:78: UserWarning: tuned lapack (openblas, atlas ...) not found, using lapack_lite
warnings.warn('tuned lapack (openblas, atlas ...) not found, using lapack_lite')
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\maco\virtualenvs\pypy\site-packages\PyDAQmx__init__.py", line 7, in
from DAQmxFunctions import *
File "C:\Users\maco\virtualenvs\pypy\site-packages\PyDAQmx\DAQmxFunctions.py", line 146, in
array_type(_type),2) for _type in type_list_array]
File "C:\Users\maco\virtualenvs\pypy\site-packages\PyDAQmx\DAQmxFunctions.py", line 111, in array_type
flags=('C_CONTIGUOUS','WRITEABLE'))
File "C:\Users\maco\virtualenvs\pypy\site-packages\numpy\ctypeslib.py", line 253, in ndpointer
elif isinstance(flags, flagsobj):
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

I'm using the Windows binary release of Pypy and installed numpy using: 'pip install git+https://bitbucket.org/pypy/numpy.git'. PyDAQmx was installed using 'pip install PyDAQmx' (v 1.3.1).

Releasing latest updates

Hi, could you release latest updates to PyPI? I need the updated ability to search for daq library files using Windows registry. Right now I need to install from source which is a bit problematic when specifying package as a dependency.

Handling functions that return non-zero gracefully

Hi Pierre,

I've been toying with PyDAQmx for a bit, thanks for this -- looks like a well-done wrapper.

One thing I bumped into was this:

In C, it is possible to use PyDAQmx.DAQmxGetSysDevNames() with a NULL char* argument to get the number of characters that need to be reserved for the characater buffer. This will return a positive value that does not indicate a warning.

However, PyDAQmx wraps the C functions inside the 'mafunction' wrapper that auto-throws an exception whenever a function returns non-zero. So it is impossible (or at least a bit cumbersome) to use this function in this way.

Is there an easy way around this?

The best I could think of now was to catch the exception and extract the "error", by hand, like this, which seems rather roundabout. In the process, I also need to silence stdout because mafunction() prints a WARNING message when warnings happen.

def GetSysDevNames():

    import sys, io

    # We know that PyDAQmx.DAQmxGetSysDevNames(None, 0)
    # will return a positive value; PyDAQmx intercepts
    # this, prints a warning, then throws a DAQError in response.
    #
    # To work around this, we need to
    #
    #   (1) silence the print()
    #   (2) catch the error

    old_stdout = sys.stdout
    sys.stdout = io.StringIO() # dummy fiel to catch print() output

    try:
        numBytesNeeded = PyDAQmx.DAQmxGetSysDevNames(None, 0)
    except PyDAQmx.DAQError as e:
        numBytesNeeded = e.error

    # Restore stdout
    sys.stdout = old_stdout

    # We now know how many bytes are needed.
    # Allocate the buffer

    stringBuffer = ctypes.create_string_buffer(numBytesNeeded)

    # Get the device names
    PyDAQmx.DAQmxGetSysDevNames(stringBuffer, numBytesNeeded)

    # Extract the device name string
    return ctypes.string_at(stringBuffer)

Is there a simpler/better way to do this? It could be useful to provide a way to call NIDAQmx functions without invoking the automatic translation of nonzero return values to DAQError exceptions.

issue in DAQmxFunctions.py _add_keywords

Comment is here, full text reproduced below.
78c76d1#PyDAQmx/DAQmxFunctions.py

On windows xp sp3 running Python 3.3 this line causes an error "global name 'add_keywords_decorator' is not defined" I solved this as follows:

44c44,45

a=locals()['add_keywords_decorator']
return a

After that python could find the function that add_keywords_decorator points to and PyDAQmx would import.

nicaiu.dll fails to import with NI-DAQmx 15

Recently tried to upgrade to NI-DAQmx 15.0.1 and my application stopped working. When I try to 'import pyDAQmx' it fails on loading the nicaiu.dll, saying the DLL failed to initialize (WinError 1114).

Previous version of NI-DAQmx was 14.5.1 which works fine. OS is Win 7 Pro 64 bit.

Problems with Windows 10 64-bit

System specs:

I am using Windows 10 64-bit with NI-DAQmx version 17.1.0.

First issue:

NotImplementedError: Location of niDAQmx library and include file unknown on win32 - if you find out, please let the PyDAQmx project know

I have found the locations.
The niDAQmx library and include files are located in the following paths:

lib_name = 'C:/Windows/System32/nicaiu.dll'
dot_h_file = 'C:/Program Files (x86)/National Instruments/Shared/ExternalCompilerSupport/C/include/nisyscfg.h'

Second issue:

After first issue has been solved (i.e. I have manually inserted the correct paths) there is an error within the Task.py file.

  File "C:\Users\johny\AppData\Local\Continuum\Anaconda2AGAIN\lib\site-packages\PyDAQmx\Task.py", line 142, in Task
    del function_name, name, func, arg_names, doc

NameError: name 'function_name' is not defined

It appears that function_dict and function_list are not being populated.

Takeaway

The package does not work with Windows 10 as of now and I am not familiar enough to debug any further. Also as a side note I think the codebase would be much better off if some of the importing conventions were changed. For instance imports like this make everything pretty confusing

import DAQmxFunctions
from DAQmxFunctions import *

Support of other DAQmx channels

I am using PyDAQmx to measure temperatures via thermocouples and a NI 9213 board. I am using the normal thermocouple DAQmx call: http://zone.ni.com/reference/en-XX/help/370471W-01/daqmxcfunc/daqmxcreateaithrmcplchan/

This is working great when I don't use the Task object but I am wondering if these other channel types will be supported in the Task object in the future or if I can somehow add them manually. I am fairly new to Python, so this may be easy and I just don't know how to do it.

Segmentation fault at cleanup

Hi,

first, thanks for the module I love python and this helps me a lot. I'm using PyDAQmx with openSuse and DAQmxbase 14.0.0. It works great with the basic functionality, however when I use the Task() class there is always an error message when calling the class destructor:

LabVIEW caught fatal signal
12.0.1f5 - Received SIGSEGV
Reason: address not mapped to object
Attempt to reference address: 0x0xb5c3a500
Segmentation fault

The data acquisition works by the way.

WriteDigitalLines on __del__ causing mafunction

I want to but a quick command to drop the output in the case of program termination, however this is causing an exception.

Windows 10, Python 3.7.3

python ni.py

Exception ignored in: <function DO.__del__ at 0x000001BF19B26378>
Traceback (most recent call last):
  File "ni.py", line 20, in __del__
  File "ni.py", line 27, in low
  File "<string>", line 3, in WriteDigitalLines
  File "<string>", line 2, in function
  File "C:\ProgramData\Anaconda3\lib\site-packages\PyDAQmx\DAQmxFunctions.py", line 57, in mafunction
ctypes.ArgumentError: argument 6: <class 'ImportError'>: sys.meta_path is None, Python is likely shutting down
import PyDAQmx
from PyDAQmx import Task
import numpy as np
import time
import pdb
import weakref

high = np.array([1], dtype=np.uint8)
low  = np.array([0], dtype=np.uint8)
 
# Simple class that can be used to control one Digital output line
class DO:
    def __init__(self, card, lines):
        self.task = Task()
        self.task.CreateDOChan('/{}/port0/{}'.format(card, lines), 
            "", PyDAQmx.DAQmx_Val_ChanForAllLines)
        self.task.StartTask()
    
    def __del__(self):
        self.low()
        self.task.StopTask()
    
    def high(self):    
        self.task.WriteDigitalLines(1, 1, 10.0, PyDAQmx.DAQmx_Val_GroupByChannel, high, None, None)

    def low(self): 
        self.task.WriteDigitalLines(1, 1, 10.0, PyDAQmx.DAQmx_Val_GroupByChannel, low, None, None)


if __name__ == '__main__':
    dig_0 = DO('cDAQ1Mod1', 'line0') 
    dig_0.high()
    time.sleep(5) 
    dig_0.low()

error getting string size

I was looking for a forum to post this question but could not find one.

I am trying to get size of string for the device names using the following function. I copied from a NI C++ example.
import ctypes
import PyDAQmx as pydaq
import numpy as np

n=pydaq.DAQmxGetSystemInfoAttribute(pydaq.DAQmx_Sys_DevNames,None)

I get the following error:

Traceback (most recent call last):
File "C:\HMRI\Calorimeter\python\main.py", line 9, in
print pydaq.DAQmxGetSystemInfoAttribute(pydaq.DAQmx_Sys_DevNames,None)
File "", line 2, in function
File "C:\Anaconda2\lib\site-packages\PyDAQmx\DAQmxFunctions.py", line 34, in mafunction
raise DAQError(error,errBuff.value.decode("utf-8"), f.name)
PyDAQmx.DAQmxFunctions.DAQError: NI-488: Interface has lost power.
in function DAQmxGetSystemInfoAttribute

Question using DAQmxGetDevProductCategory method

Hi, I wrote a class to to synchronize the Analog Inputs and Outputs of an NI PCI6221 card. Things were working just fine, but when we tried to run this program on a different computer, we received an error message when using one of the methods from this library. The strange thing is, the computer we are getting this error on is running on more recent NI drivers and the latest PyDAQmx. Here is the code:

try:
    from PyDAQmx import *
except ImportError:
    print "This program requires PyDAQmx to run."
from PyDAQmx.DAQmxCallBack import *
import numpy as np
import ctypes
import re
import time

NI_PCI_6221_MAX_VOLTAGE = 10.0;  # Max voltage output
NI_PCI_6221_MAX_SAMP_RATE = 10000;   # Measurement/generation rate ?? double check this

#Input 250 kS/s
#Output 833 kS/s for single channel, 740 kS.s for two channels
trigName = ""

class CallbackTask(Task):
    def __init__(self):
        Task.__init__(self)
        self.buffLen = 0
        self.callback =None
        self.trigName=""

    def configureCallbackTask(self, analogInputNameStr, sampRate, numSamples):
        self.buffLen = numSamples
        self.data = np.zeros(self.buffLen)
        self.CreateAIVoltageChan(analogInputNameStr,"",DAQmx_Val_Diff,-10.0,10.0,DAQmx_Val_Volts,None)
        self.CfgSampClkTiming("",float(sampRate),DAQmx_Val_Rising,DAQmx_Val_ContSamps,numSamples)
        self.trigName = self.GetTerminalNameWithDevPrefix("ai/StartTrigger")
        self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer,1000,0)
        self.AutoRegisterDoneEvent(0)

    def EveryNCallback(self):
        numReadBack = int32()
        self.data=np.zeros(self.buffLen)
        self.ReadAnalogF64(self.buffLen,10.0,DAQmx_Val_GroupByChannel,self.data,self.buffLen,byref(numReadBack),None)
        if self.callback is not None:
            self.callback(self.data)
        return 0 # The function should return an integer

    def DoneCallback(self, status):
        print "Status",status.value
        return 0 # The function should return an integer

    def setCallback(self, function):
        self.callback = function

    def GetTerminalNameWithDevPrefix(self, terminalName):
        device = ctypes.create_string_buffer(256)
        productCategory = int32()
    numDevices = uInt32()
        self.GetTaskNumDevices(byref(numDevices))
        for i in range(1, numDevices.value+1):
            self.GetNthTaskDevice(i,device,256)
            #Issue occurs in the line below
            DAQmxGetDevProductCategory(device,byref(productCategory))
            if productCategory.value!=DAQmx_Val_CSeriesModule and productCategory.value!=DAQmx_Val_SCXIModule:
                triggername = "/" + device.value + "/" + terminalName
                break
        return triggername

    def getTrigName(self):
        return self.trigName

When I create an instance of the CallbackTask class, the error from the terminal says
"Error initializing wave output:
argument 1: <type 'exceptions.TypeError'>: string or integer address expected instead of c_char_Array_256 instance"

Any thoughts?

NIDAQmx now supported on Linux

It seems that NI may now be providing support for the full version of NIDAQmx on Linux based on these instructions (http://www.ni.com/product-documentation/54754/en/). After following these instructions on CentOS 8, I installed PyDAQmx and got the error about being unable to find the NI-DAQmx headers. However, when I updated the dot_h_file to point to '/usr/include/NIDAQmx.h', it loaded properly.

Convert all the DAQmxError.* constants into DAQmxError subclasses

Something like:

class DAQException(Exception): pass
class DAQError(DAQException):
    _by_code = {}
class DAQWarning(Warning, DAQException):
    _by_code = {}

for c in constant_list:
    code = getattr(daq_constants, c)
    if c.startswith('DAQmxError'):
         errname = c[10:]
         globals()[errname + 'Error'] = type(errname + 'Error', (DAQmxError,), dict(code=code})
    elif c.startswith('DAQmxWarning'):
         errname = c[12:]
         globals()[errname + 'Warning'] = type(errname + 'Warning', (DAQWarning,), dict(code=code})

With the following changed error wrapper:

    def catch_error_default(f):
        def mafunction(*arg):
            error = f(*arg)
            if error<0:
                errBuff = ctypes.create_string_buffer(2048)
                mx.DAQmxGetExtendedErrorInfo(errBuff, 2048)
                raise DAQError._by_code[error](errBuff.value.decode("utf-8"))
            elif error>0:
                errBuff = ctypes.create_string_buffer(2048)
                mx.DAQmxGetErrorString(error, errBuff, 2048);
                warnings.warn(DAQWarning._by_code[error](errBuff.value.decode("utf-8")))

PyDAQmx 1.4.2 doesn't install correctly on Python 2.7

I've just tried installing PyDAQmx on Python 2.7.16 (a new conda 2.7 environment) using pip and it is not installing correctly (on Windows 10 anyway).

It seems to be installing into site-packages/pydaqmx rather than site-package/PyDAQmx. This means that code using PyDAQmx obviously breaks as you can't import PyDAQmx. I tried import pydaqmx but this throws an Exception because it can't import Task.

PyDAQmx==1.4.1 works correctly, so hopefully it is easy to work out what caused this change!

Digital I/O

Hello,
I am currently having an issue trying to write the code for the digital input and outputs of the examples and acquire data. If you could please help that would be greatly appreciated.

Issues using PyDAQmx 1.3.2 with 64bit Python 3.6.3 on Centos 7

Hi,

I tried installing PyDAQmx 1.3.2 on my Centos 7.4.1708 running on an 64bit Intel mini-PC. I am using NI-DAQmx Base 15.0 for Linux, and I am running a 64-bit Python 3.6.3. I am able to successfully install PyDAQmx using pip, but I get the following error when I import it.

Python 3.6.3 (default, Oct 11 2017, 18:17:37)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.

import PyDAQmx
Traceback (most recent call last):
File "", line 1, in
File "/home/tesla/.local/lib/python3.6/site-packages/PyDAQmx/init.py", line 7, in
from .DAQmxFunctions import *
File "/home/tesla/.local/lib/python3.6/site-packages/PyDAQmx/DAQmxFunctions.py", line 86, in
DAQlib, DAQlib_variadic = DAQmxConfig.get_lib()
File "/home/tesla/.local/lib/python3.6/site-packages/PyDAQmx/DAQmxConfig.py", line 62, in get_lib
ctypes.CDLL('/usr/local/lib/liblvrtdark.so', mode=ctypes.RTLD_GLOBAL)
File "/usr/lib64/python3.6/ctypes/init.py", line 343, in init
self._handle = _dlopen(self._name, mode)
OSError: /usr/local/lib/liblvrtdark.so: wrong ELF class: ELFCLASS32

Has this problem been seen before, and if yes, is there a way to resolve this.

Best,
Devesh

PyDAQmx WriteAnalogF64 -- argument 2 is wrong type

Hello,
I have ReadAnalogF64 working, but with WriteAnalogF64 I'm having trouble with argument 2 (autostart, bool32). I've tried PyDAQmx.bool32(True) (or False) as well as ctypes.c_ulong(1), etc., and always get the error below. Any help would be much appreciated.

File "", line 3, in WriteAnalogF64
File "", line 2, in function
File "C:\Python27\lib\site-packages\pydaqmx-1.2.5.2-py2.7.egg\PyDAQmx\DAQmxFunctions.py", line 23, in mafunction
error = f(*arg)
ctypes.ArgumentError: argument 2: <type 'exceptions.TypeError'>: wrong type

Named Tasks

Hi I've been wanting to make tasks with a name so that its easier to debug. The default Task does not include an option for a name, which is an argument for DAQmxCreateTask.

I've included a class that wraps Task that allows for the name. I think an optional name argument in Task.__init__ would be a helpful addition, so that wrapping it like this is no longer necessary.

Thanks!
-Ed

class NamedTask(mx.Task):
    ''' replaces __init__ with one that accepts a name for the task, otherwise identical to PyDaqmx task
        override PyDAQmx definition, which does not support named tasks
        no special chars in names, space OK
    '''
    def __init__(self, name= b''):
        self.taskHandle = mx.TaskHandle(0)
        mx.DAQmxCreateTask(name, mx.byref(self.taskHandle))

pep8-ify function names

Following on from this comment.

So instead of

task.CfgSampClkTiming(
    source=None,
    rate=1,
    activeEdge=daq.Val_Rising,
    sampleMode=daq.Val_FiniteSamps,
    sampsPerChan=1
)

it would become

task.cfg_sample_clk_timing(
    source=None,
    rate=1,
    active_edge=PyDAQmx.VAL_RISING,
    sample_mode=PyDAQmx.VAL_FINITE_SAMPS,
    samps_per_chan=1
)

This potentially raises the issue that the module name should be PEP8'd as well, becoming the much easier to type pydaqmx

NIDAQmx Base and continuous callback issue

Dear all,
PyDAQmx works well with not only DAQmx but also DAQmx-base.

The sampling example also works well, but the callback example doesn't work with DAQmx-base.
(https://pythonhosted.org/PyDAQmx/callback.html)

The function AutoRegisterEveryNSamplesEvent and variable DAQmx_Val_Acquired_Into_Buffer are not exist in DAQmx-base.

https://github.com/sppmg/matlab-ni-daqmx/blob/master/DAQmxMidLib/NIDAQmx.h
https://github.com/robotology-legacy/icub-nidaqmx/blob/master/.nidaqmx/usr/local/include/NIDAQmxBase.h

Based on the last answer of below, some (complicated) work-around might exists.
https://forums.ni.com/t5/Multifunction-DAQ/Continuous-sampling-in-NI-Daqmx-Base/td-p/226973?profile.language=en

Any successful implimentation exist for continous sampling with DAQmx-base, not DAQmx?

No attribute WriteAnalogScalarF64

Hello, I am on macOS with python3, and if I try to run example2.py I get the following error:

Traceback (most recent call last):
  File "PyDAQmx/test.py", line 20, in <module>
    task_out.WriteAnalogScalarF64(1,10.0,value,None)
AttributeError: 'Task' object has no attribute 'WriteAnalogScalarF64'

Any suggestions on how to fix it? Thank you!

Asynchronous read each channel?

Hi, I start to use usb-6289 to read voltage values from each channel. It works well when synchronous reading data. As I need to collect each channel with different time sequence, is there some way to asynchronous read each channel with PyDAQmx? Thanks:).

Synchronous Input and Output

Hi,

Since I'm new to PyDAQmx, I'd really appreciate your help. I'm trying to do synchronous input and output using a NI USB-6212 (BNC) device, but I have several questions:

  1. Can a task support both input and output? As far as I understand, it cannot, so I have to create two separate tasks, right?

  2. I tried to write a script using the simple functions DAQmxWriteAnalogF64 and DAQmxReadAnalogF64. What I wanted to do is read back the sine wave I wrote to the output channel. After reading instructions in the NI site, I used the following functions and parameters to control the timing of the two tasks:

daq.DAQmxCfgSampClkTiming(taskHandle_output,"",fs,daq.DAQmx_Val_Falling,daq.DAQmx_Val_ContSamps,block)
daq.DAQmxCfgSampClkTiming(taskHandle_input,"ao/SampleClock",fs,daq.DAQmx_Val_Falling,daq.DAQmx_Val_ContSamps,block)

with block = 1024. However, there was a noticeable latency between the two tasks.

  1. I am wondering if I have to use callback functions (and maybe threading??) to achieve this simultaneity of input and output. But again, it's not straightforward to me how to do that. Would I have to write two different callback functions, one for the output and one for the input task?

Thanks in advance for any advice!

example "AnalogInput_acq_IntClk.py" is not working at all

contains a tremendous amount of typos

the code here is "repaired", but still not working (Traceback at the bottom)

import PyDAQmx
from PyDAQmx import *
import numpy


class AIParameters(object):
    limits = (-10, 10)
    physicalChannel = ["/Dev1/ai0"]

    def __init__(self, sample_rate, sample_number, channels=None, limits=None):
        self.sampleRate = sample_rate
        self.sampleNumber = sample_number
        if limits is None:
            limits = self.limits
        self.limit_inf = limits[0]
        self.limit_sup = limits[1]
        if channels is not None:
            if type(channels) is str:
                physicalChannel = [channels]
            self.physicalChannel = channels

    @property
    def device_name(self):
        device_name = self.physicalChannel[0].split('/')[0]
        if device_name == '':
            device_name = self.physicalChannel[0].split('/')[1]
        return device_name


class Trigger(object):
    def __init__(self, terminal):
        self.terminal = terminal


class RisingTrigger(Trigger):
    direction = DAQmx_Val_Rising


class FallingTrigger(Trigger):
    direction = DAQmx_Val_Falling


class AIVoltageChan(Task):
    def __init__(self, AIParam, reset=True, terminalConfig=DAQmx_Val_RSE, trigger=None):
        if reset:
            DAQmxResetDevice(AIParam.device_name)
        super(AIVoltageChan).__init__(self)
        self.sampleNumber = AIParam.sampleNumber
        self.sampleRate = AIParam.sampleRate
        self.limit_inf = AIParam.limit_inf
        self.limit_sup = AIParam.limit_sup
        self.physicalChannel = AIParam.physicalChannel
        self.numberOfChannel = len(AIParam.physicalChannel)
        if isinstance(terminalConfig, str):
            terminalConfig = getattr(PyDAQmx, terminalConfig)
        self.terminalConfig = terminalConfig
        self.trigger = trigger
        self.configure()

    def configure(self):
        channel_string = ','.join(self.physicalChannel)
        self.CreateAIVoltageChan(channel_string, "", self.terminalConfig,
                                 self.limit_inf, self.limit_sup,
                                 DAQmx_Val_Volts, None)

    def start(self):
        n = self.sampleNumber
        sampleRate = self.sampleRate
        self.CfgSampClkTiming("", sampleRate, DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, n)
        if self.trigger is not None:
            self.CfgDigEdgeRefTrig(self.trigger.terminal, self.trigger.direction, 10)
        self.StartTask()

    def read(self):
        n = self.sampleNumber
        data = numpy.zeros((n, self.numberOfChannel), dtype=numpy.float64)
        read = int32()
        self.ReadAnalogF64(n, 10.0, DAQmx_Val_GroupByScanNumber, data, n * self.numberOfChannel, byref(read), None)
        return data

    def stop(self):
        self.StopTask()

    def wait(self, timeout=10):
        self.WaitUntilTaskDone(timeout)


#ai = AIVoltageChan(AIParam=AIParameters(100000, 10000, ['/dev1/ai0', '/dev1/ai1']))
if __name__=="__main__":
    ai = AIVoltageChan(AIParam=AIParameters(100000, 10000, ['/dev1/ai0', '/dev1/ai1']),
                    terminalConfig="DAQmx_VAl_PseudoDiff",
                    trigger=RisingTrigger('/dev1/PFI0'))
    ai.start()
    ai.wait()
    ai.read()
    ai.stop()

The Traceback is:

Traceback (most recent call last):
  File "C:/Users/Snowball/Desktop/Data Logger/AnalogInput_acq_IntClk.py", line 92, in <module>
    trigger=RisingTrigger('/dev1/PFI0'))
  File "C:/Users/Snowball/Desktop/Data Logger/AnalogInput_acq_IntClk.py", line 47, in __init__
    super(AIVoltageChan).__init__(self)
TypeError: super() argument 1 must be type, not AIVoltageChan
Exception ignored in: <object repr() failed>
Traceback (most recent call last):
  File "C:\Anaconda3\lib\site-packages\PyDAQmx\Task.py", line 118, in __del__
    self.ClearTask()
  File "C:\Anaconda3\lib\site-packages\PyDAQmx\Task.py", line 122, in ClearTask
    if self.taskHandle:
AttributeError: 'AIVoltageChan' object has no attribute 'taskHandle'

Continuous Data Acquisition using Digital Start Stop Trigger

We need help regarding using this package for continuous data acquisition using NI cDAQ chassis.

We have a NI9184 chassis with a NI9234 module and NI9421 DI module. We would like to use digital trigger to start and stop data acquisition and measure analog acceleration data.

We used the process described in this link. We are using the C API provided by NIdaqmx.

Below is our Python code(C-API) which is replicating the VI given at the link mentioned above.

  1. Create an analog input channel to measure acceleration data
    DAQmxCreateAIAccelChan(taskHandle, "cDAQ9184-1B20914Mod4/ai1","", DAQmx_Val_Cfg_Default,-50.0, 50.0, DAQmx_Val_AccelUnit_g, 100.0, DAQmx_Val_mVoltsPerG, DAQmx_Val_Internal,0.0021, None)
  2. Set the sample clock rate at 51200 samples/second and finite samples per channel to be 5120
    DAQmxCfgSampClkTiming(taskHandle,"",51200.0,DAQmx_Val_Rising,DAQmx_Val_FiniteSamps,5120)
  3. Set the buffer size to be 10 times the number of samples per channel, i.e., 51200
    DAQmxCfgInputBuffer(taskHandle, 51200)
    4a. Configure the start trigger to start filling the buffer after receiving a digital edge on PFI 0
    DAQmxCfgDigEdgeStartTrig(taskHandle,"/cDAQ9184-1B20914Mod2/PFI0", DAQmx_Val_Rising)
    4b. Configure the reference trigger (stop trigger) to stop filling the buffer (plus the number of post-trigger samples which in our case is 5120-2 = 5118) after receiving a digital edge on PFI 1
    DAQmxCfgDigEdgeRefTrig (taskHandle,"/cDAQ9184-1B20914Mod2/PFI1", DAQmx_Val_Rising,2)
  4. Set the buffer read position to "Current Read Position"
    DAQmxSetReadRelativeTo(taskHandle, DAQmx_Val_CurrReadPos)
  5. Start the acquisition
    DAQmxStartTask(taskHandle)
    7a. Read until the stop trigger is received. If task is done (stop trigger has been received) then compare the number of samples left in the buffer with the number of samples to read.

7b. If the number of samples in buffer is greater than 0, continue to read. If buffer is empty and task is done, loop will be stopped.

`taskComplete = bool32() #boolean for storing if the task is completed
avail = uint32() # integer variable for storing available samples per channel in buffer
data = numpy.zeros(5120) # data array into which analog data will be written after it is read
readDI = int32()
readBytes = int32()
tot = [] # an empty list in which data from each call to read function is appended

while True:
    print 'Started Reading From Buffer'
    DAQmxReadAnalog64(taskHandle, 5120, -1, DAQmx_Val_GroupByChannel, data, 5120, byref(readDI), byref(readBytes), None)
    DAQmxGetTaskComplete(taskHandle, byref(taskComplete))
    if taskComplete.value:
        print "Stop Trigger Received: Task Stopped"
        flag=0
        DAQmxGetReadAvailSampPerChan(taskHandle,byref(avail))
        while avail > 0:
            DAQmxReadAnalog64(taskHandle, 5120, -1, DAQmx_Val_GroupByChannel, data, 5120, byref(readDI), byref(readBytes), None)
            tot.append(data)
            DAQmxGetReadAvailSampPerChan(taskHandle,byref(avail))
        break
    tot.append(dataDI)

8. Clear the task and check for errorsif taskHandle:
# DAQmx Stop Code
DAQmxStopTask(taskHandle)
DAQmxClearTask(taskHandle)
`

However, when we run the above script, we get the following error:
"Finite acquisition or generation has been stopped before the requested number of samples were acquired or generated in function DAQmxStopTask"

Could you please explain why we are getting the above error. Also kindly advise if we are doing something incorrect in the procedure described above and the necessary corrective action.

`__version__` string did not change from v1.4 to v1.4.1

I have code that relies on functionality in PyDAQmx v1.4.1, and my code checks that the PyDAQmx version is new enough so that it can raise an exception telling the user to update PyDAQmx.

However, PyDAQmx.__version__ is '1.4', on version 1.4.1.

The version string should be updated to 1.4.1. Or, I suppose, 1.4.2 since you would need to release a new version to include the fix!

DAQmxGetDeviceAttribute - error with python 32bits (ok with python 64bits)

Hello,

I'm currently using the function DAQmxGetDeviceAttribute to obtain device attribute. It works fine with python 64bits (anaconda package) but it doesn't work with python 32bits (under windows 7 64bits or windows xp 32bits) :

some examples

from PyDAQmx import *
dev='Dev1'
rate=(ctypes.c_double*1)()
#maximum input rate for all channels
DAQmxGetDeviceAttribute(dev,DAQmx_Dev_AI_MaxSingleChanRate,byref(rate)) 
from PyDAQmx import *
dev='Dev1'
chans=ctypes.create_string_buffer('',1024)
#obtain the analog input channel name
DAQmxGetDeviceAttribute(dev,DAQmx_Dev_AI_PhysicalChans,chans) 

I have the same errors :

DAQmxGetDeviceAttribute(dev,DAQmx_Dev_AI_MaxSingleChanRate,byrefrate)) #maxi
mum input rate for all channels
  File "<string>", line 2, in function
  File "C:\Anaconda\lib\site-packages\PyDAQmx\DAQmxFunctions.py", line 23, in ma
function
    error = f(*arg)
ValueError: Procedure probably called with too many arguments (12 bytes in exces
s)

If I correctly understand this error, it seems that the "address" of arguments are sent using a 64bits value in place of 32bits values (3x4bytes/32bits in excess). I don't know if this error can be avoided by calling these functions with other parameters or corrections have to be made in the pydaqmx package or another one ?

I have a similar error when using DAQmxGetSystemInfoAttribute (8 bytes in excess) e.g.

from PyDAQmx import *
dev=ctypes.create_string_buffer('',1024)
DAQmxGetSystemInfoAttribute(DAQmx_Sys_DevNames,dev)

Let us notice that the acquisition functions work fine. When I look at the protype of these 2 functions (in NIDAQmx.h), I remark that they are variadic functions ... Maybe it explains the origin of the error ...

Could you please have a look in this and tell me if I'm doing something wrong or is it a problem with a package ?

I thank you in advance,
Kind regards,
Rudy

edit : some further tests seem to focus the problem when using windll to run these functions with python 32bits BUT the acquisitions (class Task) do not work anymore if I replace windll by cdll in the DAQmxFunctions.py when using python 32bits (ValueError: Procedure called with not enough arguments (8 bytes missing) or wrong calling convention) No problem using python 64bits in both case (windll or cdll).

This example code works fine with python 64bits & python 32bits in windows 7 64bits (not yet tested with windows xp) :

from ctypes import *
lib_name="nicaiu"
DAQlib = cdll.LoadLibrary(lib_name)
dev=create_string_buffer("Dev1")
att=c_long(10636) #DAQmx_Dev_AI_MaxSingleChanRate
rate=(c_double*1)()
DAQlib.DAQmxGetDeviceAttribute(dev,att,rate)
print rate[0]
inf=c_int32(0x193B) #DAQmx_Sys_DevNames,dev
devi=create_string_buffer('',1024)
DAQlib.DAQmxGetSystemInfoAttribute(inf,devi)
print devi.value

DAQ using callback function

Hello,
I'm trying to take data using callback method, and found PyDAQmx. I converted PyDAQmx 1.4.3 using 2to3 and installed to use it on python 3.7.6 (32bit), windows 10, NIDAQ USB-6212, NIDAQmx 19.6

I wrote code as below using PyDAQmx but it gives an error.

from PyDAQmx import *
from PyDAQmx.DAQmxCallBack import *

class MyList(list):
    pass

def EveryNCallback_py(taskHandle, eventType, nSamples, callbackData_ptr):
    callbackData = get_callbackData_from_id(callbackData_ptr)
    read = uInt32()

    nidaq.DAQmxReadAnalogF64(AItaskHandle,samples_per_chan,float64(-1),DAQmx_Val_GroupByScanNumber,AIdata.ctypes.data,Length,ctypes.byref(read),None)

    if(read>0):
        print('Acquired %d samples.' %read)
    return 0

EveryNCallback = pydaqmx.DAQmxEveryNSamplesEventCallbackPtr(EveryNCallback_py)

def some_func(num): 

    ... # some other code including import, declare variables like DAQmx_Val_Acquired_Into_Buffer, etc...

    AIdata = MyList()
    AIdata = numpy.zeros( ( max_num_samples, ), dtype=numpy.float64 )
    AIdata_dummy = numpy.zeros( ( max_num_samples, ), dtype=numpy.float64 )
    Length = AIdata.size
    samples_per_chan = round(max_num_samples/2)
    id_a = create_callbackdata_id(AIdata)

    AItaskHandle = TaskHandle( 0 )

    nidaq.DAQmxCreateTask("",ctypes.byref(AItaskHandle))
    nidaq.DAQmxCreateAIVoltageChan(AItaskHandle,b"Dev%d/ai0,Dev%d/ai2" %(num,num),"",DAQmx_Val_Diff,float64(-5.0),float64(5.0),DAQmx_Val_Volts,None)
    nidaq.DAQmxCfgSampClkTiming(AItaskHandle,"",float64(sampleRate),DAQmx_Val_Rising,DAQmx_Val_ContSamps,uInt64(max_num_samples))
    nidaq.DAQmxSetDigLvlPauseTrigSrc(AItaskHandle, b"/Dev%d/PFI0" %num)
    nidaq.DAQmxSetPauseTrigType(AItaskHandle, DAQmx_Val_DigLvl)
    nidaq.DAQmxSetDigLvlPauseTrigWhen(AItaskHandle, DAQmx_Val_High)

    DAQmxRegisterEveryNSamplesEvent(AItaskHandle,DAQmx_Val_Acquired_Into_Buffer,1000,0,EveryNCallback,id_a)
    nidaq.DAQmxStartTask( AItaskHandle )

And if I run this code, it gives me the following error.

Traceback (most recent call last):
  File ~~~, line 118, in some_func
    pydaqmx.DAQmxRegisterEveryNSamplesEvent(AItaskHandle,DAQmx_Val_Acquired_Into_Buffer,1000,0,EveryNCallback,id_a)
  File "<string>", line 2, in function
  File "C:\Users\JungEun.Suh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pydaqmx-1.4.3-py3.7.egg\PyDAQmx\DAQmxFunctions.py", line 57, in mafunction
    error = f(*arg)
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type

Do you have any idea what's wrong here? Please let me know if you need any further information.

Thank you in advance!

ArgumentError thrown at DAQmxFunctions->mafunction

I'm attempting to run PyDAQmx on Python 3.3 (32-bit), on a Windows 7 machine with LabVIEW 8.6 (32-bit) and NI-DAQ (9.2.1) installed.

During PyDAQmx installation, I had to use python 2to3.py -w . to upgrade all *.py files on latest version of source code downloaded from Github (version 1.2.5.2). I wonder if anyone else has got PyDAQmx installed and running for Python 3.3 using this approach? I had issues getting all of the modules in the PyDAQmx package installed using the published Python 3 install instructions.

The NIDAQmx.h version is Copyright 2003-2010.

After attempting to run any of the examples I get the same error message:

Traceback (most recent call last):
File "example.py", line 9, in <module>
analog_input.CreateAIVoltageChan("cDAQ1Mod1/ai0","",DAQmx_Val_Cfg_Default,-10.0,10.0,DAQmx_Val_Volts,None)
File "<string>", line 3, in CreateAIVoltageChan
File "<string>", line 2, in function
File "C:\Python33\lib\site-packages\pydaqmx-1.2.5.2-py3.3.egg\PyDAQmx\DAQmxFunctions.py", line 23, in mafunction
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type

example.py

from PyDAQmx import *
import numpy

analog_input = Task()
read = int32()
data = numpy.zeros((1000,), dtype=numpy.float64)

# DAQmx Configure Code
analog_input.CreateAIVoltageChan("cDAQ1Mod1/ai0","",DAQmx_Val_Cfg_Default,-10.0,10.0,DAQmx_Val_Volts,None)
analog_input.CfgSampClkTiming("",10000.0,DAQmx_Val_Rising,DAQmx_Val_FiniteSamps,1000)

# DAQmx Start Code
analog_input.StartTask()

# DAQmx Read Code
analog_input.ReadAnalogF64(1000,10.0,DAQmx_Val_GroupByChannel,data,1000,byref(read),None)

print("Acquired %d points"%read.value)

It's tough for me to tell if this error is due to improper PyDAQmx package setup for Python 3...

Will attempt to install and run package on Python 2.7 to see if error still exists for me.

Acquiring from Multiple Channels Syncronously (Microphones).

Hello!

I've successfully read from a single microphone using DAQmxCreateAIMicrophoneChan. Both using the OO Task interface and the lower level version.

I need to measure multiple microphones syncronously (for example, all four channels in a four channel card).

I can't figure out how to define and add 4 channels to the same task. Any idea? One tricky thing is that with microphones I need to define custom ranges for each mic, so it's not as simple as supplying a range of input channels to the CreateChannel step.

Any ideas?

get libnipalu.so failed to initialize while importing

Hi,

I get this error while importing PyDAQmx:

Python 3.3.5 (default, Mar 27 2014, 17:16:46) [GCC] on linux
Type "help", "copyright", "credits" or "license" for more information.

from PyDAQmx import *
libnipalu.so failed to initialize
Perhaps you need to run updateNIDrivers
Aborted
yann@linux-b4hp:~>

I am using OpenSUSE 13.1 i586 (32 bit), kernel 3.11.10-25, and NIDAQmx Base 14.0 (14.0.0f0)
Running updateNIDrivers and rebooting does not solve the issue.

Any idea?
Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.