Automatic commit. Thu Sep 13 12:00:07 WST 2012
[matches/honours.git] / research / TCS / interface.py
1 #!/usr/bin/python
2
3 # @file "interface.py"
4 # @author Sam Moore
5 # @purpose AVR Butterfly Datalogger control for Total Current Spectroscopy Measurements
6 #       The AVR responds to a limited number of RS232 commands to read ADC channels and set the DAC
7 #       This script can be used to control the DAC and monitor initial energy & sample current over RS232
8
9 import sys
10 import os
11 import time
12 import serial
13 import datetime
14
15 import odict
16 import Gnuplot, Gnuplot.funcutils
17 import subprocess
18
19 gnuplot = Gnuplot.Gnuplot()
20
21 # TODO: Insert variables for calibration purposes here.
22 calibrate = {
23         "ADC_Counts" : [2**10,2**10,2**10,2**10,2**10,2**10,2**10], # Maxed counts on ADC channels (10 bits = 2**10 = 1024)
24         "DAC_Counts" : 2**12, # Maxed counts on DAC channel (12 bits = 2**12 = 4096)
25
26         # Calibration data for DAC and ADC
27         "DAC" : None, 
28         "ADC" : [None, None, None, None, None, None, None, None],
29
30         # Data used for rough calibration if above data is not present
31         "Vref" : 3.3, # The output of the voltage regulator (Vref = Vcc) relative to signal ground
32         "ADC_Rin" : [None, None, None, None, 15000, 1100, 1100, 1100],
33         "ADC_Rvar" : [None, None, None, None, 1000, 5000, 10000, 50000],
34         "DAC_Gain" : 1
35 }
36
37 # TODO: Adjust aqcuisition parameters here
38 aquire = { "DAC_Sweep" : "0.0 + 10.0*int(step)", # DAC Sweep value (t is in STEPS, not seconds!)
39         "ADC_Averages" : 200,
40         #"ADC_Vi" : 5, # ADC channel to read back Vi (set by DAC) through
41         #"ADC_Is" : 4, # ADC channel to read back Is through
42         #"ADC_Ie" : 4, # ADC channel to read back Ie through
43         "DAC_Settle" : 0.0, # Time in seconds to wait for DAC to stabilise
44         #"response_wait" : 0.2, # Time to wait in seconds between sending data and reading back
45         "start_date" : None,
46         "open_files" : []
47 }
48
49 #Setup the serial connection parameters
50 ser = serial.Serial(
51         port="/dev/ttyUSB1", # Modify as needed (note: in linux need to run `sudo chmod a+rw /dev/ttyUSBX' to set permissions)
52
53         # Do not change the values below here (unless AVR butterfly is reprogrammed to use different values)
54         baudrate=4800,
55         parity="N",
56         stopbits=1,
57         bytesize=8,
58         timeout=None,
59         xonxoff=0,
60         rtscts=0
61 )
62 #Using an ordered dictionary, so results will be determined (or prompted for) in this order.
63 # Put things that are being changed a lot near the top of the list.
64 parameters = odict.odict([
65         ("Chamber Pressure" , None), # Chamber pressure now automatically determined
66         ("Venault Voltage" , None),
67         ("Title" , None),
68         ("Comment" , None),
69         ("Accelerating Voltage" , None),
70         ("Focus Voltage" , None),
71         ("Deflection Voltage" , None),
72         ("Initial Voltage" , None),
73         ("Heating Current" , None),
74         ("Heating Voltage (across filament)" , None),
75         ("Heating Voltage (across power supply)", None),
76         #("610B Zero" , None),
77         ("602 Zero" , None),
78         #("610B Scale" , None),
79         ("602 Scale" , None),
80         ("602 0.1 Battery" , None),
81         ("602 0.03 Battery" , None),
82         ("602 0.01 Battery" , None),
83         ("602 0.003 Battery" , None),
84         ("602 0.001 Battery" , None), 
85         ("ADC Regulator" , None),
86         ("Sample", None),
87         ("Sample Angle", None),
88         ("Data" , None),
89         ("Parameters last checked", None)
90 ])
91
92 def getTime():
93         return str(datetime.datetime.now()).split(" ")[1].split(".")[0].replace(":","")
94
95 def getDate():
96         return str(datetime.datetime.now()).split(" ")[0]
97
98 def getPressure():
99         p = subprocess.Popen("./pressure/get_pressure.sh", stdout=subprocess.PIPE)
100         return float(p.stdout.readline().strip(" \r\n\t"))
101         
102
103 # Used for when I press Control-C to stop things
104 def set_exit_handler(func):
105     if os.name == "nt":
106         try:
107             import win32api
108             win32api.SetConsoleCtrlHandler(func, True)
109         except ImportError:
110             version = ".".join(map(str, sys.version_info[:2]))
111             raise Exception("pywin32 not installed for Python " + version)
112     else:
113         import signal
114         signal.signal(signal.SIGTERM, func)
115         signal.signal(signal.SIGINT, func)
116
117 def killed_handler(signal, frame):
118         reason = ""
119         sys.stdout.write("\n# Reason for killing program? ")
120         reason = sys.stdin.readline().strip("\r\n ")
121         for out in aquire["open_files"]:
122                 sys.stdout.write("# Closing file " + str(out) + "\n")
123                 out.write("# Recieved KILL signal.\n# Reason: " + str(reason) + "\n")
124                 log_close(out)
125
126         
127
128 def cleanup():
129         for out in aquire["open_files"]:
130                 out.write("# Program exits.\n")
131                 log_close(out)
132
133 def log_open(a, b):
134         result = open(a, b,0)
135         if (b == "w"):
136                 result.write("# File opened at " + str(datetime.datetime.now()) + "\n")
137                 aquire["open_files"].append(result)
138         return result
139
140 def log_close(afile):
141         if (afile in aquire["open_files"]):
142                 afile.write("# File closed at " + str(datetime.datetime.now()) + "\n")
143                 aquire["open_files"].remove(afile)
144         
145         afile.close()
146
147
148 def init():
149         #import atexit
150         #atexit.register(cleanup)
151         set_exit_handler(killed_handler)
152         
153         aquire["start_date"] = getDate()
154
155
156
157         # Connect serial
158         ser.open()
159         ser.isOpen()
160 #       print("Waiting for \"# hello\" from device...")
161 #       while (ser.readline().strip("\r\n") != "# hello"):
162 #               pass
163         #while (ser.readline().strip("\r\n ") != "#"):
164         #       pass
165         #time.sleep(1.0)
166
167         ser.write("a "+str(aquire["ADC_Averages"]) + "\r\n")
168         ser.readline().strip("\r\n")
169         ser.readline().strip("\r\n")
170         ser.readline().strip("\r\n")
171         #print(ser.readline().strip("\r\n"))
172         #print(ser.readline().strip("\r\n"))
173         #print(ser.readline().strip("\r\n"))
174
175         #print("Writing config information to config.dat...")
176         #output = log_open("config.dat", "w", 1)
177
178         #output.write("# Initialise " + str(datetime.datetime.now()) + "\n")
179
180         #for field in calibrate:
181         #       output.write("# calibrate["+str(field)+"] = "+str(calibrate[field]) + "\n")
182         #output.write("\n")
183         #for field in aquire:
184         #       output.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
185
186         #output.write("# Ready " + str(datetime.datetime.now()) + "\n# EOF\n")
187         #output.close()
188
189 def main():
190
191         init()
192         
193         # I haven't ever used calibrated results, and yet this code is still here, why???
194         #if (loadCalibration_DAC() == False):
195         #       if (calibrateDAC() == False):
196         #               return -1
197         #if (loadCalibration_ADC(aquire["ADC_Is"]) == False):
198         #       if (calibrateADC_usingDAC(aquire["ADC_Is"], False) == False):
199         #               if (calibrateADC(aquire["ADC_Is"]) == False):
200         #                       return -1
201
202         #if (loadCalibration_ADC(aquire["ADC_Vi"]) == False):
203         #       if (calibrateADC_usingDAC(aquire["ADC_Vi"], True) == False):
204         #               if (calibrateADC(aquire["ADC_Vi"]) == False):
205         #                       return -1
206         
207
208         # Make directory for today, backup calibration files
209         os.system("mkdir -p " + getDate())
210         #os.system("cp *.dat " + getDate() +"/")
211
212         checkList()
213
214         
215         
216                 
217
218         # Experiment
219         # TODO: Modify data to record here
220         sweep = 1
221         #for i in range(0,5):
222         while True:
223                 os.system("mkdir -p " + getDate())
224                 record_data([5], getDate()+"/"+str(getTime())+".dat", None, 4001)
225                 sweep += 1
226         #setDAC(500)
227
228 def checkList():
229         try:
230                 input_file = log_open(getDate()+"/checklist", "r")
231         except:
232                 input_file = None
233
234         if (input_file != None):
235                 for line in input_file:
236                         k = line.split("=")
237                         item = None
238                         if (len(k) >= 2):
239                                 item = k[0].strip("# \r\n")
240                                 value = k[1].strip("# \r\n")
241
242                         if (item in parameters):
243                                 if item == "Chamber Pressure":
244                                         parameters[item] = getPressure()
245                                 else:
246                                         parameters[item] = value
247         
248                 #print("Checklist found. Overwrite? [Y/n]")
249                 response = "" #sys.stdin.readline().strip(" \r\n")
250                 if (response == "" or response == "y" or response == "Y"):
251                         input_file = log_open(getDate()+"/checklist.old", "w")
252                         for item in parameters:
253                                 input_file.write("# " + str(item) + " = " + str(parameters[item]) + "\n")
254                         input_file.write("\n")
255                         log_close(input_file)
256                         input_file = None
257         
258         if (input_file == None):
259                 for item in parameters:
260                         if item == "Parameters last checked":
261                                 continue
262                         if item == "Chamber Pressure":
263                                 #sys.stdout.write("\""+str(item)+"\" = " + str(parameters[item]) + " - get new pressure... ")
264                                 #parameters[item] = getPressure()
265                                 #sys.stdout.write(str(parameters[item]) + "\n")
266                                 continue
267
268                         sys.stdout.write("\""+str(item)+"\" = " + str(parameters[item]) + " New value?: ")
269                         response = sys.stdin.readline().strip("\r\n ")
270                         if (response == "!"):
271                                 break
272                         if (response != ""):
273                                 parameters[item] = response
274                         sys.stdout.write("\n")
275                 parameters["Parameters last checked"] = str(datetime.datetime.now())
276                         
277
278         checklist = log_open(getDate()+"/checklist", "w")
279         for item in parameters:
280                 checklist.write("# "+str(item) + " = " + str(parameters[item]) + "\n")
281                 #output_file.write("# "+str(item) + " = " + str(parameters[item]) + "\n")
282         log_close(checklist)
283         
284
285 def record_data(ADC_channels, output, pollTime = None, dac_max = None):
286         
287         if (output != None):
288                 gnuplot("set title \""+str(output)+"\"")
289                 output = [log_open(output, "w"), sys.stdout]
290
291         else:
292                 gnuplot("set title \"<No file>\"")
293                 output = [sys.stdout]
294
295         for field in aquire:
296                 for out in output:
297                         out.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
298         
299         for out in output:
300                 out.write("# Parameters:\n")
301
302         parameters["Chamber Pressure"] = getPressure() # Update chamber pressure
303
304         for field in parameters:
305                 for out in output:
306                         out.write("# "+str(field)+" = " + str(parameters[field]) + "\n")
307
308
309         start_time = time.time()
310         
311         gnuplot("set xlabel \"DAC (counts)\"")
312         gnuplot("set ylabel \"ADC (counts)\"")
313         
314         
315         for out in output:
316                 out.write("\n")
317                 out.write("# Experiment " + str(datetime.datetime.now()) + "\n")
318                 out.write("# Polling for " + str(pollTime) + "s.\n")
319                 out.write("\n")
320                 out.write("# Data:\n")
321                 out.write("# time\tDAC")
322                 for channel in ADC_channels:
323                         out.write("\tADC"+str(channel))
324                 out.write("\n")
325
326         step = 0
327         data = [] # Keep track of data for dynamic plotting
328         dacValue = int(eval(aquire["DAC_Sweep"]))
329         if (setDAC(dacValue) == False):
330                 setDAC(dacValue)
331         time.sleep(2.0)
332         while (pollTime == None or time.time() < start_time + pollTime):
333                 if (aquire["DAC_Sweep"] != None):
334                         nextDacValue = int(eval(aquire["DAC_Sweep"]))
335                         if (nextDacValue != dacValue):
336                                 dacValue = nextDacValue
337                                 if (dacValue < 0):
338                                         break
339                                 setDAC(dacValue)
340                         step += 1
341                 
342
343                 if (dac_max != None and dacValue >= dac_max):
344                         break
345
346                 measure_start = time.time()
347
348                 raw_adc = []
349
350                 for channel in ADC_channels:
351                         read = readADC(channel)
352                         if read == False:
353                                 for out in output:              
354                                         print("# Abort data collection due to failed ADC read")                                 
355                                         if out != sys.stdout:
356                                                 log_close(out)
357                                         return False
358                         raw_adc.append((channel, read[0], read[1]))
359
360                 end_time = time.time()
361
362                 for out in output:
363                         measure_time = measure_start + (end_time - measure_start)/2.0 - start_time
364                         out.write(str(measure_time))
365                         out.write("\t"+str(dacValue))
366                         data.append([measure_time, dacValue])
367
368                         for adc in raw_adc:
369                                 out.write("\t" + str(adc[1]) + "\t" + str(adc[2]))
370                                 data[len(data)-1].append(adc[1])
371                                 data[len(data)-1].append(adc[2])
372                         out.write("\n") 
373         
374                 #gnuplot("set yrange [0:1023]")
375                 #gnuplot("set xrange [0:4000]")
376                 gnuplot.plot(Gnuplot.Data(data, title="t = "+str(measure_time), with_="lp", using="2:3"))
377         for out in output:              
378                 if out != sys.stdout:
379                         log_close(out)
380         return True
381
382 def loadCalibration_ADC(channel):
383         try:
384                 input_file = log_open("calibrateADC"+str(channel)+".dat")
385         except:
386                 print("Couldn't find calibration file for ADC " + str(channel))
387                 return False
388         
389         calibrate["ADC"][channel] = []
390         for l in input_file:
391                 l = l.split("#")[0].strip("\r\n ")
392                 if (l == ""):
393                         continue
394                 else:
395                         split_line = l.split("\t")
396                         calibrate["ADC"][channel].append((float(split_line[0]), float(split_line[1])))
397         log_close(input_file)
398
399         if (len(calibrate["ADC"][channel]) <= 0):
400                 print("Empty calibration file for ADC " + str(channel))
401                 return False
402         return True
403
404 def loadCalibration_DAC():
405         try:
406                 input_file = log_open("calibrateDAC.dat")
407         except:
408                 print("Couldn't find calibration file for DAC")
409                 return False
410         
411         calibrate["DAC"] = []
412         for l in input_file:
413                 #print("Line is: "+str(l))
414                 l = l.split("#")[0].strip("\r\n ")
415                 if (l == ""):
416                         continue
417                 else:
418                         split_line = l.split("\t")
419                         if (len(split_line) >= 3):
420                                 calibrate["DAC"].append((int(split_line[0]), float(split_line[1]), float(split_line[2])))
421                         else:
422                                 calibrate["DAC"].append((int(split_line[0]), float(split_line[1])))
423
424
425         log_close(input_file)
426
427         if (len(calibrate["DAC"]) <= 0):
428                 print("Empty calibration file for DAC")
429                 return False
430         return True
431
432 def getADC_Voltage(channel, counts):
433         if (calibrate["ADC"][channel] == None or len(calibrate["ADC"][channel]) <= 0):
434                 if (calibrate["ADC_Rin"][channel] != None and calibrate["ADC_Rvar"][channel] != None):
435                         print("Warning: Using rough calibration for ADC"+str(channel) + " = " + str(counts))
436                         ratio = float(calibrate["ADC_Rin"][channel]) / (float(calibrate["ADC_Rin"][channel]) + float(calibrate["ADC_Rvar"][channel]))
437                         return ratio * (float(counts) / float(calibrate["ADC_Counts"][channel]) * Vref)
438                 else:
439                         print("Error: No calibration for ADC"+str(channel))
440                         return False
441
442         c = calibrate["ADC"][channel]
443         valueIndex = 1
444         for i in range(0, len(c)-1):
445                 if (c[i][0] <= counts and i + 1 < len(c)):
446                         grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
447                         value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
448                         return value
449
450         
451         print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
452
453         grad = (float(c[len(c)-1][valueIndex]) - float(c[len(c)-2][valueIndex])) / (float(c[len(c)-1][0]) -  float(c[len(c)-2][0]))
454         value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
455                 
456 def readADC(channel):
457         #for i in range(0, aquire["ADC_Averages"]):
458         #       ser.write("r "+str(channel)+"\r") # Send command to datalogger
459                 #time.sleep(aquire["response_wait"])
460         #       response = ser.readline().strip("#\r\n ")
461         #       if (response != "r "+str(channel)):
462         #               print("Received wierd response reading ADC ("+response+")")
463         #               return False                    
464                 #time.sleep(aquire["response_wait"])
465         #       values.append(int(ser.readline().strip("\r\n ")))
466         #       adc_sum += float(values[len(values)-1])
467         ser.write("r "+str(channel)+"\r")
468         response = ser.readline().strip("#\r\n")
469         if (response != "r "+str(channel)):
470                 print("Received wierd response reading ADC ("+response+")")
471                 return False                    
472         return ser.readline().strip("\r\n").split(" ")
473
474 def getDAC_Voltage(counts, gain = True):
475         if (calibrate["DAC"] == None or len(calibrate["DAC"]) <= 0):
476                 if (calibrate["DAC_Gain"] != None):
477                         print("Warning: Using rough calibration for DAC = " + str(counts))
478                         return float(counts) / float(calibrate["DAC_Counts"]) * float(calibrate["Vref"]) * float(calibrate["DAC_Gain"])
479                 else:
480                         print("Error: No calibrate for DAC")
481                         return False
482
483         valueIndex = 1
484         if (gain == False):
485                 valueIndex = 2
486                 if (len(calibrate["DAC"][0]) < 3):
487                         print("Error: No data for unamplified DAC")
488                         return False
489         
490         c = calibrate["DAC"]
491         if (len(c) == 1):
492                 print("Warning: Only one point in calibration data!")
493                 return float(c[0][valueIndex])
494         
495         for i in range(0, len(c)-1):
496                 if (c[i][0] <= counts and i + 1 < len(c)):
497                         grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
498                         value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
499                         return value
500
501         
502         print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
503
504         grad = (float(c[len(c)-1][valueIndex]) - float(c[len(c)-2][valueIndex])) / (float(c[len(c)-1][0]) -  float(c[len(c)-2][0]))
505         value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
506         return value
507
508
509 def setDAC(level):
510         
511         ser.write("d "+str(level)+"\r") 
512         
513         response = ser.readline().strip("#\r\n ")
514         if (response != "d "+str(level)):
515                 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
516                 return False
517         #time.sleep(aquire["response_wait"])
518         #time.sleep(aquire["DAC_Settle"])
519         #time.sleep(aquire["DAC_Settle"])
520         response = ser.readline().strip("#\r\n ")
521         if (response != "DAC "+str(level)):
522                 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
523                 return False
524         #time.sleep(aquire["response_wait"])
525         time.sleep(aquire["DAC_Settle"])
526                 
527
528 def calibrateADC_usingDAC(channel, gain = True):
529         if (calibrate["DAC"] == None):
530                 print("ERROR: DAC is not calibrated, can't use to calibrate ADC!")
531                 return False
532
533         calibrate["ADC"][channel] = []
534         outfile = log_open("calibrateADC"+str(channel)+".dat", "w")
535         outfile.write("# Calibrate ADC " + str(channel) + "\n")
536         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
537
538         print("Connect DAC output to ADC " + str(channel) + " and press enter\n")
539         sys.stdin.readline()
540         
541         for dac in calibrate["DAC"]:
542                 if (setDAC(dac[0]) == False):
543                         return False
544                 
545                 value = readADC(channel)
546                 if (value == False):
547                         return False
548                 canadd = (len(calibrate["ADC"][channel]) <= 0)
549                 if (canadd == False):
550                         canadd = True
551                         for adc in calibrate["ADC"][channel]:
552                                 if adc[0] == value[0]:
553                                         canadd = False
554                                         break
555
556                 if (canadd):            
557
558                         if gain:
559                                 input_value = dac[1]
560                         else:
561                                 input_value = dac[2]
562
563                         #input_value = getDAC_Voltage(dac[0], gain)
564                         if (input_value == False):
565                                 return False
566         
567                         outfile.write(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]) + "\n")
568                         print(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]))
569
570                         calibrate["ADC"][channel].append((value[0], input_value, value[1]))
571
572         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
573         log_close(outfile)
574         if (setDAC(0) == False):
575                 return False
576         if (len(calibrate["ADC"][channel]) <= 0):
577                 print("Error: No calibration points taken for ADC " + str(channel))
578                 return False
579         return True
580
581 def calibrateADC(channel):      
582         calibrate["ADC"][channel] = []
583         outfile = log_open("calibrateADC"+str(channel)+".dat", "w")
584         outfile.write("# Calibrate ADC " + str(channel) + "\n")
585         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
586
587         print("Calibrating ADC...\n")
588         print("Enter measured voltage, empty line stops.\n")
589
590         while True:
591                 read = sys.stdin.readline().strip("\r\n ")
592                 if (read == ""):
593                         break
594                 input_value = float(read)
595                 output_value = readADC(channel)
596                 if (output_value == False):
597                         return False
598                 
599                 calibrate["ADC"][channel].append((output_value[0], input_value))
600                 print(str(output_value[0]) + "\t" + str(input_value))
601                 
602         calibrate["ADC"][channel].sort(lambda e : e[1], reverse = False)
603         
604         
605         
606
607         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
608         log_close(outfile)
609         if (len(calibrate["ADC"][channel]) <= 0):
610                 print("Error: No calibration points taken for ADC " + str(channel))
611                 return False
612
613         return True
614
615 def calibrateDAC():
616         calibrate["DAC"] = []
617
618         outfile = log_open("calibrateDAC.dat", "w")
619         outfile.write("# Calibrate DAC\n")
620         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
621
622         print("Calibrating DAC...")
623         sys.stdout.write("Number of counts to increment per step: ")
624         read = sys.stdin.readline().strip("\r\n")
625         if (read == ""):
626                 return False
627         stepSize = max(1, int(read))
628         sys.stdout.write("\n")
629
630         outfile.write("# Increment by " + str(stepSize) + "\n")
631         print("Input measured DAC voltage for each level; empty input ends calibration.")
632         print("You may optionally input the DAC voltage before it is amplified too.")
633
634         level = 0
635         while (level < calibrate["DAC_Counts"]):
636
637                 setDAC(level)
638
639                 sys.stdout.write(str(level) + " ?")
640                 read = sys.stdin.readline().strip("\r\n ")
641                 if (read == ""):
642                         break
643                 else:
644                         read = read.split(" ")
645                         if (len(calibrate["DAC"]) > 0 and len(calibrate["DAC"][len(calibrate["DAC"])-1]) != len(read)):
646                                 print("Either give one value for EVERY point, or two values for EVERY point. Don't mess around.")
647                                 return False
648                         if (len(read) == 2):
649                                 calibrate["DAC"].append((level, float(read[0]), float(read[1])))
650                                 outfile.write(str(level) + "\t" + str(float(read[0])) + "\t" + str(float(read[1])) + "\n")
651                         else:
652                                 calibrate["DAC"].append((level, float(read[0])))
653                                 outfile.write(str(level) + "\t" + str(float(read[0])) + "\n")
654                 
655
656
657                 level += stepSize
658
659         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
660         log_close(outfile)
661         if (len(calibrate["DAC"]) <= 0):
662                 print("Error: No calibration points taken for DAC")
663                 return False
664         return setDAC(0)
665
666 # Run the main function
667 if __name__ == "__main__":
668         sys.exit(main())

UCC git Repository :: git.ucc.asn.au