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

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