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

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