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
16 import Gnuplot, Gnuplot.funcutils
19 gnuplot = Gnuplot.Gnuplot()
21 # TODO: Insert variables for calibration purposes here.
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)
26 # Calibration data for DAC and ADC
28 "ADC" : [None, None, None, None, None, None, None, None],
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],
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!)
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
49 #Setup the serial connection parameters
51 port="/dev/ttyUSB1", # Modify as needed (note: in linux need to run `sudo chmod a+rw /dev/ttyUSBX' to set permissions)
53 # Do not change the values below here (unless AVR butterfly is reprogrammed to use different values)
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),
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),
78 #("610B 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),
87 ("Sample Angle", None),
89 ("Parameters last checked", None)
93 return str(datetime.datetime.now()).split(" ")[1].split(".")[0].replace(":","")
96 return str(datetime.datetime.now()).split(" ")[0]
99 p = subprocess.Popen("./pressure/get_pressure.sh", stdout=subprocess.PIPE)
100 return float(p.stdout.readline().strip(" \r\n\t"))
103 # Used for when I press Control-C to stop things
104 def set_exit_handler(func):
108 win32api.SetConsoleCtrlHandler(func, True)
110 version = ".".join(map(str, sys.version_info[:2]))
111 raise Exception("pywin32 not installed for Python " + version)
114 signal.signal(signal.SIGTERM, func)
115 signal.signal(signal.SIGINT, func)
117 def killed_handler(signal, frame):
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")
129 for out in aquire["open_files"]:
130 out.write("# Program exits.\n")
134 result = open(a, b,0)
136 result.write("# File opened at " + str(datetime.datetime.now()) + "\n")
137 aquire["open_files"].append(result)
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)
150 #atexit.register(cleanup)
151 set_exit_handler(killed_handler)
153 aquire["start_date"] = getDate()
160 # print("Waiting for \"# hello\" from device...")
161 # while (ser.readline().strip("\r\n") != "# hello"):
163 #while (ser.readline().strip("\r\n ") != "#"):
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"))
175 #print("Writing config information to config.dat...")
176 #output = log_open("config.dat", "w", 1)
178 #output.write("# Initialise " + str(datetime.datetime.now()) + "\n")
180 #for field in calibrate:
181 # output.write("# calibrate["+str(field)+"] = "+str(calibrate[field]) + "\n")
183 #for field in aquire:
184 # output.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
186 #output.write("# Ready " + str(datetime.datetime.now()) + "\n# EOF\n")
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):
197 #if (loadCalibration_ADC(aquire["ADC_Is"]) == False):
198 # if (calibrateADC_usingDAC(aquire["ADC_Is"], False) == False):
199 # if (calibrateADC(aquire["ADC_Is"]) == False):
202 #if (loadCalibration_ADC(aquire["ADC_Vi"]) == False):
203 # if (calibrateADC_usingDAC(aquire["ADC_Vi"], True) == False):
204 # if (calibrateADC(aquire["ADC_Vi"]) == False):
208 # Make directory for today, backup calibration files
209 os.system("mkdir -p " + getDate())
210 #os.system("cp *.dat " + getDate() +"/")
219 # TODO: Modify data to record here
223 os.system("mkdir -p " + getDate())
224 record_data([5], getDate()+"/"+str(getTime())+".dat", None, 4000)
230 input_file = log_open(getDate()+"/checklist", "r")
234 if (input_file != None):
235 for line in input_file:
239 item = k[0].strip("# \r\n")
240 value = k[1].strip("# \r\n")
242 if (item in parameters):
243 if item == "Chamber Pressure":
244 parameters[item] = getPressure()
246 parameters[item] = value
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)
258 if (input_file == None):
259 for item in parameters:
260 if item == "Parameters last checked":
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")
268 sys.stdout.write("\""+str(item)+"\" = " + str(parameters[item]) + " New value?: ")
269 response = sys.stdin.readline().strip("\r\n ")
270 if (response == "!"):
273 parameters[item] = response
274 sys.stdout.write("\n")
275 parameters["Parameters last checked"] = str(datetime.datetime.now())
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")
285 def record_data(ADC_channels, output, pollTime = None, dac_max = None):
288 gnuplot("set title \""+str(output)+"\"")
289 output = [log_open(output, "w"), sys.stdout]
292 gnuplot("set title \"<No file>\"")
293 output = [sys.stdout]
297 out.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
300 out.write("# Parameters:\n")
302 parameters["Chamber Pressure"] = getPressure() # Update chamber pressure
304 for field in parameters:
306 out.write("# "+str(field)+" = " + str(parameters[field]) + "\n")
309 start_time = time.time()
311 gnuplot("set xlabel \"DAC (counts)\"")
312 gnuplot("set ylabel \"ADC (counts)\"")
317 out.write("# Experiment " + str(datetime.datetime.now()) + "\n")
318 out.write("# Polling for " + str(pollTime) + "s.\n")
320 out.write("# Data:\n")
321 out.write("# time\tDAC")
322 for channel in ADC_channels:
323 out.write("\tADC"+str(channel))
327 data = [] # Keep track of data for dynamic plotting
328 dacValue = int(eval(aquire["DAC_Sweep"]))
329 if (setDAC(dacValue) == False):
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
343 if (dac_max != None and dacValue >= dac_max):
346 measure_start = time.time()
350 for channel in ADC_channels:
351 read = readADC(channel)
354 print("# Abort data collection due to failed ADC read")
355 if out != sys.stdout:
358 raw_adc.append((channel, read[0], read[1]))
360 end_time = time.time()
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])
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])
375 gnuplot.plot(Gnuplot.Data(data, title="t = "+str(measure_time), with_="lp", using="2:3"))
377 if out != sys.stdout:
381 def loadCalibration_ADC(channel):
383 input_file = log_open("calibrateADC"+str(channel)+".dat")
385 print("Couldn't find calibration file for ADC " + str(channel))
388 calibrate["ADC"][channel] = []
390 l = l.split("#")[0].strip("\r\n ")
394 split_line = l.split("\t")
395 calibrate["ADC"][channel].append((float(split_line[0]), float(split_line[1])))
396 log_close(input_file)
398 if (len(calibrate["ADC"][channel]) <= 0):
399 print("Empty calibration file for ADC " + str(channel))
403 def loadCalibration_DAC():
405 input_file = log_open("calibrateDAC.dat")
407 print("Couldn't find calibration file for DAC")
410 calibrate["DAC"] = []
412 #print("Line is: "+str(l))
413 l = l.split("#")[0].strip("\r\n ")
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])))
421 calibrate["DAC"].append((int(split_line[0]), float(split_line[1])))
424 log_close(input_file)
426 if (len(calibrate["DAC"]) <= 0):
427 print("Empty calibration file for DAC")
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)
438 print("Error: No calibration for ADC"+str(channel))
441 c = calibrate["ADC"][channel]
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]))
450 print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
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]))
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+")")
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+")")
471 return ser.readline().strip("\r\n").split(" ")
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"])
479 print("Error: No calibrate for DAC")
485 if (len(calibrate["DAC"][0]) < 3):
486 print("Error: No data for unamplified DAC")
491 print("Warning: Only one point in calibration data!")
492 return float(c[0][valueIndex])
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]))
501 print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
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]))
510 ser.write("d "+str(level)+"\r")
512 response = ser.readline().strip("#\r\n ")
513 if (response != "d "+str(level)):
514 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
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+")")
523 #time.sleep(aquire["response_wait"])
524 time.sleep(aquire["DAC_Settle"])
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!")
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")
537 print("Connect DAC output to ADC " + str(channel) + " and press enter\n")
540 for dac in calibrate["DAC"]:
541 if (setDAC(dac[0]) == False):
544 value = readADC(channel)
547 canadd = (len(calibrate["ADC"][channel]) <= 0)
548 if (canadd == False):
550 for adc in calibrate["ADC"][channel]:
551 if adc[0] == value[0]:
562 #input_value = getDAC_Voltage(dac[0], gain)
563 if (input_value == False):
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]))
569 calibrate["ADC"][channel].append((value[0], input_value, value[1]))
571 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
573 if (setDAC(0) == False):
575 if (len(calibrate["ADC"][channel]) <= 0):
576 print("Error: No calibration points taken for ADC " + str(channel))
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")
586 print("Calibrating ADC...\n")
587 print("Enter measured voltage, empty line stops.\n")
590 read = sys.stdin.readline().strip("\r\n ")
593 input_value = float(read)
594 output_value = readADC(channel)
595 if (output_value == False):
598 calibrate["ADC"][channel].append((output_value[0], input_value))
599 print(str(output_value[0]) + "\t" + str(input_value))
601 calibrate["ADC"][channel].sort(lambda e : e[1], reverse = False)
606 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
608 if (len(calibrate["ADC"][channel]) <= 0):
609 print("Error: No calibration points taken for ADC " + str(channel))
615 calibrate["DAC"] = []
617 outfile = log_open("calibrateDAC.dat", "w")
618 outfile.write("# Calibrate DAC\n")
619 outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
621 print("Calibrating DAC...")
622 sys.stdout.write("Number of counts to increment per step: ")
623 read = sys.stdin.readline().strip("\r\n")
626 stepSize = max(1, int(read))
627 sys.stdout.write("\n")
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.")
634 while (level < calibrate["DAC_Counts"]):
638 sys.stdout.write(str(level) + " ?")
639 read = sys.stdin.readline().strip("\r\n ")
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.")
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")
651 calibrate["DAC"].append((level, float(read[0])))
652 outfile.write(str(level) + "\t" + str(float(read[0])) + "\n")
658 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
660 if (len(calibrate["DAC"]) <= 0):
661 print("Error: No calibration points taken for DAC")
665 # Run the main function
666 if __name__ == "__main__":