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
17 # TODO: Insert variables for calibration purposes here.
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)
22 # Calibration data for DAC and ADC
24 "ADC" : [None, None, None, None, None, None, None, None],
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],
33 # TODO: Adjust aqcuisition parameters here
34 aquire = { "DAC_Sweep" : "0.0 + 250.0*int(step/300)", # DAC Sweep value (t is in STEPS, not seconds!)
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" : 2.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
44 #Setup the serial connection parameters
46 port="/dev/ttyUSB0", # Modify as needed (note: in linux need to run `sudo chmod a+rw /dev/ttyUSBX' to set permissions)
48 # Do not change the values below here (unless AVR butterfly is reprogrammed to use different values)
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
75 return str(datetime.datetime.now()).split(" ")[1].split(".")[0].replace(":","")
78 return str(datetime.datetime.now()).split(" ")[0]
83 aquire["start_date"] = getDate()
90 # print("Waiting for \"# hello\" from device...")
91 # while (ser.readline().strip("\r\n") != "# hello"):
93 #while (ser.readline().strip("\r\n ") != "#"):
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"))
102 print("Writing config information to config.dat...")
103 output = open("config.dat", "w", 1)
105 output.write("# Initialise " + str(datetime.datetime.now()) + "\n")
107 for field in calibrate:
108 output.write("# calibrate["+str(field)+"] = "+str(calibrate[field]) + "\n")
111 output.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
113 output.write("# Ready " + str(datetime.datetime.now()) + "\n# EOF\n")
120 if (loadCalibration_DAC() == False):
121 if (calibrateDAC() == False):
123 if (loadCalibration_ADC(aquire["ADC_Is"]) == False):
124 if (calibrateADC_usingDAC(aquire["ADC_Is"], False) == False):
125 if (calibrateADC(aquire["ADC_Is"]) == False):
128 if (loadCalibration_ADC(aquire["ADC_Vi"]) == False):
129 if (calibrateADC_usingDAC(aquire["ADC_Vi"], True) == False):
130 if (calibrateADC(aquire["ADC_Vi"]) == False):
134 # Make directory for today, backup calibration files
135 os.system("mkdir -p " + getDate())
136 os.system("cp *.dat " + getDate() +"/")
144 # TODO: Modify data to record here
146 #record_data([4, 5], getDate()+"/"+str(getTime())+".dat", None, None, "Measure emission&sample current varying with time, constant initial energy.")
148 os.system("mkdir -p " + getDate())
149 record_data([4, 5], getDate()+"/"+str(getTime())+".dat", None, 2250, "Test response to change in Vi. Sweep " + str(sweep) + " (started on " + aquire["start_date"]+")")
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")
163 def record_data(ADC_channels, output, pollTime = None, dac_max = None, comment = 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")
171 output = [sys.stdout]
173 start_time = time.time()
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))
186 dacValue = int(eval(aquire["DAC_Sweep"]))
187 if (setDAC(dacValue) == False):
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
196 if (dac_max != None and dacValue >= dac_max):
199 measure_start = time.time()
203 for channel in ADC_channels:
204 read = readADC(channel)
206 print("Abort data collection")
208 raw_adc.append((channel, read[0], read[1]))
210 end_time = time.time()
213 out.write(str((measure_start + (end_time - measure_start)/2.0 - start_time)))
214 out.write("\t"+str(dacValue))
216 out.write("\t" + str(adc[1]) + "\t" + str(adc[2]))
221 if out != sys.stdout:
225 def loadCalibration_ADC(channel):
227 input_file = open("calibrateADC"+str(channel)+".dat")
229 print("Couldn't find calibration file for ADC " + str(channel))
232 calibrate["ADC"][channel] = []
234 l = l.split("#")[0].strip("\r\n ")
238 split_line = l.split("\t")
239 calibrate["ADC"][channel].append((float(split_line[0]), float(split_line[1])))
242 if (len(calibrate["ADC"][channel]) <= 0):
243 print("Empty calibration file for ADC " + str(channel))
247 def loadCalibration_DAC():
249 input_file = open("calibrateDAC.dat")
251 print("Couldn't find calibration file for DAC")
254 calibrate["DAC"] = []
256 #print("Line is: "+str(l))
257 l = l.split("#")[0].strip("\r\n ")
261 split_line = l.split("\t")
262 if (len(split_line) >= 3):
263 calibrate["DAC"].append((int(split_line[0]), float(split_line[1]), float(split_line[2])))
265 calibrate["DAC"].append((int(split_line[0]), float(split_line[1])))
270 if (len(calibrate["DAC"]) <= 0):
271 print("Empty calibration file for DAC")
275 def getADC_Voltage(channel, counts):
276 if (calibrate["ADC"][channel] == None or len(calibrate["ADC"][channel]) <= 0):
277 if (calibrate["ADC_Rin"][channel] != None and calibrate["ADC_Rvar"][channel] != None):
278 print("Warning: Using rough calibration for ADC"+str(channel) + " = " + str(counts))
279 ratio = float(calibrate["ADC_Rin"][channel]) / (float(calibrate["ADC_Rin"][channel]) + float(calibrate["ADC_Rvar"][channel]))
280 return ratio * (float(counts) / float(calibrate["ADC_Counts"][channel]) * Vref)
282 print("Error: No calibration for ADC"+str(channel))
285 c = calibrate["ADC"][channel]
287 for i in range(0, len(c)-1):
288 if (c[i][0] <= counts and i + 1 < len(c)):
289 grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
290 value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
294 print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
296 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]))
297 value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
299 def readADC(channel):
300 #for i in range(0, aquire["ADC_Averages"]):
301 # ser.write("r "+str(channel)+"\r") # Send command to datalogger
302 #time.sleep(aquire["response_wait"])
303 # response = ser.readline().strip("#\r\n ")
304 # if (response != "r "+str(channel)):
305 # print("Received wierd response reading ADC ("+response+")")
307 #time.sleep(aquire["response_wait"])
308 # values.append(int(ser.readline().strip("\r\n ")))
309 # adc_sum += float(values[len(values)-1])
310 ser.write("r "+str(channel)+"\r")
311 response = ser.readline().strip("#\r\n")
312 if (response != "r "+str(channel)):
313 print("Received wierd response reading ADC ("+response+")")
315 return ser.readline().strip("\r\n").split(" ")
317 def getDAC_Voltage(counts, gain = True):
318 if (calibrate["DAC"] == None or len(calibrate["DAC"]) <= 0):
319 if (calibrate["DAC_Gain"] != None):
320 print("Warning: Using rough calibration for DAC = " + str(counts))
321 return float(counts) / float(calibrate["DAC_Counts"]) * float(calibrate["Vref"]) * float(calibrate["DAC_Gain"])
323 print("Error: No calibrate for DAC")
329 if (len(calibrate["DAC"][0]) < 3):
330 print("Error: No data for unamplified DAC")
335 print("Warning: Only one point in calibration data!")
336 return float(c[0][valueIndex])
338 for i in range(0, len(c)-1):
339 if (c[i][0] <= counts and i + 1 < len(c)):
340 grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
341 value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
345 print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
347 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]))
348 value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
354 ser.write("d "+str(level)+"\r")
356 response = ser.readline().strip("#\r\n ")
357 if (response != "d "+str(level)):
358 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
360 #time.sleep(aquire["response_wait"])
361 #time.sleep(aquire["DAC_Settle"])
362 #time.sleep(aquire["DAC_Settle"])
363 response = ser.readline().strip("#\r\n ")
364 if (response != "DAC "+str(level)):
365 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
367 #time.sleep(aquire["response_wait"])
368 time.sleep(aquire["DAC_Settle"])
371 def calibrateADC_usingDAC(channel, gain = True):
372 if (calibrate["DAC"] == None):
373 print("ERROR: DAC is not calibrated, can't use to calibrate ADC!")
376 calibrate["ADC"][channel] = []
377 outfile = open("calibrateADC"+str(channel)+".dat", "w", 1)
378 outfile.write("# Calibrate ADC " + str(channel) + "\n")
379 outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
381 print("Connect DAC output to ADC " + str(channel) + " and press enter\n")
384 for dac in calibrate["DAC"]:
385 if (setDAC(dac[0]) == False):
388 value = readADC(channel)
391 canadd = (len(calibrate["ADC"][channel]) <= 0)
392 if (canadd == False):
394 for adc in calibrate["ADC"][channel]:
395 if adc[0] == value[0]:
406 #input_value = getDAC_Voltage(dac[0], gain)
407 if (input_value == False):
410 outfile.write(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]) + "\n")
411 print(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]))
413 calibrate["ADC"][channel].append((value[0], input_value, value[1]))
415 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
417 if (setDAC(0) == False):
419 if (len(calibrate["ADC"][channel]) <= 0):
420 print("Error: No calibration points taken for ADC " + str(channel))
424 def calibrateADC(channel):
425 calibrate["ADC"][channel] = []
426 outfile = open("calibrateADC"+str(channel)+".dat", "w", 1)
427 outfile.write("# Calibrate ADC " + str(channel) + "\n")
428 outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
430 print("Calibrating ADC...\n")
431 print("Enter measured voltage, empty line stops.\n")
434 read = sys.stdin.readline().strip("\r\n ")
437 input_value = float(read)
438 output_value = readADC(channel)
439 if (output_value == False):
442 calibrate["ADC"][channel].append((output_value[0], input_value))
443 print(str(output_value[0]) + "\t" + str(input_value))
445 calibrate["ADC"][channel].sort(lambda e : e[1], reverse = False)
450 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
452 if (len(calibrate["ADC"][channel]) <= 0):
453 print("Error: No calibration points taken for ADC " + str(channel))
459 calibrate["DAC"] = []
461 outfile = open("calibrateDAC.dat", "w", 1)
462 outfile.write("# Calibrate DAC\n")
463 outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
465 print("Calibrating DAC...")
466 sys.stdout.write("Number of counts to increment per step: ")
467 read = sys.stdin.readline().strip("\r\n")
470 stepSize = max(1, int(read))
471 sys.stdout.write("\n")
473 outfile.write("# Increment by " + str(stepSize) + "\n")
474 print("Input measured DAC voltage for each level; empty input ends calibration.")
475 print("You may optionally input the DAC voltage before it is amplified too.")
478 while (level < calibrate["DAC_Counts"]):
482 sys.stdout.write(str(level) + " ?")
483 read = sys.stdin.readline().strip("\r\n ")
487 read = read.split(" ")
488 if (len(calibrate["DAC"]) > 0 and len(calibrate["DAC"][len(calibrate["DAC"])-1]) != len(read)):
489 print("Either give one value for EVERY point, or two values for EVERY point. Don't mess around.")
492 calibrate["DAC"].append((level, float(read[0]), float(read[1])))
493 outfile.write(str(level) + "\t" + str(float(read[0])) + "\t" + str(float(read[1])) + "\n")
495 calibrate["DAC"].append((level, float(read[0])))
496 outfile.write(str(level) + "\t" + str(float(read[0])) + "\n")
502 outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
504 if (len(calibrate["DAC"]) <= 0):
505 print("Error: No calibration points taken for DAC")
509 # Run the main function
510 if __name__ == "__main__":