Automatic commit. Wed Sep 19 12:00:12 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("set xlabel \"DAC (counts)\"")
377                 gnuplot("set ylabel \"Sample Current (ADC counts)\"")
378                 gnuplot.plot(Gnuplot.Data(data, title="t = "+str(measure_time), with_="lp", using="2:3"))
379         for out in output:              
380                 if out != sys.stdout:
381                         log_close(out)
382         return True
383
384 def loadCalibration_ADC(channel):
385         try:
386                 input_file = log_open("calibrateADC"+str(channel)+".dat")
387         except:
388                 print("Couldn't find calibration file for ADC " + str(channel))
389                 return False
390         
391         calibrate["ADC"][channel] = []
392         for l in input_file:
393                 l = l.split("#")[0].strip("\r\n ")
394                 if (l == ""):
395                         continue
396                 else:
397                         split_line = l.split("\t")
398                         calibrate["ADC"][channel].append((float(split_line[0]), float(split_line[1])))
399         log_close(input_file)
400
401         if (len(calibrate["ADC"][channel]) <= 0):
402                 print("Empty calibration file for ADC " + str(channel))
403                 return False
404         return True
405
406 def loadCalibration_DAC():
407         try:
408                 input_file = log_open("calibrateDAC.dat")
409         except:
410                 print("Couldn't find calibration file for DAC")
411                 return False
412         
413         calibrate["DAC"] = []
414         for l in input_file:
415                 #print("Line is: "+str(l))
416                 l = l.split("#")[0].strip("\r\n ")
417                 if (l == ""):
418                         continue
419                 else:
420                         split_line = l.split("\t")
421                         if (len(split_line) >= 3):
422                                 calibrate["DAC"].append((int(split_line[0]), float(split_line[1]), float(split_line[2])))
423                         else:
424                                 calibrate["DAC"].append((int(split_line[0]), float(split_line[1])))
425
426
427         log_close(input_file)
428
429         if (len(calibrate["DAC"]) <= 0):
430                 print("Empty calibration file for DAC")
431                 return False
432         return True
433
434 def getADC_Voltage(channel, counts):
435         if (calibrate["ADC"][channel] == None or len(calibrate["ADC"][channel]) <= 0):
436                 if (calibrate["ADC_Rin"][channel] != None and calibrate["ADC_Rvar"][channel] != None):
437                         print("Warning: Using rough calibration for ADC"+str(channel) + " = " + str(counts))
438                         ratio = float(calibrate["ADC_Rin"][channel]) / (float(calibrate["ADC_Rin"][channel]) + float(calibrate["ADC_Rvar"][channel]))
439                         return ratio * (float(counts) / float(calibrate["ADC_Counts"][channel]) * Vref)
440                 else:
441                         print("Error: No calibration for ADC"+str(channel))
442                         return False
443
444         c = calibrate["ADC"][channel]
445         valueIndex = 1
446         for i in range(0, len(c)-1):
447                 if (c[i][0] <= counts and i + 1 < len(c)):
448                         grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
449                         value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
450                         return value
451
452         
453         print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
454
455         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]))
456         value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
457                 
458 def readADC(channel):
459         #for i in range(0, aquire["ADC_Averages"]):
460         #       ser.write("r "+str(channel)+"\r") # Send command to datalogger
461                 #time.sleep(aquire["response_wait"])
462         #       response = ser.readline().strip("#\r\n ")
463         #       if (response != "r "+str(channel)):
464         #               print("Received wierd response reading ADC ("+response+")")
465         #               return False                    
466                 #time.sleep(aquire["response_wait"])
467         #       values.append(int(ser.readline().strip("\r\n ")))
468         #       adc_sum += float(values[len(values)-1])
469         ser.write("r "+str(channel)+"\r")
470         response = ser.readline().strip("#\r\n")
471         if (response != "r "+str(channel)):
472                 print("Received wierd response reading ADC ("+response+")")
473                 return False                    
474         return ser.readline().strip("\r\n").split(" ")
475
476 def getDAC_Voltage(counts, gain = True):
477         if (calibrate["DAC"] == None or len(calibrate["DAC"]) <= 0):
478                 if (calibrate["DAC_Gain"] != None):
479                         print("Warning: Using rough calibration for DAC = " + str(counts))
480                         return float(counts) / float(calibrate["DAC_Counts"]) * float(calibrate["Vref"]) * float(calibrate["DAC_Gain"])
481                 else:
482                         print("Error: No calibrate for DAC")
483                         return False
484
485         valueIndex = 1
486         if (gain == False):
487                 valueIndex = 2
488                 if (len(calibrate["DAC"][0]) < 3):
489                         print("Error: No data for unamplified DAC")
490                         return False
491         
492         c = calibrate["DAC"]
493         if (len(c) == 1):
494                 print("Warning: Only one point in calibration data!")
495                 return float(c[0][valueIndex])
496         
497         for i in range(0, len(c)-1):
498                 if (c[i][0] <= counts and i + 1 < len(c)):
499                         grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
500                         value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
501                         return value
502
503         
504         print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
505
506         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]))
507         value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
508         return value
509
510
511 def setDAC(level):
512         
513         ser.write("d "+str(level)+"\r") 
514         
515         response = ser.readline().strip("#\r\n ")
516         if (response != "d "+str(level)):
517                 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
518                 return False
519         #time.sleep(aquire["response_wait"])
520         #time.sleep(aquire["DAC_Settle"])
521         #time.sleep(aquire["DAC_Settle"])
522         response = ser.readline().strip("#\r\n ")
523         if (response != "DAC "+str(level)):
524                 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
525                 return False
526         #time.sleep(aquire["response_wait"])
527         time.sleep(aquire["DAC_Settle"])
528                 
529
530 def calibrateADC_usingDAC(channel, gain = True):
531         if (calibrate["DAC"] == None):
532                 print("ERROR: DAC is not calibrated, can't use to calibrate ADC!")
533                 return False
534
535         calibrate["ADC"][channel] = []
536         outfile = log_open("calibrateADC"+str(channel)+".dat", "w")
537         outfile.write("# Calibrate ADC " + str(channel) + "\n")
538         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
539
540         print("Connect DAC output to ADC " + str(channel) + " and press enter\n")
541         sys.stdin.readline()
542         
543         for dac in calibrate["DAC"]:
544                 if (setDAC(dac[0]) == False):
545                         return False
546                 
547                 value = readADC(channel)
548                 if (value == False):
549                         return False
550                 canadd = (len(calibrate["ADC"][channel]) <= 0)
551                 if (canadd == False):
552                         canadd = True
553                         for adc in calibrate["ADC"][channel]:
554                                 if adc[0] == value[0]:
555                                         canadd = False
556                                         break
557
558                 if (canadd):            
559
560                         if gain:
561                                 input_value = dac[1]
562                         else:
563                                 input_value = dac[2]
564
565                         #input_value = getDAC_Voltage(dac[0], gain)
566                         if (input_value == False):
567                                 return False
568         
569                         outfile.write(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]) + "\n")
570                         print(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]))
571
572                         calibrate["ADC"][channel].append((value[0], input_value, value[1]))
573
574         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
575         log_close(outfile)
576         if (setDAC(0) == False):
577                 return False
578         if (len(calibrate["ADC"][channel]) <= 0):
579                 print("Error: No calibration points taken for ADC " + str(channel))
580                 return False
581         return True
582
583 def calibrateADC(channel):      
584         calibrate["ADC"][channel] = []
585         outfile = log_open("calibrateADC"+str(channel)+".dat", "w")
586         outfile.write("# Calibrate ADC " + str(channel) + "\n")
587         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
588
589         print("Calibrating ADC...\n")
590         print("Enter measured voltage, empty line stops.\n")
591
592         while True:
593                 read = sys.stdin.readline().strip("\r\n ")
594                 if (read == ""):
595                         break
596                 input_value = float(read)
597                 output_value = readADC(channel)
598                 if (output_value == False):
599                         return False
600                 
601                 calibrate["ADC"][channel].append((output_value[0], input_value))
602                 print(str(output_value[0]) + "\t" + str(input_value))
603                 
604         calibrate["ADC"][channel].sort(lambda e : e[1], reverse = False)
605         
606         
607         
608
609         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
610         log_close(outfile)
611         if (len(calibrate["ADC"][channel]) <= 0):
612                 print("Error: No calibration points taken for ADC " + str(channel))
613                 return False
614
615         return True
616
617 def calibrateDAC():
618         calibrate["DAC"] = []
619
620         outfile = log_open("calibrateDAC.dat", "w")
621         outfile.write("# Calibrate DAC\n")
622         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
623
624         print("Calibrating DAC...")
625         sys.stdout.write("Number of counts to increment per step: ")
626         read = sys.stdin.readline().strip("\r\n")
627         if (read == ""):
628                 return False
629         stepSize = max(1, int(read))
630         sys.stdout.write("\n")
631
632         outfile.write("# Increment by " + str(stepSize) + "\n")
633         print("Input measured DAC voltage for each level; empty input ends calibration.")
634         print("You may optionally input the DAC voltage before it is amplified too.")
635
636         level = 0
637         while (level < calibrate["DAC_Counts"]):
638
639                 setDAC(level)
640
641                 sys.stdout.write(str(level) + " ?")
642                 read = sys.stdin.readline().strip("\r\n ")
643                 if (read == ""):
644                         break
645                 else:
646                         read = read.split(" ")
647                         if (len(calibrate["DAC"]) > 0 and len(calibrate["DAC"][len(calibrate["DAC"])-1]) != len(read)):
648                                 print("Either give one value for EVERY point, or two values for EVERY point. Don't mess around.")
649                                 return False
650                         if (len(read) == 2):
651                                 calibrate["DAC"].append((level, float(read[0]), float(read[1])))
652                                 outfile.write(str(level) + "\t" + str(float(read[0])) + "\t" + str(float(read[1])) + "\n")
653                         else:
654                                 calibrate["DAC"].append((level, float(read[0])))
655                                 outfile.write(str(level) + "\t" + str(float(read[0])) + "\n")
656                 
657
658
659                 level += stepSize
660
661         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
662         log_close(outfile)
663         if (len(calibrate["DAC"]) <= 0):
664                 print("Error: No calibration points taken for DAC")
665                 return False
666         return setDAC(0)
667
668 # Run the main function
669 if __name__ == "__main__":
670         sys.exit(main())

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