Automatic commit. Mon Jul 30 14: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
16
17 # TODO: Insert variables for calibration purposes here.
18 calibrate = {
19         "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)
20         "DAC_Counts" : 2**12, # Maxed counts on DAC channel (12 bits = 2**12 = 4096)
21
22         # Calibration data for DAC and ADC
23         "DAC" : None, 
24         "ADC" : [None, None, None, None, None, None, None, None],
25
26         # Data used for rough calibration if above data is not present
27         "Vref" : 3.3, # The output of the voltage regulator (Vref = Vcc) relative to signal ground
28         "ADC_Rin" : [None, None, None, None, 15000, 1100, 1100, 1100],
29         "ADC_Rvar" : [None, None, None, None, 1000, 5000, 10000, 50000],
30         "DAC_Gain" : 1
31 }
32
33 # TODO: Adjust aqcuisition parameters here
34 aquire = { "DAC_Sweep" : "2200.0 - 50.0*int(step/1000)", # DAC Sweep value (t is in STEPS, not seconds!)
35         "ADC_Averages" : 200,
36         "ADC_Vi" : 5, # ADC channel to read back Vi (set by DAC) through
37         "ADC_Is" : 4, # ADC channel to read back Is through
38         "ADC_Ie" : 4, # ADC channel to read back Ie through
39         "DAC_Settle" : 0.0, # Time in seconds to wait for DAC to stabilise
40         #"response_wait" : 0.2, # Time to wait in seconds between sending data and reading back
41         "start_date" : None
42 }
43
44 #Setup the serial connection parameters
45 ser = serial.Serial(
46         port="/dev/ttyUSB0", # Modify as needed (note: in linux need to run `sudo chmod a+rw /dev/ttyUSBX' to set permissions)
47
48         # Do not change the values below here (unless AVR butterfly is reprogrammed to use different values)
49         baudrate=4800,
50         parity="N",
51         stopbits=1,
52         bytesize=8,
53         timeout=None,
54         xonxoff=0,
55         rtscts=0
56 )
57
58 parameters = {
59         "Accelerating Voltage" : None,
60         "Focus Voltage" : None,
61         "Deflection Voltage" : None,
62         "Venault Voltage" : None,
63         "Initial Voltage" : None,
64         "Heating Current" : None,
65         "Heating Voltage" : None,
66         "Chamber Pressure" : None,
67         "602 0.1 Battery" : None,
68         "602 0.03 Battery" : None,
69         "602 0.01 Battery" : None,
70         "602 0.003 Battery" : None,
71         "602 0.001 Battery" : None
72 }
73
74 def getTime():
75         return str(datetime.datetime.now()).split(" ")[1].split(".")[0].replace(":","")
76
77 def getDate():
78         return str(datetime.datetime.now()).split(" ")[0]
79
80 def init():
81
82         
83         aquire["start_date"] = getDate()
84
85
86
87         # Connect serial
88         ser.open()
89         ser.isOpen()
90 #       print("Waiting for \"# hello\" from device...")
91 #       while (ser.readline().strip("\r\n") != "# hello"):
92 #               pass
93         #while (ser.readline().strip("\r\n ") != "#"):
94         #       pass
95         time.sleep(1.0)
96
97         ser.write("a "+str(aquire["ADC_Averages"]) + "\r\n")
98         print(ser.readline().strip("\r\n"))
99         print(ser.readline().strip("\r\n"))
100         print(ser.readline().strip("\r\n"))
101
102         print("Writing config information to config.dat...")
103         output = open("config.dat", "w", 1)
104
105         output.write("# Initialise " + str(datetime.datetime.now()) + "\n")
106
107         for field in calibrate:
108                 output.write("# calibrate["+str(field)+"] = "+str(calibrate[field]) + "\n")
109         output.write("\n")
110         for field in aquire:
111                 output.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
112
113         output.write("# Ready " + str(datetime.datetime.now()) + "\n# EOF\n")
114         output.close()
115
116 def main():
117
118         init()
119         
120         if (loadCalibration_DAC() == False):
121                 if (calibrateDAC() == False):
122                         return -1
123         if (loadCalibration_ADC(aquire["ADC_Is"]) == False):
124                 if (calibrateADC_usingDAC(aquire["ADC_Is"], False) == False):
125                         if (calibrateADC(aquire["ADC_Is"]) == False):
126                                 return -1
127
128         if (loadCalibration_ADC(aquire["ADC_Vi"]) == False):
129                 if (calibrateADC_usingDAC(aquire["ADC_Vi"], True) == False):
130                         if (calibrateADC(aquire["ADC_Vi"]) == False):
131                                 return -1
132         
133
134         # Make directory for today, backup calibration files
135         os.system("mkdir -p " + getDate())
136         os.system("cp *.dat " + getDate() +"/")
137
138         #checkList()
139
140         
141         
142
143         # Experiment
144         # TODO: Modify data to record here
145         sweep = 1
146         #record_data([4, 5], getDate()+"/"+str(getTime())+".dat", None, None, "Measure emission&sample current varying with time, constant initial energy.")
147         while True:
148                 os.system("mkdir -p " + getDate())
149                 record_data([4, 5], getDate()+"/"+str(getTime())+".dat", None, 2300, "Measure Ie and Is .Sweep DOWN " + str(sweep) + " (started on " + aquire["start_date"]+")")
150                 sweep += 1
151         
152
153 def checkList():
154         
155         output = open(getDate()+"/checklist", "w", 0)
156         for item in parameters:
157                 sys.stdout.write("Enter value for \""+str(item)+"\": ")
158                 parameters[item] = sys.stdin.readline().strip("\r\n ")
159                 sys.stdout.write("\n")
160                 output.write(str(parameters[item]) + "\n")
161
162
163 def record_data(ADC_channels, output, pollTime = None, dac_max = None, comment = None):
164         if (output != None):
165                 output = [open(output, "w", 0), sys.stdout]
166                 if (comment == None):
167                         print("Enter a comment for the experiment.")
168                         comment = sys.stdin.readline().strip("\r\n ")
169                 output[0].write("# Comment: "+str(comment)+"\n")
170         else:
171                 output = [sys.stdout]
172
173         start_time = time.time()
174         
175         for out in output:
176                 out.write("# Experiment " + str(datetime.datetime.now()) + "\n")
177                 out.write("# Polling for " + str(pollTime) + "s.\n")
178                 out.write("# DAC = " + str(aquire["DAC_Sweep"]) + "\n")
179                 out.write("# Data:\n")
180                 out.write("# time\tDAC")
181                 for channel in ADC_channels:
182                         out.write("\tADC"+str(channel))
183                 out.write("\n")
184
185         step = 0
186         dacValue = int(eval(aquire["DAC_Sweep"]))
187         if (setDAC(dacValue) == False):
188                 setDAC(dacValue)
189         while (pollTime == None or time.time() < start_time + pollTime):
190                 if (aquire["DAC_Sweep"] != None):
191                         nextDacValue = int(eval(aquire["DAC_Sweep"]))
192                         if (nextDacValue != dacValue):
193                                 dacValue = nextDacValue
194                                 if (dacValue < 0):
195                                         break
196                                 setDAC(dacValue)
197                         step += 1
198                 
199
200                 if (dac_max != None and dacValue >= dac_max):
201                         break
202
203                 measure_start = time.time()
204
205                 raw_adc = []
206
207                 for channel in ADC_channels:
208                         read = readADC(channel)
209                         if read == False:
210                                 print("Abort data collection")
211                                 return False
212                         raw_adc.append((channel, read[0], read[1]))
213
214                 end_time = time.time()
215
216                 for out in output:
217                         out.write(str((measure_start + (end_time - measure_start)/2.0 - start_time)))
218                         out.write("\t"+str(dacValue))
219                         for adc in raw_adc:
220                                 out.write("\t" + str(adc[1]) + "\t" + str(adc[2]))
221                         out.write("\n") 
222         
223                 
224         for out in output:              
225                 if out != sys.stdout:
226                         out.close()
227         return True
228
229 def loadCalibration_ADC(channel):
230         try:
231                 input_file = open("calibrateADC"+str(channel)+".dat")
232         except:
233                 print("Couldn't find calibration file for ADC " + str(channel))
234                 return False
235         
236         calibrate["ADC"][channel] = []
237         for l in input_file:
238                 l = l.split("#")[0].strip("\r\n ")
239                 if (l == ""):
240                         continue
241                 else:
242                         split_line = l.split("\t")
243                         calibrate["ADC"][channel].append((float(split_line[0]), float(split_line[1])))
244         input_file.close()
245
246         if (len(calibrate["ADC"][channel]) <= 0):
247                 print("Empty calibration file for ADC " + str(channel))
248                 return False
249         return True
250
251 def loadCalibration_DAC():
252         try:
253                 input_file = open("calibrateDAC.dat")
254         except:
255                 print("Couldn't find calibration file for DAC")
256                 return False
257         
258         calibrate["DAC"] = []
259         for l in input_file:
260                 #print("Line is: "+str(l))
261                 l = l.split("#")[0].strip("\r\n ")
262                 if (l == ""):
263                         continue
264                 else:
265                         split_line = l.split("\t")
266                         if (len(split_line) >= 3):
267                                 calibrate["DAC"].append((int(split_line[0]), float(split_line[1]), float(split_line[2])))
268                         else:
269                                 calibrate["DAC"].append((int(split_line[0]), float(split_line[1])))
270
271
272         input_file.close()
273
274         if (len(calibrate["DAC"]) <= 0):
275                 print("Empty calibration file for DAC")
276                 return False
277         return True
278
279 def getADC_Voltage(channel, counts):
280         if (calibrate["ADC"][channel] == None or len(calibrate["ADC"][channel]) <= 0):
281                 if (calibrate["ADC_Rin"][channel] != None and calibrate["ADC_Rvar"][channel] != None):
282                         print("Warning: Using rough calibration for ADC"+str(channel) + " = " + str(counts))
283                         ratio = float(calibrate["ADC_Rin"][channel]) / (float(calibrate["ADC_Rin"][channel]) + float(calibrate["ADC_Rvar"][channel]))
284                         return ratio * (float(counts) / float(calibrate["ADC_Counts"][channel]) * Vref)
285                 else:
286                         print("Error: No calibration for ADC"+str(channel))
287                         return False
288
289         c = calibrate["ADC"][channel]
290         valueIndex = 1
291         for i in range(0, len(c)-1):
292                 if (c[i][0] <= counts and i + 1 < len(c)):
293                         grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
294                         value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
295                         return value
296
297         
298         print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
299
300         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]))
301         value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
302                 
303 def readADC(channel):
304         #for i in range(0, aquire["ADC_Averages"]):
305         #       ser.write("r "+str(channel)+"\r") # Send command to datalogger
306                 #time.sleep(aquire["response_wait"])
307         #       response = ser.readline().strip("#\r\n ")
308         #       if (response != "r "+str(channel)):
309         #               print("Received wierd response reading ADC ("+response+")")
310         #               return False                    
311                 #time.sleep(aquire["response_wait"])
312         #       values.append(int(ser.readline().strip("\r\n ")))
313         #       adc_sum += float(values[len(values)-1])
314         ser.write("r "+str(channel)+"\r")
315         response = ser.readline().strip("#\r\n")
316         if (response != "r "+str(channel)):
317                 print("Received wierd response reading ADC ("+response+")")
318                 return False                    
319         return ser.readline().strip("\r\n").split(" ")
320
321 def getDAC_Voltage(counts, gain = True):
322         if (calibrate["DAC"] == None or len(calibrate["DAC"]) <= 0):
323                 if (calibrate["DAC_Gain"] != None):
324                         print("Warning: Using rough calibration for DAC = " + str(counts))
325                         return float(counts) / float(calibrate["DAC_Counts"]) * float(calibrate["Vref"]) * float(calibrate["DAC_Gain"])
326                 else:
327                         print("Error: No calibrate for DAC")
328                         return False
329
330         valueIndex = 1
331         if (gain == False):
332                 valueIndex = 2
333                 if (len(calibrate["DAC"][0]) < 3):
334                         print("Error: No data for unamplified DAC")
335                         return False
336         
337         c = calibrate["DAC"]
338         if (len(c) == 1):
339                 print("Warning: Only one point in calibration data!")
340                 return float(c[0][valueIndex])
341         
342         for i in range(0, len(c)-1):
343                 if (c[i][0] <= counts and i + 1 < len(c)):
344                         grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
345                         value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
346                         return value
347
348         
349         print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
350
351         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]))
352         value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
353         return value
354
355
356 def setDAC(level):
357         
358         ser.write("d "+str(level)+"\r") 
359         
360         response = ser.readline().strip("#\r\n ")
361         if (response != "d "+str(level)):
362                 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
363                 return False
364         #time.sleep(aquire["response_wait"])
365         #time.sleep(aquire["DAC_Settle"])
366         #time.sleep(aquire["DAC_Settle"])
367         response = ser.readline().strip("#\r\n ")
368         if (response != "DAC "+str(level)):
369                 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
370                 return False
371         #time.sleep(aquire["response_wait"])
372         time.sleep(aquire["DAC_Settle"])
373                 
374
375 def calibrateADC_usingDAC(channel, gain = True):
376         if (calibrate["DAC"] == None):
377                 print("ERROR: DAC is not calibrated, can't use to calibrate ADC!")
378                 return False
379
380         calibrate["ADC"][channel] = []
381         outfile = open("calibrateADC"+str(channel)+".dat", "w", 1)
382         outfile.write("# Calibrate ADC " + str(channel) + "\n")
383         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
384
385         print("Connect DAC output to ADC " + str(channel) + " and press enter\n")
386         sys.stdin.readline()
387         
388         for dac in calibrate["DAC"]:
389                 if (setDAC(dac[0]) == False):
390                         return False
391                 
392                 value = readADC(channel)
393                 if (value == False):
394                         return False
395                 canadd = (len(calibrate["ADC"][channel]) <= 0)
396                 if (canadd == False):
397                         canadd = True
398                         for adc in calibrate["ADC"][channel]:
399                                 if adc[0] == value[0]:
400                                         canadd = False
401                                         break
402
403                 if (canadd):            
404
405                         if gain:
406                                 input_value = dac[1]
407                         else:
408                                 input_value = dac[2]
409
410                         #input_value = getDAC_Voltage(dac[0], gain)
411                         if (input_value == False):
412                                 return False
413         
414                         outfile.write(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]) + "\n")
415                         print(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]))
416
417                         calibrate["ADC"][channel].append((value[0], input_value, value[1]))
418
419         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
420         outfile.close()
421         if (setDAC(0) == False):
422                 return False
423         if (len(calibrate["ADC"][channel]) <= 0):
424                 print("Error: No calibration points taken for ADC " + str(channel))
425                 return False
426         return True
427
428 def calibrateADC(channel):      
429         calibrate["ADC"][channel] = []
430         outfile = open("calibrateADC"+str(channel)+".dat", "w", 1)
431         outfile.write("# Calibrate ADC " + str(channel) + "\n")
432         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
433
434         print("Calibrating ADC...\n")
435         print("Enter measured voltage, empty line stops.\n")
436
437         while True:
438                 read = sys.stdin.readline().strip("\r\n ")
439                 if (read == ""):
440                         break
441                 input_value = float(read)
442                 output_value = readADC(channel)
443                 if (output_value == False):
444                         return False
445                 
446                 calibrate["ADC"][channel].append((output_value[0], input_value))
447                 print(str(output_value[0]) + "\t" + str(input_value))
448                 
449         calibrate["ADC"][channel].sort(lambda e : e[1], reverse = False)
450         
451         
452         
453
454         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
455         outfile.close()
456         if (len(calibrate["ADC"][channel]) <= 0):
457                 print("Error: No calibration points taken for ADC " + str(channel))
458                 return False
459
460         return True
461
462 def calibrateDAC():
463         calibrate["DAC"] = []
464
465         outfile = open("calibrateDAC.dat", "w", 1)
466         outfile.write("# Calibrate DAC\n")
467         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
468
469         print("Calibrating DAC...")
470         sys.stdout.write("Number of counts to increment per step: ")
471         read = sys.stdin.readline().strip("\r\n")
472         if (read == ""):
473                 return False
474         stepSize = max(1, int(read))
475         sys.stdout.write("\n")
476
477         outfile.write("# Increment by " + str(stepSize) + "\n")
478         print("Input measured DAC voltage for each level; empty input ends calibration.")
479         print("You may optionally input the DAC voltage before it is amplified too.")
480
481         level = 0
482         while (level < calibrate["DAC_Counts"]):
483
484                 setDAC(level)
485
486                 sys.stdout.write(str(level) + " ?")
487                 read = sys.stdin.readline().strip("\r\n ")
488                 if (read == ""):
489                         break
490                 else:
491                         read = read.split(" ")
492                         if (len(calibrate["DAC"]) > 0 and len(calibrate["DAC"][len(calibrate["DAC"])-1]) != len(read)):
493                                 print("Either give one value for EVERY point, or two values for EVERY point. Don't mess around.")
494                                 return False
495                         if (len(read) == 2):
496                                 calibrate["DAC"].append((level, float(read[0]), float(read[1])))
497                                 outfile.write(str(level) + "\t" + str(float(read[0])) + "\t" + str(float(read[1])) + "\n")
498                         else:
499                                 calibrate["DAC"].append((level, float(read[0])))
500                                 outfile.write(str(level) + "\t" + str(float(read[0])) + "\n")
501                 
502
503
504                 level += stepSize
505
506         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
507         outfile.close()
508         if (len(calibrate["DAC"]) <= 0):
509                 print("Error: No calibration points taken for DAC")
510                 return False
511         return setDAC(0)
512
513 # Run the main function
514 if __name__ == "__main__":
515         sys.exit(main())

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