-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdiff.txt
538 lines (519 loc) · 18.2 KB
/
diff.txt
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
diff --git a/code/Display.py b/code/Display.py
new file mode 100644
index 0000000..97d854c
--- /dev/null
+++ b/code/Display.py
@@ -0,0 +1,299 @@
+"""
+ COPYRIGHT © 2018 BY DATAQ INSTRUMENTS, INC.
+!!!!!!!! VERY IMPORTANT !!!!!!!!
+!!!!!!!! READ THIS FIRST !!!!!!!!
+This program works only with model DI-1100.
+Disconnect any other instrument models to prevent the program from
+detecting a different device model with a DATAQ Instruments VID and attempting to use it.
+Such attempts will fail.
+While the DI-1100's protocol is similar to model DI-2108, it doesn't support
+a decimation function. Therefore, its minimum sample rate of ~915 Hz is
+too fast for this program to work properly because of its heavy
+use of print statements. The program overcomes that problem
+through use of a 'decimation_factor' variable to slow scan rate to an
+acceptable level.
+The DI-1100 used with this program MUST be placed in its CDC communication mode.
+Follow this link for guidance:
+https://www.dataq.com/blog/data-acquisition/usb-daq-products-support-libusb-cdc/
+The DI-1100 protocol this program uses can be downloaded from the instrument's
+product page:
+https://www.dataq.com/resources/pdfs/misc/di-1100-protocol.pdf
+"""
+
+
+import serial
+import serial.tools.list_ports
+import keyboard
+import time
+
+import Format
+
+"""
+Example slist for model DI-1100
+0x0000 = Analog channel 0, ±10 V range
+0x0001 = Analog channel 1, ±10 V range
+0x0002 = Analog channel 2, ±10 V range
+0x0003 = Analog channel 3, ±10 V range
+"""
+#slist = [0x0000,0x0001,0x0002,0x0003]
+slist = [0x0000,0x0001,0x0002,0x0003]
+
+ser=serial.Serial()
+
+
+#Define formatting for the different sensors.
+def Format_Force_1(num):
+ const1 = 1
+ const2 = 0 #TODO: replace these with actual values, once we've calibrated the force gauges!
+ num = num * const1 + const2
+ return "{: 3.3f}".format(num) + " Kg\t"
+
+def Format_Force_2(num):
+ const1 = 1
+ const2 = 0 #TODO: replace these with actual values, once we've calibrated the force gauges!
+ num = num * const1 + const2
+ return "{: 3.3f}".format(num) + " Kg\t"
+
+def Format_Press_1(num):
+ const1 = 625
+ const2 = 312.5 #This is for the MSP300, and the numbers are from that datasheet.
+ #Specifically, at 0 PSI, we get 0.5V, and at 4.5V, we get 2500 PSI. Hence, the values stated here.
+
+ num = num * const1 + const2
+ return "{: 3.3f}".format(num) + " PSI\t"
+
+def Format_Press_2(num):
+ const1 = 1
+ const2 = 0 #TODO: replace these with actual values, once we've calibrated the Swagelock transducer!
+ num = num * const1 + const2
+ return "{: 3.3f}".format(num) + " KPa\t"
+
+
+
+
+
+
+"""
+Since model DI-1100 cannot scan slower that 915 Hz at the protocol level,
+and that rate or higher is not practical for this program, define a decimation
+factor to slow scan rate to a practical level. It defines the number of analog readings to average
+before displaying them. By design, digital input values display instantaneously
+without averaging at the same rate as decimated analog values.
+Averaging n values on each analog channel is more difficult than simply using
+every nth value, but is recommended since it reduces noise by a factor of n^0.5
+'decimation_factor' must be an integer value greater than zero.
+'decimation_factor' = 1 disables decimation and attemps to output all values.
+"""
+# Define a decimation factor variable
+decimation_factor = 500
+
+# Contains accumulated values for each analog channel used for the average calculation
+achan_accumulation_table = list(())
+
+# Define flag to indicate if acquiring is active
+acquiring = False
+
+""" Discover DATAQ Instruments devices and models. Note that if multiple devices are connected, only the
+device discovered first is used. We leave it to you to ensure that it's a DI-1100."""
+def discovery():
+ # Get a list of active com ports to scan for possible DATAQ Instruments devices
+ available_ports = list(serial.tools.list_ports.comports())
+ # Will eventually hold the com port of the detected device, if any
+ hooked_port = ""
+ for p in available_ports:
+ # Do we have a DATAQ Instruments device?
+ if ("VID:PID=0683" in p.hwid):
+ # Yes! Dectect and assign the hooked com port
+ hooked_port = p.device
+ break
+
+ if hooked_port:
+ print("Found a DATAQ Instruments device on",hooked_port)
+ ser.timeout = 0
+ ser.port = hooked_port
+ ser.baudrate = '115200'
+ ser.open()
+ return(True)
+ else:
+ # Get here if no DATAQ Instruments devices are detected
+ print("Please connect a DATAQ Instruments device")
+ input("Press ENTER to try again...")
+ return(False)
+
+# Sends a passed command string after appending <cr>
+def send_cmd(command):
+ ser.write((command+'\r').encode())
+ time.sleep(.1)
+ if not(acquiring):
+ # Echo commands if not acquiring
+ while True:
+ if(ser.inWaiting() > 0):
+ while True:
+ try:
+ s = ser.readline().decode()
+ s = s.strip('\n')
+ s = s.strip('\r')
+ s = s.strip(chr(0))
+ break
+ except:
+ continue
+ if s != "":
+ print (s)
+ break
+
+# Configure the instrment's scan list
+def config_scn_lst():
+ # Scan list position must start with 0 and increment sequentially
+ position = 0
+ for item in slist:
+ send_cmd("slist "+ str(position ) + " " + str(item))
+ # Add the channel to the logical list.
+ achan_accumulation_table.append(0)
+ position += 1
+
+while discovery() == False:
+ discovery()
+# Stop in case DI-1100 is already scanning
+send_cmd("stop")
+# Define binary output mode
+send_cmd("encode 0")
+# Keep the packet size small for responsiveness
+send_cmd("ps 0")
+# Configure the instrument's scan list
+config_scn_lst()
+
+# Define sample rate = 1 Hz, where decimation_factor = 1000:
+# 60,000,000/(srate) = 60,000,000 / 60000 / decimation_factor = 1 Hz
+send_cmd("srate 60000")
+print("")
+print("Ready to acquire...")
+print ("")
+
+# This is the slist position pointer. Ranges from 0 (first position)
+# to len(slist)
+slist_pointer = 0
+
+# Init a decimation counter:
+dec_count = decimation_factor
+
+# Init the logical channel number for enabled analog channels
+achan_number = 0
+
+# This is the constructed output string
+output_string = []
+dig_in = 0
+
+
+acquiring = True
+send_cmd("start")
+
+start_time = time.time()
+
+# This is the main program loop, broken only by typing a command key as defined
+while time.time() - start_time < 10:
+
+ #Uncomment the following, and replace the above while loop condition with 'True' for
+ #indefinite reading:
+ if dig_in > 0 and time.time() - start_time > 5:
+ break
+
+ # If key 'G' start scanning
+ #if keyboard.is_pressed('g' or 'G'):
+ # keyboard.read_key()
+ # acquiring = True
+ # send_cmd("start")
+ # If key 'S' stop scanning
+ #if keyboard.is_pressed('s' or 'S'):
+ # keyboard.read_key()
+ # send_cmd("stop")
+ # time.sleep(1)
+ # ser.flushInput()
+ # print ("")
+ # print ("stopped")
+ # acquiring = False
+ # If key 'Q' exit
+ #if keyboard.is_pressed('q' or 'Q'):
+ # keyboard.read_key()
+ # send_cmd("stop")
+ # ser.flushInput()
+ # break
+ while (ser.inWaiting() > (2 * len(slist))):
+ for i in range(len(slist)):
+ # Always two bytes per sample...read them
+ bytes = ser.read(2)
+ # Only analog channels for a DI-1100, with dig_in states appearing in the two LSBs of ONLY the first slist position
+ result = int.from_bytes(bytes,byteorder='little', signed=True)
+
+ # Since digital input states are embedded into the analog data stream there are four possibilities:
+ if (dec_count == 1) and (slist_pointer == 0):
+ # Decimation loop finished and first slist position
+ # Two LSBs carry information only for first slist posiiton. So, ...
+ # Preserve lower two bits representing digital input states
+ dig_in = result & 0x3
+ # Strip two LSBs from value to be added to the analog channel accumulation, preserving sign
+ result = result >> 2
+ result = result << 2
+ # Add the value to the accumulator
+ achan_accumulation_table[achan_number] = result + achan_accumulation_table[achan_number]
+ achan_number += 1
+ # End of a decimation loop. So, append accumulator value / decimation_factor to the output string
+ output_string.append(achan_accumulation_table[achan_number-1] * 10 / 32768 / decimation_factor)
+
+ elif (dec_count == 1) and (slist_pointer != 0):
+ # Decimation loop finished and NOT the first slist position
+ # Two LSBs carry information only for first slist posiiton, which this isn't. So, ...
+ # Just add value to the accumulator
+ achan_accumulation_table[achan_number] = result + achan_accumulation_table[achan_number]
+ achan_number += 1
+ # End of a decimation loop. So, append accumulator value / decimation_factor to the output string
+ output_string.append(achan_accumulation_table[achan_number-1] * 10 / 32768 / decimation_factor)
+
+ elif (dec_count != 1) and (slist_pointer == 0):
+ # Decimation loop NOT finished and first slist position
+ # Not the end of a decimation loop, but this is the first position in slist. So, ...
+ # Just strip two LSBs, preserving sign...
+ result = result >> 2
+ result = result << 2
+ # ...and add the value to the accumulator
+ achan_accumulation_table[achan_number] = result + achan_accumulation_table[achan_number]
+ achan_number += 1
+ else:
+ # Decimation loop NOT finished and NOT first slist position
+ # Nothing to do except add the value to the accumlator
+ achan_accumulation_table[achan_number] = result + achan_accumulation_table[achan_number]
+ achan_number += 1
+
+ # Get the next position in slist
+ slist_pointer += 1
+
+ if (slist_pointer + 1) > (len(slist)):
+ # End of a pass through slist items
+ if dec_count == 1:
+ # Get here if decimation loop has finished
+ dec_count = decimation_factor
+ # Reset analog channel accumulators to zero
+ achan_accumulation_table = [0] * len(achan_accumulation_table)
+ # Append digital inputs to output string
+ output_string.append(dig_in)
+
+ #TODO: insert formatting for force measurements. Maybe insert
+ #the actual conversion right when it's read in?
+
+ print(Format.pretty(output_string), end="\r")
+ output_string = []
+ else:
+ dec_count -= 1
+ slist_pointer = 0
+ achan_number = 0
+
+#Close the connection
+send_cmd("stop")
+time.sleep(1)
+ser.flushInput()
+print ("")
+print ("stopped")
+acquiring = False
+
+
+ser.close()
+SystemExit
diff --git a/code/Format.py b/code/Format.py
new file mode 100644
index 0000000..c6023b7
--- /dev/null
+++ b/code/Format.py
@@ -0,0 +1,61 @@
+#Force gauges calibration
+def force1(num):
+ return num * 1 + 0
+def force2(num):
+ return num * 1 + 0
+
+#Pressure gauges calibration
+def press1(num):
+ return num * 1 + 0
+def press2(num):
+ return num * 1 + 0
+
+def format(data):
+ out = [0,0,0,0]
+ #we only want to modify the first four elements. The rest are fine.
+ for i in range(4):
+ num = float(data[i])
+ #do conversion here
+ if i == 0:
+ num = force1(num)
+ if i == 1:
+ num = force2(num)
+ if i == 2:
+ num = press1(num)
+ if i == 3:
+ num = press2(num)
+
+ out[i] = num
+
+ #Append digital inputs and sample count
+ out.append(int(data[4]))
+ out.append(int(data[5]))
+
+ #Append all 4 temperature probe readings
+ out.append(float(data[6]))
+ out.append(float(data[7]))
+ out.append(float(data[8]))
+ out.append(float(data[9]))
+
+ return str(out).strip().strip("[]")
+
+
+def pretty(data):
+ out = ""
+ #we only want to modify the first four elements. The rest are fine.
+ for i in range(min(4,len(data))):
+ num = float(data[i])
+ #do conversion here
+ if i == 0:
+ num = '{: 3.3f} Kg\t'.format( force1(num))
+ if i == 1:
+ num = '{: 3.3f} Kg\t'.format( force2(num))
+ if i == 2:
+ num = '{: 3.3f} KPa\t'.format( press1(num))
+ #print("Formatting the third one!")
+ if i == 3:
+ num = '{: 3.3f} KPa\t'.format( press2(num))
+ #print("Formatting the fourth one!")
+ out =out + num
+
+ return str(out) + "\t".join(str(d) for d in data[4:])
diff --git a/code/Main.py b/code/Main.py
index 9a72b2d..6205732 100644
--- a/code/Main.py
+++ b/code/Main.py
@@ -5,12 +5,23 @@ import time
import configparser
import threading
import queue
+import spidev
-from sensors.Thermo_MAX31855 import thermo
+from sensors.Thermo_MAX31855 import Thermo
from sensors.dataq import dataq
+import Format
+
+spi = spidev.SpiDev()
+spi.open(0,0)
+spi.mode = 0
+spi.max_speed_hz = 500000
+
dataq = dataq()
-thermo = Thermo(1,0)
+thermo1 = Thermo(23, spi)
+thermo2 = Thermo(24, spi)
+thermo3 = Thermo(25, spi)
+thermo4 = Thermo(16, spi)
config = configparser.ConfigParser()
config.read("config.txt")
@@ -44,8 +55,12 @@ def read():
# pass
# #do nothing
- return dataq.out.get().append(thermo.read())
-
+ data = dataq.out.get()
+ data.append(thermo1.read())
+ data.append(thermo2.read())
+ data.append(thermo3.read())
+ data.append(thermo4.read())
+ return data
@@ -55,29 +70,32 @@ init()
# 'read button'
start_time = time.time()
+t = start_time
+
counter = 0
data = []
dataq.go()
-#this will eventually prevent button bouncing. currently does 5 secs of reading.
-#while time.time()-start_time <= 10 or not 'button pushed':
-while True:
- #time.sleep(0.001)
- d = read()
- #print(d[-1])
-
- if d[4] > 0: # If the digital out(the event buttons) get pushed, exit.
- break
-
- data.append(d)
- counter +=1
- if counter>= 10:
-
- "write data to file"
- f.writelines(str(i) + '\n' for i in data)
- counter = 0
- data = []
+try:
+ while True: #time.time()-start_time <= 10:
+ #time.sleep(0.001)
+ d = read()
+
+ #Every second, print some data to the file.
+ if time.time() - t > 1:
+ print(Format.pretty(d))
+ t = time.time()
+
+ data.append(d)
+ counter +=1
+ if counter>= 10:
+ #write data to file
+ f.writelines(str(i) + '\n' for i in data)
+ counter = 0
+ data = []
+except:
+ print("Exception caught!")
dataq.stop()
f.writelines(str(i) + '\n' for i in data)
-
+print("Exiting!")
f.close()
diff --git a/code/PostProcessing.py b/code/PostProcessing.py
index 6fcb0ef..6b1b0da 100644
--- a/code/PostProcessing.py
+++ b/code/PostProcessing.py
@@ -1,3 +1,4 @@
+import Format
infile_name = input("File to postprocess: ")
@@ -5,10 +6,14 @@ infile_name = input("File to postprocess: ")
infile = open(infile_name, mode='r')
outfile = open("post_" + infile_name, mode='w')
+line = infile.readline() #skip the first line - it has the labels.
line = infile.readline()
while line:
- outfile.write(line.strip().strip("[]")+"\n")
+ data = line.strip().strip("[]").split(",")
+
+ outfile.write(Format.format(data) + "\n")
line = infile.readline()
infile.close()
outfile.close()
+
diff --git a/code/sensors/Thermo_MAX31855.py b/code/sensors/Thermo_MAX31855.py
index 893a0aa..2716678 100644
--- a/code/sensors/Thermo_MAX31855.py
+++ b/code/sensors/Thermo_MAX31855.py
@@ -1,18 +1,21 @@
import time
import spidev
+import gpiozero
+class Thermo:
+ #def __init__(self, bus, device):
+ def __init__(self, pin, spi):
+ self.spi = spi
+
+
+ self.ce = gpiozero.DigitalOutputDevice(pin, active_high=False,initial_value=True)
-class Thermo_MAX31855:
- def __init__(self, bus, device):
- self.spi = spidev.SpiDev()
- self.spi.open(bus, device)
-
- self.spi.max_speed_hz = 5000000 #5GHz is the maximum frequency of these chip.
- self.spi.mode = 0
def read(self):
+ self.ce.on() #We control the chip enable pin manually.
data = self.spi.readbytes(4) #read 32 bits from the interface.
+ self.ce.off()
data = int.from_bytes(data, "big")
@@ -28,8 +31,8 @@ class Thermo_MAX31855:
#then we xor it with all 1's (to flip it from positive to negative) and add 1, then convert
# to a negative number within python (because python ints are weird).
# we then divide by 4, because the lcb of this int represents 0.25C.
- return (~((data >> 17) ^ 0b111111111111111)+1)/4
+ return (~((data >> 18) ^ 0b111111111111111)+1)/4
else:
#since it's positive, we don't convert to negative. We just separate
#out the temperature.
- return (data >> 17) / 4
+ return (data >> 18) / 4