Automatic commit. Thu Sep 27 00: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 + 50.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/ttyUSB0", # 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         return 0.0
100         p = subprocess.Popen("./pressure/get_pressure.sh", stdout=subprocess.PIPE)
101         return float(p.stdout.readline().strip(" \r\n\t"))
102         
103
104 # Used for when I press Control-C to stop things
105 def set_exit_handler(func):
106     if os.name == "nt":
107         try:
108             import win32api
109             win32api.SetConsoleCtrlHandler(func, True)
110         except ImportError:
111             version = ".".join(map(str, sys.version_info[:2]))
112             raise Exception("pywin32 not installed for Python " + version)
113     else:
114         import signal
115         signal.signal(signal.SIGTERM, func)
116         signal.signal(signal.SIGINT, func)
117
118 def killed_handler(signal, frame):
119         reason = ""
120         sys.stdout.write("\n# Reason for killing program? ")
121         reason = sys.stdin.readline().strip("\r\n ")
122         for out in aquire["open_files"]:
123                 sys.stdout.write("# Closing file " + str(out) + "\n")
124                 out.write("# Recieved KILL signal.\n# Reason: " + str(reason) + "\n")
125                 log_close(out)
126
127         
128
129 def cleanup():
130         for out in aquire["open_files"]:
131                 out.write("# Program exits.\n")
132                 log_close(out)
133
134 def log_open(a, b):
135         result = open(a, b,0)
136         if (b == "w"):
137                 result.write("# File opened at " + str(datetime.datetime.now()) + "\n")
138                 aquire["open_files"].append(result)
139         return result
140
141 def log_close(afile):
142         if (afile in aquire["open_files"]):
143                 afile.write("# File closed at " + str(datetime.datetime.now()) + "\n")
144                 aquire["open_files"].remove(afile)
145         
146         afile.close()
147
148
149 def init():
150         #import atexit
151         #atexit.register(cleanup)
152         set_exit_handler(killed_handler)
153         
154         aquire["start_date"] = getDate()
155
156
157
158         # Connect serial
159         ser.open()
160         ser.isOpen()
161 #       print("Waiting for \"# hello\" from device...")
162 #       while (ser.readline().strip("\r\n") != "# hello"):
163 #               pass
164         #while (ser.readline().strip("\r\n ") != "#"):
165         #       pass
166         #time.sleep(1.0)
167
168         ser.write("a "+str(aquire["ADC_Averages"]) + "\r\n")
169         ser.readline().strip("\r\n")
170         ser.readline().strip("\r\n")
171         ser.readline().strip("\r\n")
172         #print(ser.readline().strip("\r\n"))
173         #print(ser.readline().strip("\r\n"))
174         #print(ser.readline().strip("\r\n"))
175
176         #print("Writing config information to config.dat...")
177         #output = log_open("config.dat", "w", 1)
178
179         #output.write("# Initialise " + str(datetime.datetime.now()) + "\n")
180
181         #for field in calibrate:
182         #       output.write("# calibrate["+str(field)+"] = "+str(calibrate[field]) + "\n")
183         #output.write("\n")
184         #for field in aquire:
185         #       output.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
186
187         #output.write("# Ready " + str(datetime.datetime.now()) + "\n# EOF\n")
188         #output.close()
189
190 def main():
191
192         init()
193         
194         # I haven't ever used calibrated results, and yet this code is still here, why???
195         #if (loadCalibration_DAC() == False):
196         #       if (calibrateDAC() == False):
197         #               return -1
198         #if (loadCalibration_ADC(aquire["ADC_Is"]) == False):
199         #       if (calibrateADC_usingDAC(aquire["ADC_Is"], False) == False):
200         #               if (calibrateADC(aquire["ADC_Is"]) == False):
201         #                       return -1
202
203         #if (loadCalibration_ADC(aquire["ADC_Vi"]) == False):
204         #       if (calibrateADC_usingDAC(aquire["ADC_Vi"], True) == False):
205         #               if (calibrateADC(aquire["ADC_Vi"]) == False):
206         #                       return -1
207         
208
209         # Make directory for today, backup calibration files
210         os.system("mkdir -p " + getDate())
211         #os.system("cp *.dat " + getDate() +"/")
212
213         checkList()
214
215         
216         
217                 
218
219         # Experiment
220         # TODO: Modify data to record here
221         sweep = 1
222         #for i in range(0,5):
223         while True:
224                 os.system("mkdir -p " + getDate())
225                 record_data([5], getDate()+"/"+str(getTime())+".dat", None, 4001)
226                 sweep += 1
227         #setDAC(500)
228
229 def checkList():
230         try:
231                 input_file = log_open(getDate()+"/checklist", "r")
232         except:
233                 input_file = None
234
235         if (input_file != None):
236                 for line in input_file:
237                         k = line.split("=")
238                         item = None
239                         if (len(k) >= 2):
240                                 item = k[0].strip("# \r\n")
241                                 value = k[1].strip("# \r\n")
242
243                         if (item in parameters):
244                                 if item == "Chamber Pressure":
245                                         parameters[item] = getPressure()
246                                 else:
247                                         parameters[item] = value
248         
249                 #print("Checklist found. Overwrite? [Y/n]")
250                 response = "" #sys.stdin.readline().strip(" \r\n")
251                 if (response == "" or response == "y" or response == "Y"):
252                         input_file = log_open(getDate()+"/checklist.old", "w")
253                         for item in parameters:
254                                 input_file.write("# " + str(item) + " = " + str(parameters[item]) + "\n")
255                         input_file.write("\n")
256                         log_close(input_file)
257                         input_file = None
258         
259         if (input_file == None):
260                 for item in parameters:
261                         if item == "Parameters last checked":
262                                 continue
263                         if item == "Chamber Pressure":
264                                 #sys.stdout.write("\""+str(item)+"\" = " + str(parameters[item]) + " - get new pressure... ")
265                                 #parameters[item] = getPressure()
266                                 #sys.stdout.write(str(parameters[item]) + "\n")
267                                 continue
268
269                         sys.stdout.write("\""+str(item)+"\" = " + str(parameters[item]) + " New value?: ")
270                         response = sys.stdin.readline().strip("\r\n ")
271                         if (response == "!"):
272                                 break
273                         if (response != ""):
274                                 parameters[item] = response
275                         sys.stdout.write("\n")
276                 parameters["Parameters last checked"] = str(datetime.datetime.now())
277                         
278
279         checklist = log_open(getDate()+"/checklist", "w")
280         for item in parameters:
281                 checklist.write("# "+str(item) + " = " + str(parameters[item]) + "\n")
282                 #output_file.write("# "+str(item) + " = " + str(parameters[item]) + "\n")
283         log_close(checklist)
284         
285
286 def record_data(ADC_channels, output, pollTime = None, dac_max = None):
287         
288         if (output != None):
289                 gnuplot("set title \""+str(output)+"\"")
290                 output = [log_open(output, "w"), sys.stdout]
291
292         else:
293                 gnuplot("set title \"<No file>\"")
294                 output = [sys.stdout]
295
296         for field in aquire:
297                 for out in output:
298                         out.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
299         
300         for out in output:
301                 out.write("# Parameters:\n")
302
303         #parameters["Chamber Pressure"] = getPressure() # Update chamber pressure
304
305         for field in parameters:
306                 for out in output:
307                         out.write("# "+str(field)+" = " + str(parameters[field]) + "\n")
308
309
310         start_time = time.time()
311         
312         gnuplot("set xlabel \"DAC (counts)\"")
313         gnuplot("set ylabel \"ADC (counts)\"")
314         
315         
316         for out in output:
317                 out.write("\n")
318                 out.write("# Experiment " + str(datetime.datetime.now()) + "\n")
319                 out.write("# Polling for " + str(pollTime) + "s.\n")
320                 out.write("\n")
321                 out.write("# Data:\n")
322                 out.write("# time\tDAC")
323                 for channel in ADC_channels:
324                         out.write("\tADC"+str(channel))
325                 out.write("\n")
326
327         step = 0
328         data = [] # Keep track of data for dynamic plotting
329         dacValue = int(eval(aquire["DAC_Sweep"]))
330         if (setDAC(dacValue) == False):
331                 setDAC(dacValue)
332         time.sleep(2.0)
333         while (pollTime == None or time.time() < start_time + pollTime):
334                 if (aquire["DAC_Sweep"] != None):
335                         nextDacValue = int(eval(aquire["DAC_Sweep"]))
336                         if (nextDacValue != dacValue):
337                                 dacValue = nextDacValue
338                                 if (dacValue < 0):
339                                         break
340                                 setDAC(dacValue)
341                         step += 1
342                 
343
344                 if (dac_max != None and dacValue >= dac_max):
345                         break
346
347                 measure_start = time.time()
348
349                 raw_adc = []
350
351                 for channel in ADC_channels:
352                         read = readADC(channel)
353                         if read == False:
354                                 for out in output:              
355                                         print("# Abort data collection due to failed ADC read")                                 
356                                         if out != sys.stdout:
357                                                 log_close(out)
358                                         return False
359                         raw_adc.append((channel, read[0], read[1]))
360
361                 end_time = time.time()
362
363                 for out in output:
364                         measure_time = measure_start + (end_time - measure_start)/2.0 - start_time
365                         out.write(str(measure_time))
366                         out.write("\t"+str(dacValue))
367                         data.append([measure_time, dacValue])
368
369                         for adc in raw_adc:
370                                 out.write("\t" + str(adc[1]) + "\t" + str(adc[2]))
371                                 data[len(data)-1].append(adc[1])
372                                 data[len(data)-1].append(adc[2])
373                         out.write("\n") 
374         
375                 #gnuplot("set yrange [0:1023]")
376                 #gnuplot("set xrange [0:4000]")
377                 gnuplot("set xlabel \"DAC (counts)\"")
378                 gnuplot("set ylabel \"Sample Current (ADC counts)\"")
379                 gnuplot.plot(Gnuplot.Data(data, title="t = "+str(measure_time), with_="lp", using="2:3"))
380         for out in output:              
381                 if out != sys.stdout:
382                         log_close(out)
383         return True
384
385 def loadCalibration_ADC(channel):
386         try:
387                 input_file = log_open("calibrateADC"+str(channel)+".dat")
388         except:
389                 print("Couldn't find calibration file for ADC " + str(channel))
390                 return False
391         
392         calibrate["ADC"][channel] = []
393         for l in input_file:
394                 l = l.split("#")[0].strip("\r\n ")
395                 if (l == ""):
396                         continue
397                 else:
398                         split_line = l.split("\t")
399                         calibrate["ADC"][channel].append((float(split_line[0]), float(split_line[1])))
400         log_close(input_file)
401
402         if (len(calibrate["ADC"][channel]) <= 0):
403                 print("Empty calibration file for ADC " + str(channel))
404                 return False
405         return True
406
407 def loadCalibration_DAC():
408         try:
409                 input_file = log_open("calibrateDAC.dat")
410         except:
411                 print("Couldn't find calibration file for DAC")
412                 return False
413         
414         calibrate["DAC"] = []
415         for l in input_file:
416                 #print("Line is: "+str(l))
417                 l = l.split("#")[0].strip("\r\n ")
418                 if (l == ""):
419                         continue
420                 else:
421                         split_line = l.split("\t")
422                         if (len(split_line) >= 3):
423                                 calibrate["DAC"].append((int(split_line[0]), float(split_line[1]), float(split_line[2])))
424                         else:
425                                 calibrate["DAC"].append((int(split_line[0]), float(split_line[1])))
426
427
428         log_close(input_file)
429
430         if (len(calibrate["DAC"]) <= 0):
431                 print("Empty calibration file for DAC")
432                 return False
433         return True
434
435 def getADC_Voltage(channel, counts):
436         if (calibrate["ADC"][channel] == None or len(calibrate["ADC"][channel]) <= 0):
437                 if (calibrate["ADC_Rin"][channel] != None and calibrate["ADC_Rvar"][channel] != None):
438                         print("Warning: Using rough calibration for ADC"+str(channel) + " = " + str(counts))
439                         ratio = float(calibrate["ADC_Rin"][channel]) / (float(calibrate["ADC_Rin"][channel]) + float(calibrate["ADC_Rvar"][channel]))
440                         return ratio * (float(counts) / float(calibrate["ADC_Counts"][channel]) * Vref)
441                 else:
442                         print("Error: No calibration for ADC"+str(channel))
443                         return False
444
445         c = calibrate["ADC"][channel]
446         valueIndex = 1
447         for i in range(0, len(c)-1):
448                 if (c[i][0] <= counts and i + 1 < len(c)):
449                         grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
450                         value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
451                         return value
452
453         
454         print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
455
456         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]))
457         value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
458                 
459 def readADC(channel):
460         #for i in range(0, aquire["ADC_Averages"]):
461         #       ser.write("r "+str(channel)+"\r") # Send command to datalogger
462                 #time.sleep(aquire["response_wait"])
463         #       response = ser.readline().strip("#\r\n ")
464         #       if (response != "r "+str(channel)):
465         #               print("Received wierd response reading ADC ("+response+")")
466         #               return False                    
467                 #time.sleep(aquire["response_wait"])
468         #       values.append(int(ser.readline().strip("\r\n ")))
469         #       adc_sum += float(values[len(values)-1])
470         ser.write("r "+str(channel)+"\r")
471         response = ser.readline().strip("#\r\n")
472         if (response != "r "+str(channel)):
473                 print("Received wierd response reading ADC ("+response+")")
474                 return False                    
475         return ser.readline().strip("\r\n").split(" ")
476
477 def getDAC_Voltage(counts, gain = True):
478         if (calibrate["DAC"] == None or len(calibrate["DAC"]) <= 0):
479                 if (calibrate["DAC_Gain"] != None):
480                         print("Warning: Using rough calibration for DAC = " + str(counts))
481                         return float(counts) / float(calibrate["DAC_Counts"]) * float(calibrate["Vref"]) * float(calibrate["DAC_Gain"])
482                 else:
483                         print("Error: No calibrate for DAC")
484                         return False
485
486         valueIndex = 1
487         if (gain == False):
488                 valueIndex = 2
489                 if (len(calibrate["DAC"][0]) < 3):
490                         print("Error: No data for unamplified DAC")
491                         return False
492         
493         c = calibrate["DAC"]
494         if (len(c) == 1):
495                 print("Warning: Only one point in calibration data!")
496                 return float(c[0][valueIndex])
497         
498         for i in range(0, len(c)-1):
499                 if (c[i][0] <= counts and i + 1 < len(c)):
500                         grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
501                         value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
502                         return value
503
504         
505         print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
506
507         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]))
508         value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
509         return value
510
511
512 def setDAC(level):
513         
514         ser.write("d "+str(level)+"\r") 
515         
516         response = ser.readline().strip("#\r\n ")
517         if (response != "d "+str(level)):
518                 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
519                 return False
520         #time.sleep(aquire["response_wait"])
521         #time.sleep(aquire["DAC_Settle"])
522         #time.sleep(aquire["DAC_Settle"])
523         response = ser.readline().strip("#\r\n ")
524         if (response != "DAC "+str(level)):
525                 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
526                 return False
527         #time.sleep(aquire["response_wait"])
528         time.sleep(aquire["DAC_Settle"])
529                 
530
531 def calibrateADC_usingDAC(channel, gain = True):
532         if (calibrate["DAC"] == None):
533                 print("ERROR: DAC is not calibrated, can't use to calibrate ADC!")
534                 return False
535
536         calibrate["ADC"][channel] = []
537         outfile = log_open("calibrateADC"+str(channel)+".dat", "w")
538         outfile.write("# Calibrate ADC " + str(channel) + "\n")
539         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
540
541         print("Connect DAC output to ADC " + str(channel) + " and press enter\n")
542         sys.stdin.readline()
543         
544         for dac in calibrate["DAC"]:
545                 if (setDAC(dac[0]) == False):
546                         return False
547                 
548                 value = readADC(channel)
549                 if (value == False):
550                         return False
551                 canadd = (len(calibrate["ADC"][channel]) <= 0)
552                 if (canadd == False):
553                         canadd = True
554                         for adc in calibrate["ADC"][channel]:
555                                 if adc[0] == value[0]:
556                                         canadd = False
557                                         break
558
559                 if (canadd):            
560
561                         if gain:
562                                 input_value = dac[1]
563                         else:
564                                 input_value = dac[2]
565
566                         #input_value = getDAC_Voltage(dac[0], gain)
567                         if (input_value == False):
568                                 return False
569         
570                         outfile.write(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]) + "\n")
571                         print(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]))
572
573                         calibrate["ADC"][channel].append((value[0], input_value, value[1]))
574
575         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
576         log_close(outfile)
577         if (setDAC(0) == False):
578                 return False
579         if (len(calibrate["ADC"][channel]) <= 0):
580                 print("Error: No calibration points taken for ADC " + str(channel))
581                 return False
582         return True
583
584 def calibrateADC(channel):      
585         calibrate["ADC"][channel] = []
586         outfile = log_open("calibrateADC"+str(channel)+".dat", "w")
587         outfile.write("# Calibrate ADC " + str(channel) + "\n")
588         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
589
590         print("Calibrating ADC...\n")
591         print("Enter measured voltage, empty line stops.\n")
592
593         while True:
594                 read = sys.stdin.readline().strip("\r\n ")
595                 if (read == ""):
596                         break
597                 input_value = float(read)
598                 output_value = readADC(channel)
599                 if (output_value == False):
600                         return False
601                 
602                 calibrate["ADC"][channel].append((output_value[0], input_value))
603                 print(str(output_value[0]) + "\t" + str(input_value))
604                 
605         calibrate["ADC"][channel].sort(lambda e : e[1], reverse = False)
606         
607         
608         
609
610         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
611         log_close(outfile)
612         if (len(calibrate["ADC"][channel]) <= 0):
613                 print("Error: No calibration points taken for ADC " + str(channel))
614                 return False
615
616         return True
617
618 def calibrateDAC():
619         calibrate["DAC"] = []
620
621         outfile = log_open("calibrateDAC.dat", "w")
622         outfile.write("# Calibrate DAC\n")
623         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
624
625         print("Calibrating DAC...")
626         sys.stdout.write("Number of counts to increment per step: ")
627         read = sys.stdin.readline().strip("\r\n")
628         if (read == ""):
629                 return False
630         stepSize = max(1, int(read))
631         sys.stdout.write("\n")
632
633         outfile.write("# Increment by " + str(stepSize) + "\n")
634         print("Input measured DAC voltage for each level; empty input ends calibration.")
635         print("You may optionally input the DAC voltage before it is amplified too.")
636
637         level = 0
638         while (level < calibrate["DAC_Counts"]):
639
640                 setDAC(level)
641
642                 sys.stdout.write(str(level) + " ?")
643                 read = sys.stdin.readline().strip("\r\n ")
644                 if (read == ""):
645                         break
646                 else:
647                         read = read.split(" ")
648                         if (len(calibrate["DAC"]) > 0 and len(calibrate["DAC"][len(calibrate["DAC"])-1]) != len(read)):
649                                 print("Either give one value for EVERY point, or two values for EVERY point. Don't mess around.")
650                                 return False
651                         if (len(read) == 2):
652                                 calibrate["DAC"].append((level, float(read[0]), float(read[1])))
653                                 outfile.write(str(level) + "\t" + str(float(read[0])) + "\t" + str(float(read[1])) + "\n")
654                         else:
655                                 calibrate["DAC"].append((level, float(read[0])))
656                                 outfile.write(str(level) + "\t" + str(float(read[0])) + "\n")
657                 
658
659
660                 level += stepSize
661
662         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
663         log_close(outfile)
664         if (len(calibrate["DAC"]) <= 0):
665                 print("Error: No calibration points taken for DAC")
666                 return False
667         return setDAC(0)
668
669 # Run the main function
670 if __name__ == "__main__":
671         sys.exit(main())

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