-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnidaq.py
More file actions
271 lines (211 loc) · 8.31 KB
/
nidaq.py
File metadata and controls
271 lines (211 loc) · 8.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 08 10:28:40 2016
@author: samg
modified version of iodaq.py from aibstim package
"""
from PyDAQmx import Task
from PyDAQmx.DAQmxConstants import *
from PyDAQmx.DAQmxFunctions import *
import numpy as np
def GetDevices():
bufferSize = 1024 #set max buffer size
devicenames = " "*bufferSize #build device string
DAQmxGetSysDevNames(devicenames, bufferSize) #fill string with names
return devicenames.strip().strip('\x00').split(', ') #strip off null char for each
def GetAIChannels(device):
bufferSize = 1024
channels = " "*bufferSize
DAQmxGetDevAIPhysicalChans(device,channels,bufferSize)
return channels.strip().strip('\x00').split(', ')
def GetAOChannels(device):
bufferSize = 1024
channels = " "*bufferSize
DAQmxGetDevAOPhysicalChans(device,channels,bufferSize)
return channels.strip().strip('\x00').split(', ')
def GetDOPorts(device):
bufferSize = 1024
ports = " "*bufferSize
DAQmxGetDevDOPorts(device, ports, bufferSize)
return ports.strip().strip('\x00').split(', ')
def GetDIPorts(device):
bufferSize = 1024
ports = " "*bufferSize
DAQmxGetDevDIPorts(device, ports, bufferSize)
return ports.strip().strip('\x00').split(', ')
def GetDOLines(device):
bufferSize = 1024
lines = " "*bufferSize
DAQmxGetDevDOLines(device, lines, bufferSize)
return lines.strip().strip('\x00').split(', ')
def GetDILines(device):
bufferSize = 1024
lines = " "*bufferSize
DAQmxGetDevDILines(device, lines, bufferSize)
return lines.strip().strip('\x00').split(', ')
class AnalogInput(Task):
'''
create an AnalogInput object for a single channel
example 1:
import nidaq
ai = nidaq.AnalogInput(device='Dev1',channel=0)
ai = di.StartTask()
ai.data # single data buffer
ai.StopTask()
ai.ClearTask()
example 2:
import nidaq
ai = nidaq.AnalogInput(device='Dev1',channel=0,accumulate=True)
ai = di.StartTask()
ai.StopTask()
ai.dataArray # array of data buffers
ai.bufferCount
ai.ClearTask()
'''
def __init__(self,
device='Dev1',
channel=0,
voltageRange=(-10.0,10.0),
sampRate=1000.0,
bufferSize=1000,
accumulate=False):
# construct task
Task.__init__(self)
# set up task properties
self.channel = channel
self.voltageRange = voltageRange
self.sampRate = sampRate
self.bufferSize = bufferSize
self.timeout = 10.0
self.data = np.zeros(self.bufferSize,dtype=np.float64)
self.accumulate = accumulate
self.dataArray = []
self.bufferCount = 0
self.CreateAIVoltageChan(device+'/ai'+str(channel),'',DAQmx_Val_RSE,voltageRange[0],voltageRange[1],DAQmx_Val_Volts,None)
self.CfgSampClkTiming('',sampRate,DAQmx_Val_Rising,DAQmx_Val_ContSamps,bufferSize)
# set up data buffer callback
self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer,self.bufferSize,0)
# set up task complete callback (unused since this class takes continuous samples)
self.AutoRegisterDoneEvent(0)
def EveryNCallback(self):
try:
read = int32()
self.ReadAnalogF64(self.bufferSize,self.timeout,DAQmx_Val_Auto,self.data,self.bufferSize,byref(read),None)
if self.accumulate:
# append each data buffer to a list
self.dataArray.extend(self.data.astype(np.float64).tolist())
self.bufferCount+=1
except Exception, e:
print 'Failed to read buffer'
def DoneCallback(self, status):
print 'Status',status
return 0 # the function should return an integer
class AnalogOutput(Task):
'''
create an AnalogOutput object for a single channel
for unknown reason output rate is 1600 samples/s
'''
def __init__(self,
device='Dev1',
channel=0,
voltageRange=(0.0,5.0)):
# construct task
Task.__init__(self)
# set up task properties
self.channel = channel
self.voltageRange = voltageRange
self.sampRate = 1600
self.lastOut = np.nan
self.CreateAOVoltageChan(device+'/ao'+str(channel),"",voltageRange[0],voltageRange[1],DAQmx_Val_Volts,None)
self.AutoRegisterDoneEvent(0)
def Write(self,values):
'''Writes a numpy array of float64's to the analog output'''
self.lastOut = values[-1]
self.WriteAnalogF64(len(values),0,-1,DAQmx_Val_GroupByChannel,values,None,None)
def DoneCallback(self,status):
return 0
class DigitalInputs(Task):
'''
create a DigitalInputs object for all lines on a port
example:
import nidaq
di = nidaq.DigitalInputs(device='Dev1',port=0)
di = di.StartTask()
data = di.Read()
ch0 = data[0]
di.StopTask()
di.ClearTask()
'''
def __init__(self,
device='Dev1',
port=0):
# construct task
Task.__init__(self)
# set up task properties
self.port = port
lines = GetDILines(device)
lines = [l for l in lines if 'port' + str(port) in l]
self.deviceLines = len(lines)
self.timeout = 10.0
devStr = str(device) + '/port' + str(port) + '/line0:' + str(self.deviceLines-1)
self.CreateDIChan(devStr,'',DAQmx_Val_ChanForAllLines)
self.AutoRegisterDoneEvent(0)
def Read(self):
# reads the current setting of all inputs
data = np.zeros(self.deviceLines, dtype=np.uint8)
bytesPerSample = c_long()
samplesPerChannel = c_long()
self.ReadDigitalLines(1,self.timeout,DAQmx_Val_GroupByChannel,data,self.deviceLines,samplesPerChannel,bytesPerSample,None)
return data
def DoneCallback(self, status):
print "Status",status.value
return 0 # the function should return an integer
class DigitalOutputs(Task):
'''
create DigitalOutputs object for all lines on port
example:
import nidaq
do = nidaq.DigitalOutputs(device='Dev1',port=1,initialState='high')
do.StartTask()
do.Write(np.array([True,False,True,False]))
do.WriteBit(0,True)
do.StopTask()
do.ClearTask()
'''
def __init__(self,
device='Dev1',
port=1,
initialState='low'):
# construct task
Task.__init__(self)
# set up task properties
self.port = port
lines = GetDOLines(device)
lines = [l for l in lines if 'port' + str(port) in l]
self.deviceLines = len(lines)
self.timeout = 10.0
#create initial state of output lines
if initialState.lower()=='low':
self.lastOut = np.zeros(self.deviceLines,dtype=np.uint8)
elif initialState.lower()=='high':
self.lastOut = np.ones(self.deviceLines,dtype=np.uint8)
elif type(initial_state) == np.ndarray:
self.lastOut = initialState
else:
raise TypeError("Initial state not understood. Try 'high' or 'low'")
devStr = str(device) + "/port" + str(port) + "/line0:" + str(self.deviceLines-1)
self.CreateDOChan(devStr,"",DAQmx_Val_ChanForAllLines)
self.AutoRegisterDoneEvent(0)
def DoneCallback(self,status):
print "Status", status.value
return 0
def Write(self,levels):
'''Writes a numpy uint8 array of levels to set the current output state'''
self.lastOut = levels
self.WriteDigitalLines(1,1,self.timeout,DAQmx_Val_GroupByChannel,levels,None,None)
def WriteBit(self,index,level):
'''Writes a single bit to the given line index'''
self.lastOut[index] = level
self.WriteDigitalLines(1,1,self.timeout,DAQmx_Val_GroupByChannel,self.lastOut,None,None)
if __name__ == '__main__':
pass