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

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