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
18 gnuplot = Gnuplot.Gnuplot()
20 # TODO: Insert variables for calibration purposes here.
22 "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)
23 "DAC_Counts" : 2**12, # Maxed counts on DAC channel (12 bits = 2**12 = 4096)
25 # Calibration data for DAC and ADC
27 "ADC" : [None, None, None, None, None, None, None, None],
29 # Data used for rough calibration if above data is not present
30 "Vref" : 3.3, # The output of the voltage regulator (Vref = Vcc) relative to signal ground
31 "ADC_Rin" : [None, None, None, None, 15000, 1100, 1100, 1100],
32 "ADC_Rvar" : [None, None, None, None, 1000, 5000, 10000, 50000],
36 # TODO: Adjust aqcuisition parameters here
37 aquire = { "DAC_Sweep" : "0.0 + 50.0*int(step)", # DAC Sweep value (t is in STEPS, not seconds!)
39 #"ADC_Vi" : 5, # ADC channel to read back Vi (set by DAC) through
40 #"ADC_Is" : 4, # ADC channel to read back Is through
41 #"ADC_Ie" : 4, # ADC channel to read back Ie through
42 "DAC_Settle" : 0.0, # Time in seconds to wait for DAC to stabilise
43 #"response_wait" : 0.2, # Time to wait in seconds between sending data and reading back
48 #Setup the serial connection parameters
50 port="/dev/ttyUSB1", # Modify as needed (note: in linux need to run `sudo chmod a+rw /dev/ttyUSBX' to set permissions)
52 # Do not change the values below here (unless AVR butterfly is reprogrammed to use different values)
62 parameters = odict.odict([
63 ("Accelerating Voltage" , None),
64 ("Focus Voltage" , None),
65 ("Deflection Voltage" , None),
66 ("Venault Voltage" , None),
67 ("Initial Voltage" , None),
68 ("Heating Current" , None),
69 ("Heating Voltage" , None),
70 ("Chamber Pressure" , None),
73 ("610B Scale" , None),
75 ("602 0.1 Battery" , None),
76 ("602 0.03 Battery" , None),
77 ("602 0.01 Battery" , None),
78 ("602 0.003 Battery" , None),
79 ("602 0.001 Battery" , None),
80 ("ADC Regulator" , None),
82 ("Sample Angle", None),
86 ("Parameters last checked", None)
90 return str(datetime.datetime.now()).split(" ")[1].split(".")[0].replace(":","")
93 return str(datetime.datetime.now()).split(" ")[0]
95 # Used for when I press Control-C to stop things
96 def set_exit_handler(func):
100 win32api.SetConsoleCtrlHandler(func, True)
102 version = ".".join(map(str, sys.version_info[:2]))
103 raise Exception("pywin32 not installed for Python " + version)
106 signal.signal(signal.SIGTERM, func)
107 signal.signal(signal.SIGINT, func)
109 def killed_handler(signal, frame):
111 sys.stdout.write("\n# Reason for killing program? ")
112 reason = sys.stdin.readline().strip("\r\n ")
113 for out in aquire["open_files"]:
114 sys.stdout.write("# Closing file " + str(out) + "\n")
115 out.write("# Recieved KILL signal.\n# Reason: " + str(reason) + "\n")
121 for out in aquire["open_files"]:
122 out.write("# Program exits.\n")
126 result = open(a, b,0)
128 result.write("# File opened at " + str(datetime.datetime.now()) + "\n")
129 aquire["open_files"].append(result)
132 def log_close(afile):
133 if (afile in aquire["open_files"]):
134 afile.write("# File closed at " + str(datetime.datetime.now()) + "\n")
135 aquire["open_files"].remove(afile)
142 #atexit.register(cleanup)
143 set_exit_handler(killed_handler)
145 aquire["start_date"] = getDate()
152 # print("Waiting for \"# hello\" from device...")
153 # while (ser.readline().strip("\r\n") != "# hello"):
155 #while (ser.readline().strip("\r\n ") != "#"):
159 ser.write("a "+str(aquire["ADC_Averages"]) + "\r\n")
160 print(ser.readline().strip("\r\n"))
161 print(ser.readline().strip("\r\n"))
162 print(ser.readline().strip("\r\n"))
164 #print("Writing config information to config.dat...")
165 #output = log_open("config.dat", "w", 1)
167 #output.write("# Initialise " + str(datetime.datetime.now()) + "\n")
169 #for field in calibrate:
170 # output.write("# calibrate["+str(field)+"] = "+str(calibrate[field]) + "\n")
172 #for field in aquire:
173 # output.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
175 #output.write("# Ready " + str(datetime.datetime.now()) + "\n# EOF\n")
182 # I haven't ever used calibrated results, and yet this code is still here, why???
183 #if (loadCalibration_DAC() == False):
184 # if (calibrateDAC() == False):
186 #if (loadCalibration_ADC(aquire["ADC_Is"]) == False):
187 # if (calibrateADC_usingDAC(aquire["ADC_Is"], False) == False):
188 # if (calibrateADC(aquire["ADC_Is"]) == False):
191 #if (loadCalibration_ADC(aquire["ADC_Vi"]) == False):
192 # if (calibrateADC_usingDAC(aquire["ADC_Vi"], True) == False):
193 # if (calibrateADC(aquire["ADC_Vi"]) == False):
197 # Make directory for today, backup calibration files
198 os.system("mkdir -p " + getDate())
199 #os.system("cp *.dat " + getDate() +"/")
208 # TODO: Modify data to record here
211 os.system("mkdir -p " + getDate())
212 record_data([5], getDate()+"/"+str(getTime())+".dat", None, 4000)
218 input_file = log_open(getDate()+"/checklist", "r")
222 if (input_file != None):
223 for line in input_file:
227 item = k[0].strip("# \r\n")
228 value = k[1].strip("# \r\n")
230 if (item in parameters):
231 parameters[item] = value
233 print("Checklist found. Overwrite? [Y/n]")
234 response = sys.stdin.readline().strip(" \r\n")
235 if (response == "" or response == "y" or response == "Y"):
236 input_file = log_open(getDate()+"/checklist.old", "w")
237 for item in parameters:
238 input_file.write("# " + str(item) + " = " + str(parameters[item]) + "\n")
239 input_file.write("\n")
240 log_close(input_file)
243 if (input_file == None):
244 for item in parameters:
245 if item == "Parameters last checked":
247 sys.stdout.write("\""+str(item)+"\" = " + str(parameters[item]) + " New value?: ")
248 response = sys.stdin.readline().strip("\r\n ")
250 parameters[item] = response
251 sys.stdout.write("\n")
252 parameters["Parameters last checked"] = str(datetime.datetime.now())
255 checklist = log_open(getDate()+"/checklist", "w")
256 for item in parameters:
257 checklist.write("# "+str(item) + " = " + str(parameters[item]) + "\n")
258 #output_file.write("# "+str(item) + " = " + str(parameters[item]) + "\n")
262 def record_data(ADC_channels, output, pollTime = None, dac_max = None):
265 gnuplot("set title \""+str(output)+"\"")
266 output = [log_open(output, "w"), sys.stdout]
269 gnuplot("set title \"<No file>\"")
270 output = [sys.stdout]
274 out.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
277 out.write("# Parameters:\n")
279 for field in parameters:
281 out.write("# "+str(field)+" = " + str(parameters[field]) + "\n")
284 start_time = time.time()
286 gnuplot("set xlabel \"DAC (counts)\"")
287 gnuplot("set ylabel \"ADC (counts)\"")
292 out.write("# Experiment " + str(datetime.datetime.now()) + "\n")
293 out.write("# Polling for " + str(pollTime) + "s.\n")
295 out.write("# Data:\n")
296 out.write("# time\tDAC")
297 for channel in ADC_channels:
298 out.write("\tADC"+str(channel))
302 data = [] # Keep track of data for dynamic plotting
303 dacValue = int(eval(aquire["DAC_Sweep"]))
304 if (setDAC(dacValue) == False):
307 while (pollTime == None or time.time() < start_time + pollTime):
308 if (aquire["DAC_Sweep"] != None):
309 nextDacValue = int(eval(aquire["DAC_Sweep"]))
310 if (nextDacValue != dacValue):
311 dacValue = nextDacValue
318 if (dac_max != None and dacValue >= dac_max):
321 measure_start = time.time()
325 for channel in ADC_channels:
326 read = readADC(channel)
329 print("# Abort data collection due to failed ADC read")
330 if out != sys.stdout:
333 raw_adc.append((channel, read[0], read[1]))
335 end_time = time.time()
338 measure_time = measure_start + (end_time - measure_start)/2.0 - start_time
339 out.write(str(measure_time))
340 out.write("\t"+str(dacValue))
341 data.append([measure_time, dacValue])
344 out.write("\t" + str(adc[1]) + "\t" + str(adc[2]))
345 data[len(data)-1].append(adc[1])
346 data[len(data)-1].append(adc[2])
350 gnuplot.plot(Gnuplot.Data(data, title="t = "+str(measure_time), with_="lp", using="2:3"))
352 if out != sys.stdout:
356 def loadCalibration_ADC(channel):
358 input_file = log_open("calibrateADC"+str(channel)+".dat")
360 print("Couldn't find calibration file for ADC " + str(channel))
363 calibrate["ADC"][channel] = []
365 l = l.split("#")[0].strip("\r\n ")
369 split_line = l.split("\t")
370 calibrate["ADC"][channel].append((float(split_line[0]), float(split_line[1])))
371 log_close(input_file)
373 if (len(calibrate["ADC"][channel]) <= 0):
374 print("Empty calibration file for ADC " + str(channel))
378 def loadCalibration_DAC():
380 input_file = log_open("calibrateDAC.dat")
382 print("Couldn't find calibration file for DAC")
385 calibrate["DAC"] = []
387 #print("Line is: "+str(l))
388 l = l.split("#")[0].strip("\r\n ")
392 split_line = l.split("\t")
393 if (len(split_line) >= 3):
394 calibrate["DAC"].append((int(split_line[0]), float(split_line[1]), float(split_line[2])))
396 calibrate["DAC"].append((int(split_line[0]), float(split_line[1])))
399 log_close(input_file)
401 if (len(calibrate["DAC"]) <= 0):
402 print("Empty calibration file for DAC")
406 def getADC_Voltage(channel, counts):
407 if (calibrate["ADC"][channel] == None or len(calibrate["ADC"][channel]) <= 0):
408 if (calibrate["ADC_Rin"][channel] != None and calibrate["ADC_Rvar"][channel] != None):
409 print("Warning: Using rough calibration for ADC"+str(channel) + " = " + str(counts))
410 ratio = float(calibrate["ADC_Rin"][channel]) / (float(calibrate["ADC_Rin"][channel]) + float(calibrate["ADC_Rvar"][channel]))
411 return ratio * (float(counts) / float(calibrate["ADC_Counts"][channel]) * Vref)
413 print("Error: No calibration for ADC"+str(channel))
416 c = calibrate["ADC"][channel]
418 for i in range(0, len(c)-1):
419 if (c[i][0] <= counts and i + 1 < len(c)):
420 grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
421 value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
425 print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
427 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]))
428 value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
430 def readADC(channel):
431 #for i in range(0, aquire["ADC_Averages"]):
432 # ser.write("r "+str(channel)+"\r") # Send command to datalogger
433 #time.sleep(aquire["response_wait"])
434 # response = ser.readline().strip("#\r\n ")
435 # if (response != "r "+str(channel)):
436 # print("Received wierd response reading ADC ("+response+")")
438 #time.sleep(aquire["response_wait"])
439 # values.append(int(ser.readline().strip("\r\n ")))
440 # adc_sum += float(values[len(values)-1])
441 ser.write("r "+str(channel)+"\r")
442 response = ser.readline().strip("#\r\n")
443 if (response != "r "+str(channel)):
444 print("Received wierd response reading ADC ("+response+")")
446 return ser.readline().strip("\r\n").split(" ")
448 def getDAC_Voltage(counts, gain = True):
449 if (calibrate["DAC"] == None or len(calibrate["DAC"]) <= 0):
450 if (calibrate["DAC_Gain"] != None):
451 print("Warning: Using rough calibration for DAC = " + str(counts))
452 return float(counts) / float(calibrate["DAC_Counts"]) * float(calibrate["Vref"]) * float(calibrate["DAC_Gain"])
454 print("Error: No calibrate for DAC")
460 if (len(calibrate["DAC"][0]) < 3):
461 print("Error: No data for unamplified DAC")
466 print("Warning: Only one point in calibration data!")
467 return float(c[0][valueIndex])
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]))
485 ser.write("d "+str(level)+"\r")
487 response = ser.readline().strip("#\r\n ")
488 if (response != "d "+str(level)):
489 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
491 #time.sleep(aquire["response_wait"])
492 #time.sleep(aquire["DAC_Settle"])
493 #time.sleep(aquire["DAC_Settle"])
494 response = ser.readline().strip("#\r\n ")
495 if (response != "DAC "+str(level)):
496 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
498 #time.sleep(aquire["response_wait"])
499 time.sleep(aquire["DAC_Settle"])
502 def calibrateADC_usingDAC(channel, gain = True):
503 if (calibrate["DAC"] == None):
504 print("ERROR: DAC is not calibrated, can't use to calibrate ADC!")
507 calibrate["ADC"][channel] = []
508 outfile = log_open("calibrateADC"+str(channel)+".dat", "w")
509 outfile.write("# Calibrate ADC " + str(channel) + "\n")
510 outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
512 print("Connect DAC output to ADC " + str(channel) + " and press enter\n")
515 for dac in calibrate["DAC"]:
516 if (setDAC(dac[0]) == False):
519 value = readADC(channel)
522 canadd = (len(calibrate["ADC"][channel]) <= 0)
523 if (canadd == False):
525 for adc in calibrate["ADC"][channel]:
526 if adc[0] == value[0]:
537 #input_value = getDAC_Voltage(dac[0], gain)
538 if (input_value == False):
541 outfile.write(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]) + "\n")
542 print(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]))
544 calibrate["ADC"][channel].append((value[0], input_value, value[1]))
546 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
548 if (setDAC(0) == False):
550 if (len(calibrate["ADC"][channel]) <= 0):
551 print("Error: No calibration points taken for ADC " + str(channel))
555 def calibrateADC(channel):
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")
561 print("Calibrating ADC...\n")
562 print("Enter measured voltage, empty line stops.\n")
565 read = sys.stdin.readline().strip("\r\n ")
568 input_value = float(read)
569 output_value = readADC(channel)
570 if (output_value == False):
573 calibrate["ADC"][channel].append((output_value[0], input_value))
574 print(str(output_value[0]) + "\t" + str(input_value))
576 calibrate["ADC"][channel].sort(lambda e : e[1], reverse = False)
581 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
583 if (len(calibrate["ADC"][channel]) <= 0):
584 print("Error: No calibration points taken for ADC " + str(channel))
590 calibrate["DAC"] = []
592 outfile = log_open("calibrateDAC.dat", "w")
593 outfile.write("# Calibrate DAC\n")
594 outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
596 print("Calibrating DAC...")
597 sys.stdout.write("Number of counts to increment per step: ")
598 read = sys.stdin.readline().strip("\r\n")
601 stepSize = max(1, int(read))
602 sys.stdout.write("\n")
604 outfile.write("# Increment by " + str(stepSize) + "\n")
605 print("Input measured DAC voltage for each level; empty input ends calibration.")
606 print("You may optionally input the DAC voltage before it is amplified too.")
609 while (level < calibrate["DAC_Counts"]):
613 sys.stdout.write(str(level) + " ?")
614 read = sys.stdin.readline().strip("\r\n ")
618 read = read.split(" ")
619 if (len(calibrate["DAC"]) > 0 and len(calibrate["DAC"][len(calibrate["DAC"])-1]) != len(read)):
620 print("Either give one value for EVERY point, or two values for EVERY point. Don't mess around.")
623 calibrate["DAC"].append((level, float(read[0]), float(read[1])))
624 outfile.write(str(level) + "\t" + str(float(read[0])) + "\t" + str(float(read[1])) + "\n")
626 calibrate["DAC"].append((level, float(read[0])))
627 outfile.write(str(level) + "\t" + str(float(read[0])) + "\n")
633 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
635 if (len(calibrate["DAC"]) <= 0):
636 print("Error: No calibration points taken for DAC")
640 # Run the main function
641 if __name__ == "__main__":