-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
468 lines (368 loc) · 18 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.system('color')
from time import sleep
import time
import pyvisa
from termcolor import colored
from fileUtilities import readConfigFile
# pyvisa.log_to_screen()
voltageStabilizationTimeout = 10 # in s
HVSourceSettingOFFTimeout = 60 # in s
def getInstruments(k2400_gpibAddress, hvSource_gpibAddress):
delay = 0.1
rm = pyvisa.ResourceManager()
l_resources = rm.list_resources()
printMessage("Looking for pyVisa Resources......", "*", "*")
printMessage(l_resources, "*", "*")
hv_source = None
k2400 = None
k2400 = rm.open_resource("GPIB0::" + str(k2400_gpibAddress) + "::INSTR", send_end=True)
k2400.timeout = 25000 # si configuramos el k2400 con filtro y nplcs altos, necesitaremos tiempos de timeout altos tambien
# sleep(delay)
sendCommandToInstrument(k2400, "*IDN?", "", 0, delay)
response = k2400.read_raw() # type(response) =--> bytes
decoded_response = response.decode(encoding='ascii', errors='ignore')
print(decoded_response)
hv_source = rm.open_resource("GPIB0::" + str(hvSource_gpibAddress) + "::INSTR", send_end=True)
# sleep(delay)
sendCommandToInstrument(hv_source, "ID", "", 0, delay)
response = hv_source.read_raw() # type(response) =--> bytes
decoded_response = response.decode(encoding='ascii', errors='ignore')
print(decoded_response)
return k2400, hv_source
def sendCommandToInstrument(instrument, command, terminator, delayBefore, delayAfter):
sleep(delayBefore)
instrument.write_raw(command + terminator)
sleep(delayAfter)
def printMessage(message, headerStr, footerStr):
print(colored(len(message) * headerStr, "magenta"))
print(colored(message, "magenta"))
print(colored(len(message) * footerStr, "magenta"))
def initializeK2400(k2400, compliance, nplcs, range):
delay = 0.25 # seconds
term = ""
message = "Initializing the K2400 as Ampermeter....."
printMessage(message, "*", "*")
sendCommandToInstrument(k2400, "*CLS", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, "*SRE 4", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, "*ESE 0", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":STAT:OPER:ENAB 0", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":STAT:MEAS:ENAB 0", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":STAT:QUES:ENAB 0", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":FORM:SREG ASC", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, "*RST", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":SYST:BEEP:STAT ON", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":SOUR:FUNC VOLT", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":SOUR:VOLT:LEV 0", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":SOUR:VOLT:RANG 0.2", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":FORM:ELEM VOLT, CURR, TIME", term, 0, delay)
sleep(delay)
# sendCommandToInstrument(k2400, ":SENS:FUNC:CONC ON", term, 0, delay)
# sleep(delay)
sendCommandToInstrument(k2400, ":SENS:FUNC:OFF:ALL", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":SENS:FUNC:ON 'CURR'", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":SENS:CURR:NPLC " + str(int(nplcs)), term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":SENSe:AVERage:TCONtrol REPeat", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":SENSe:AVERage:COUNt 8", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":SENSe:AVERage ON", term, 0, delay)
sleep(delay)
sendCommandToInstrument(k2400, ":SENS:CURR:RANG " + "{:.8f}".format(range), term, 0, delay) # AMPS
sleep(delay)
sendCommandToInstrument(k2400, ":SENS:CURR:PROT " + "{:.8f}".format(compliance), term, 0, delay) # AMPS
sleep(delay)
sendCommandToInstrument(k2400, ":ROUTE:TERM REAR", term, 0, delay)
sleep(delay)
# K2400 ON
sendCommandToInstrument(k2400, ":OUTP:STAT ON", term, 0, delay)
# :SENSe: AVERage:TCONtrol < type >
# :SENSe: AVERage:COUNt < n >
# :SENSe: AVERage < state >
message = "Initializing done!!!"
printMessage(message, "*", "*")
def initializeHVSource(hv_source, rampVoltage, outputCurrentLimit, enableKill):
delay = 0.25
term = ""
message = "Initializing the HV Source....."
printMessage(message, "*", "*")
outputCurrentLimitInMilliamps = int(outputCurrentLimit * 1000)
sendCommandToInstrument(hv_source, "*RST", term, 0, delay)
sleep(delay)
sendCommandToInstrument(hv_source, "*CLS", term, 0, delay)
sleep(delay)
# set output current limit
sendCommandToInstrument(hv_source, "I," + str(outputCurrentLimitInMilliamps) + "mA", term, 0, delay)
sleep(delay)
# set ramp
sendCommandToInstrument(hv_source, "RAMP," + str(int(rampVoltage)) + "V/s", term, 0, delay)
sleep(delay)
# set kill enable
sendCommandToInstrument(hv_source, "KILL," + 'EN' if enableKill else 'DIS', term, 0, delay)
sleep(delay)
# Setting output voltage to zero
setHVOutputVoltage(hv_source, 0, 60)
message = "Initializing done!!!"
printMessage(message, "*", "*")
def readVoltageFromHVSource(hv_source, delay=0.5):
term = ""
correctResponse = False
voltage = 0.0
while not correctResponse:
sendCommandToInstrument(hv_source, "STATUS,MU", term, 0, delay)
response = hv_source.read_raw() # response should be in format "UM, RANGE=3000V, VALUE=2.458kV\x00"
decoded_response = response.decode(encoding='ascii', errors='ignore')
decoded_response = decoded_response.split(", ")
print(decoded_response)
if len(decoded_response) == 3:
correctResponse = True
voltageString = decoded_response[2][:-1]
# de esto "UM, RANGE=3000V, VALUE=2.458kV\x00"
# debemos obtener esto otro 2.458
voltageString = voltageString.removeprefix("VALUE=")
voltageString = voltageString.removesuffix("kV")
voltage = float(voltageString) * 1000
print(colored("Lectura de voltage correcta en la fuente de HV. Voltage = " + str(voltage) + "V", "green"))
else:
# la lectura del voltage ha fallado, esperamos y volvemos a pedir
print(colored(
"Fallo en la lectura de voltage a la fuente de HV. Esperamos un tiempo y solicitamos de nuevo...",
"red"))
sleep(1)
return voltage
def waitForVoltageStabilization(hv_source, desiredVoltage, maxAbsolutePermissibleError, checkPeriod, lastDelay,
voltageStabilizationTimeout=10):
"""
Funcion sincrona cuya funcion basica es esperar a que la salida de tension de una fuente de alimentacion (en nuestro caso una hv_voltage)
entre dentro del rango de error permisible. Una vez la salida se encuentra dentro de dicho rango de error la funcion retorna True.
Por ejemplo: Si deriredVoltage = 1000V y nuestro maxAbsolutePermissibleError = 10V entonces la funcion retornara True en el momento
de leer un voltage en la fuente de alimentacion que se encuentre dentro del rango (990V,1010V). En nuestro caso un valor leido
en la salida de la fuente igual a 995V haría retornar True a la fuencion, por el contrario un valor leido a la salida de la fuente
igual a 880V mantendria a la funcion dentro del bucle de lectura de tension a la salida de la fuente.\n
Args:
hv_source (pyvisa.resource.resource): Instrumento
desiredVoltage (float): Voltaje nominal deseado a la salida de la fuente. Volts
maxAbsolutePermissibleError (float): Maximo error (absoluto) permitido a la salida de la fuente. Volts
checkPeriod (float): Periodo de chequeo del valor de voltaje a la salida de la fuente. Seconds
lastDelay (float): Tiempo de espera de seguridad una vez que la salida de la fuente se encuentra dentro del rango. Seconds
(desiredVoltage-maxAbsolutePermissibleError, desiredVoltage+maxAbsolutePermissibleError)
voltageStabilizationTimeout (long): Tiempo máximo dado a la funcion para chequear la salida de la fuente de alimentacion. Seconds
Returns:
True si el valor leido a la salida de la fuente de alimentacion se encuentra dentro del rango
(desiredVoltage-maxAbsolutePermissibleError, desiredVoltage+maxAbsolutePermissibleError) \n
False si el valor leido a la salida de la fuente de alimentación no llega a situarse dentro del rango
(desiredVoltage-maxAbsolutePermissibleError, desiredVoltage+maxAbsolutePermissibleError) y el tiempo de ejecucion
de la funcion supera o iguala el valor dado por el voltageStabilizationTimeout
"""
initialTime = time.time() * 1000
deadTime = initialTime + voltageStabilizationTimeout * 1000
permissibleRange = (desiredVoltage - maxAbsolutePermissibleError, desiredVoltage + maxAbsolutePermissibleError)
while True:
sleep(checkPeriod)
# primero chequeamos el timeout
actualTime = time.time() * 1000
if actualTime >= deadTime:
return False # Se ha cumplido el timeout
# si no se ha cumplido el timeout miramos la tension a la salida de la fuente y comprobamos si se encuentra
# dentro del rango permitido
readedVoltage = readVoltageFromHVSource(hv_source)
if permissibleRange[0] < readedVoltage < permissibleRange[1]:
break
sleep(lastDelay)
return True
def getHVSourceStatus(hv_source):
delay = 1
term = ""
sendCommandToInstrument(hv_source, "STATUS,DI", term, 0, delay)
response = hv_source.read_raw()
return response
def setHVOutputVoltage(hv_source, targetVoltage, voltageStabilizationTimeout=10):
"""
Funcion sincrona que permite settear una determinada tension (targetVoltage) en la fuente de alimentacion (hv_source) y
espera a la estabiizacion de esta segun unos criterios definidos por un error, una frecuencia de actualizacion y un tiempo de timeout.\n
:param hv_source: pyvisa.resource.resorce como la fuente de alimentacion
:param voltage: float con el voltage deseado a la salida de la fuente de alimentacion. Kv
:param voltageStabilizationTimeout: Tiempo de espera que toma la funcion para comprobar qe la salida de
la fuente de alimentacion ofrece el voltage deseado. Seconds
:return: None
"""
term = ""
hvSource_OutputVoltageStabilization_Success = False
while not hvSource_OutputVoltageStabilization_Success:
# Actualizamos la tension en la fuente
print(colored("Setting the H Source to --> " + "U," + "{:.3f}".format(targetVoltage) + "kV", "yellow"))
sendCommandToInstrument(hv_source, "U," + "{:.3f}".format(targetVoltage) + "kV", term, 0, 0.5)
print(colored("Waiting for voltage stabilization...", "grey", "on_white"))
hvSource_OutputVoltageStabilization_Success = waitForVoltageStabilization(hv_source, targetVoltage * 1000, 20,
0.5, 1,
voltageStabilizationTimeout) # maxAbsolutePermissibleError is 10V
if not hvSource_OutputVoltageStabilization_Success:
print(colored(
"Voltage Stabilization WatchDog has raised an exception. Voltage stabilization is taking too much time...",
"red"))
def start_process(K2400_gpibAddress,
HVSource_gpibAddress,
initialVoltage,
finalVoltage,
pointsVoltage,
measureDelay_ms,
rampVoltage,
outputCurrentLimit,
enableKill,
ammeterRange,
ammeterCompliance,
ammeterNPLCs,
resultsFilePath):
delay = 0.5 # in s
term = ""
k2400, hv_source = getInstruments(K2400_gpibAddress, HVSource_gpibAddress)
# !!!!!!!!!MUY IMPORTANTE. PARA PROTEGER LA TENSION QUE VEN LOS BORNES DEL AMPERIMETRO!!!!!!!!!!!!!!
# SIEMPRE AMMETER ON ANTES DE APLICAR VOLTAJE O INICIALIZAR LA FUENTE QUE PUEDE TENER VOLTAJE ALTO ANTES DE EMPEZAR EL PROCESO
# K2400 ON
sendCommandToInstrument(k2400, ":OUTP:STAT ON", term, 0, delay)
# importante inicializar primero la fuente de voltage para bajar a cero antes de inicializar el amperimetro
initializeHVSource(hv_source, rampVoltage, outputCurrentLimit, enableKill)
initializeK2400(k2400, ammeterCompliance, ammeterNPLCs, ammeterRange)
# #calculo del step voltage
step_voltage = (finalVoltage - initialVoltage) / pointsVoltage
next_voltage = initialVoltage
finalProcess = False
# HV source ON
sendCommandToInstrument(hv_source, "HV,ON", term, 0, delay)
# Here you have to write to file
f = open(resultsFilePath, "a")
f.truncate(0)
# mean_current calculation
previous_current = 0.0
sum_current = 0.0
mean_current = 0.0
n_steps = 0
# current threshold in percent of current value
maxCurrentDelta_inTimesOfPreviousCurrent = 100 #20
is_current_overflow = False
# file format
sep = "\t"
while not finalProcess:
if next_voltage > finalVoltage or is_current_overflow:
finalProcess = True
else:
setHVOutputVoltage(hv_source, next_voltage / 1000, voltageStabilizationTimeout)
print(
colored("Waiting for measure delay = " + str(measureDelay_ms / 1000) + " seconds", "grey", "on_white"))
sleep(measureDelay_ms / 1000)
# Una vez el voltaje de la fuente es estable a su salida podremos considerar que actualvoltage = nextvoltage
actual_voltage = next_voltage
# Here you have to measure the hv_source volatge
hv_source_voltage = readVoltageFromHVSource(hv_source)
print(colored("Voltage source --> " + str(hv_source_voltage) + "V", "cyan"))
# Here you have to measure the current of the k2400
sendCommandToInstrument(k2400, ":READ?", term, 0, 0.5)
ammeter_response = k2400.read_raw()
ammeter_decoded_response = ammeter_response.decode(encoding='ascii', errors='ignore')
ammeter_decoded_response = ammeter_decoded_response[:-1]
ammeter_decoded_response = ammeter_decoded_response.split(",")
ammeter_current = float(ammeter_decoded_response[1])
#Al estar el smu en modo amperimetro, el signo de la corriente es negativo
#invertimos el signo de la corriente para trabajar mejor
ammeter_current = -ammeter_current
if n_steps == 0:
previous_current = ammeter_current
print(colored("Previous Current --> " + str(previous_current) + "A", "cyan"))
print(colored("Ammeter Current --> " + str(ammeter_current) + "A", "cyan"))
print(colored("Current Delta --> " + str(ammeter_current - previous_current) + "A", "cyan"))
print(colored(
"Max Current Delta --> " + str(abs(maxCurrentDelta_inTimesOfPreviousCurrent * previous_current)) + "A",
"cyan"))
# Here you have to write to file
f.write(str(hv_source_voltage) + sep + str(abs(ammeter_current)) + "\n")
f.flush()
# check if the ammeter_current overflows
current_delta = ammeter_current - previous_current
if current_delta > 0:
if abs(current_delta) > abs(maxCurrentDelta_inTimesOfPreviousCurrent * previous_current):
# ammeter_currrent overflow
is_current_overflow = True
print(colored("CURRENT OVERFLOW!!!!!!!", "red"))
if not is_current_overflow:
next_voltage = actual_voltage + step_voltage
previous_current = ammeter_current
n_steps = n_steps + 1
message = "Closing the results file!!!"
printMessage(message, "*", "*")
f.close()
message = "Process Complete!!!"
printMessage(message, "*", "*")
message = "Powering off instruments!!!"
printMessage(message, "*", "*")
# Setting output voltage to zero
setHVOutputVoltage(hv_source, 0, 60)
# HV source off
sendCommandToInstrument(hv_source, "HV,OFF", term, 0, delay)
message = "Now HV Source is safe!!!!"
printMessage(message, "*", "*")
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
process_config_file_path = "process_config_file.json"
K2400_gpibAddress, \
HVSource_gpibAddress, \
initialVoltage, \
finalVoltage, \
pointsVoltage, \
measureDelay_ms, \
rampVoltage, \
outputCurrentLimit, \
enableKill, \
ammeterRange, \
ammeterCompliance, \
ammeterNPLCs, \
resultsFileName, \
resultsFileExtension = readConfigFile(process_config_file_path)
# print(measureDelay_ms)
# exit(0)
# counter = 0
#
# while True:
# start_process(K2400_gpibAddress,
# HVSource_gpibAddress,
# initialVoltage,
# finalVoltage,
# pointsVoltage,
# measureDelay_ms,
# rampVoltage,
# outputCurrentLimit,
# enableKill,
# ammeterRange,
# ammeterCompliance,
# ammeterNPLCs,
# resultsFileName + str(counter) + "." + resultsFileExtension)
# counter += 1
start_process(K2400_gpibAddress,
HVSource_gpibAddress,
initialVoltage,
finalVoltage,
pointsVoltage,
measureDelay_ms,
rampVoltage,
outputCurrentLimit,
enableKill,
ammeterRange,
ammeterCompliance,
ammeterNPLCs,
resultsFileName + "." + resultsFileExtension)