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

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