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 + 50.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/ttyUSB0", # 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 ("Focus Voltage" , None),
67 ("Deflection Voltage" , None),
68 ("Accelerating Voltage" , None),
69 ("Venault Voltage" , None),
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),
82 #("610B Scale" , None),
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),
90 ("Sample Angle", None),
91 ("ADC Regulator" , None),
93 ("Parameters last checked", None)
97 return str(datetime.datetime.now()).split(" ")[1].split(".")[0].replace(":","")
100 return str(datetime.datetime.now()).split(" ")[0]
105 p = subprocess.Popen("./pressure/get_pressure.sh", stdout=subprocess.PIPE)
106 #p = subprocess.Popen("./this_program_does_not_exist.sh", stdout=subprocess.PIPE)
108 result = float(p.stdout.readline().strip(" \r\n\t"))
114 # Used for when I press Control-C to stop things
115 def set_exit_handler(func):
119 win32api.SetConsoleCtrlHandler(func, True)
121 version = ".".join(map(str, sys.version_info[:2]))
122 raise Exception("pywin32 not installed for Python " + version)
125 signal.signal(signal.SIGTERM, func)
126 signal.signal(signal.SIGINT, func)
128 def killed_handler(signal, frame):
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")
140 for out in aquire["open_files"]:
141 out.write("# Program exits.\n")
145 result = open(a, b,0)
147 result.write("# File opened at " + str(datetime.datetime.now()) + "\n")
148 aquire["open_files"].append(result)
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)
161 #atexit.register(cleanup)
162 set_exit_handler(killed_handler)
164 aquire["start_date"] = getDate()
171 # print("Waiting for \"# hello\" from device...")
172 # while (ser.readline().strip("\r\n") != "# hello"):
174 #while (ser.readline().strip("\r\n ") != "#"):
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"))
186 #print("Writing config information to config.dat...")
187 #output = log_open("config.dat", "w", 1)
189 #output.write("# Initialise " + str(datetime.datetime.now()) + "\n")
191 #for field in calibrate:
192 # output.write("# calibrate["+str(field)+"] = "+str(calibrate[field]) + "\n")
194 #for field in aquire:
195 # output.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
197 #output.write("# Ready " + str(datetime.datetime.now()) + "\n# EOF\n")
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):
208 #if (loadCalibration_ADC(aquire["ADC_Is"]) == False):
209 # if (calibrateADC_usingDAC(aquire["ADC_Is"], False) == False):
210 # if (calibrateADC(aquire["ADC_Is"]) == False):
213 #if (loadCalibration_ADC(aquire["ADC_Vi"]) == False):
214 # if (calibrateADC_usingDAC(aquire["ADC_Vi"], True) == False):
215 # if (calibrateADC(aquire["ADC_Vi"]) == False):
219 # Make directory for today, backup calibration files
220 os.system("mkdir -p " + getDate())
221 #os.system("cp *.dat " + getDate() +"/")
230 # TODO: Modify data to record here
234 os.system("mkdir -p " + getDate())
235 record_data([5], getDate()+"/"+str(getTime())+".dat", None, 4001)
239 #os.system("echo \"Sweep number " + str(sweep) + " completed\" | festival --tts")
246 os.system("echo \"Experiment complete\" | festival --tts")
253 input_file = log_open(getDate()+"/checklist", "r")
257 if (input_file != None):
258 for line in input_file:
262 item = k[0].strip("# \r\n")
263 value = k[1].strip("# \r\n")
265 if (item in parameters):
266 if item == "Chamber Pressure":
267 parameters[item] = getPressure()
269 parameters[item] = value
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)
281 if (input_file == None):
282 for item in parameters:
283 if item == "Parameters last checked":
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")
291 sys.stdout.write("\""+str(item)+"\" = " + str(parameters[item]) + " New value?: ")
292 response = sys.stdin.readline().strip("\r\n ")
293 if (response == "!"):
296 parameters[item] = response
297 sys.stdout.write("\n")
298 parameters["Parameters last checked"] = str(datetime.datetime.now())
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")
308 def record_data(ADC_channels, output, pollTime = None, dac_max = None):
311 gnuplot("set title \""+str(output)+"\"")
312 output = [log_open(output, "w"), sys.stdout]
315 gnuplot("set title \"<No file>\"")
316 output = [sys.stdout]
320 out.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
323 out.write("# Parameters:\n")
325 parameters["Chamber Pressure"] = getPressure() # Update chamber pressure
327 for field in parameters:
329 out.write("# "+str(field)+" = " + str(parameters[field]) + "\n")
332 start_time = time.time()
334 gnuplot("set xlabel \"DAC (counts)\"")
335 gnuplot("set ylabel \"ADC (counts)\"")
340 out.write("# Experiment " + str(datetime.datetime.now()) + "\n")
341 out.write("# Polling for " + str(pollTime) + "s.\n")
343 out.write("# Data:\n")
344 out.write("# time\tDAC")
345 for channel in ADC_channels:
346 out.write("\tADC"+str(channel))
350 data = [] # Keep track of data for dynamic plotting
351 dacValue = int(eval(aquire["DAC_Sweep"]))
352 if (setDAC(dacValue) == False):
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
366 if (dac_max != None and dacValue >= dac_max):
369 measure_start = time.time()
373 for channel in ADC_channels:
374 read = readADC(channel)
377 print("# Abort data collection due to failed ADC read")
378 if out != sys.stdout:
381 raw_adc.append((channel, read[0], read[1]))
383 end_time = time.time()
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])
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])
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"))
403 if out != sys.stdout:
407 def loadCalibration_ADC(channel):
409 input_file = log_open("calibrateADC"+str(channel)+".dat")
411 print("Couldn't find calibration file for ADC " + str(channel))
414 calibrate["ADC"][channel] = []
416 l = l.split("#")[0].strip("\r\n ")
420 split_line = l.split("\t")
421 calibrate["ADC"][channel].append((float(split_line[0]), float(split_line[1])))
422 log_close(input_file)
424 if (len(calibrate["ADC"][channel]) <= 0):
425 print("Empty calibration file for ADC " + str(channel))
429 def loadCalibration_DAC():
431 input_file = log_open("calibrateDAC.dat")
433 print("Couldn't find calibration file for DAC")
436 calibrate["DAC"] = []
438 #print("Line is: "+str(l))
439 l = l.split("#")[0].strip("\r\n ")
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])))
447 calibrate["DAC"].append((int(split_line[0]), float(split_line[1])))
450 log_close(input_file)
452 if (len(calibrate["DAC"]) <= 0):
453 print("Empty calibration file for DAC")
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)
464 print("Error: No calibration for ADC"+str(channel))
467 c = calibrate["ADC"][channel]
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]))
476 print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
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]))
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+")")
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+")")
497 return ser.readline().strip("\r\n").split(" ")
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"])
505 print("Error: No calibrate for DAC")
511 if (len(calibrate["DAC"][0]) < 3):
512 print("Error: No data for unamplified DAC")
517 print("Warning: Only one point in calibration data!")
518 return float(c[0][valueIndex])
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]))
527 print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
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]))
536 ser.write("d "+str(level)+"\r")
538 response = ser.readline().strip("#\r\n ")
539 if (response != "d "+str(level)):
540 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
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+")")
549 #time.sleep(aquire["response_wait"])
550 time.sleep(aquire["DAC_Settle"])
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!")
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")
563 print("Connect DAC output to ADC " + str(channel) + " and press enter\n")
566 for dac in calibrate["DAC"]:
567 if (setDAC(dac[0]) == False):
570 value = readADC(channel)
573 canadd = (len(calibrate["ADC"][channel]) <= 0)
574 if (canadd == False):
576 for adc in calibrate["ADC"][channel]:
577 if adc[0] == value[0]:
588 #input_value = getDAC_Voltage(dac[0], gain)
589 if (input_value == False):
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]))
595 calibrate["ADC"][channel].append((value[0], input_value, value[1]))
597 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
599 if (setDAC(0) == False):
601 if (len(calibrate["ADC"][channel]) <= 0):
602 print("Error: No calibration points taken for ADC " + str(channel))
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")
612 print("Calibrating ADC...\n")
613 print("Enter measured voltage, empty line stops.\n")
616 read = sys.stdin.readline().strip("\r\n ")
619 input_value = float(read)
620 output_value = readADC(channel)
621 if (output_value == False):
624 calibrate["ADC"][channel].append((output_value[0], input_value))
625 print(str(output_value[0]) + "\t" + str(input_value))
627 calibrate["ADC"][channel].sort(lambda e : e[1], reverse = False)
632 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
634 if (len(calibrate["ADC"][channel]) <= 0):
635 print("Error: No calibration points taken for ADC " + str(channel))
641 calibrate["DAC"] = []
643 outfile = log_open("calibrateDAC.dat", "w")
644 outfile.write("# Calibrate DAC\n")
645 outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
647 print("Calibrating DAC...")
648 sys.stdout.write("Number of counts to increment per step: ")
649 read = sys.stdin.readline().strip("\r\n")
652 stepSize = max(1, int(read))
653 sys.stdout.write("\n")
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.")
660 while (level < calibrate["DAC_Counts"]):
664 sys.stdout.write(str(level) + " ?")
665 read = sys.stdin.readline().strip("\r\n ")
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.")
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")
677 calibrate["DAC"].append((level, float(read[0])))
678 outfile.write(str(level) + "\t" + str(float(read[0])) + "\n")
684 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
686 if (len(calibrate["DAC"]) <= 0):
687 print("Error: No calibration points taken for DAC")
691 # Run the main function
692 if __name__ == "__main__":