Debian Codegraph @

pymeasure/instruments/hp/hp3478A.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 import ctypes
26 import logging
27 import math
28 from enum import IntFlag
29 from pymeasure.instruments.hp.hplegacyinstrument import HPLegacyInstrument, StatusBitsBase
30 from pymeasure.instruments.validators import strict_discrete_set, strict_range
31
32
33 log = logging.getLogger(__name__)
34 log.addHandler(logging.NullHandler())
35
36 c_uint8 = ctypes.c_uint8
37
38
39 class SRQ(ctypes.BigEndianStructure):
40 """Support class for the SRQ handling
41 """
42 _fields_ = [
43 ("power_on", c_uint8, 1),
44 ("not_assigned_1", c_uint8, 1),
45 ("calibration", c_uint8, 1),
46 ("front_panel_button", c_uint8, 1),
47 ("internal_error", c_uint8, 1),
48 ("syntax_error", c_uint8, 1),
49 ("not_assigned_2", c_uint8, 1),
50 ("data_ready", c_uint8, 1),
51 ]
52
53 def __str__(self):
54 """
55 Returns a pretty formatted string showing the status of the instrument
56
57 """
58 ret_str = ""
59 for field in self._fields_:
60 ret_str = ret_str + f"{field[0]}: {hex(getattr(self, field[0]))}\n"
61
62 return ret_str
63
64
65 class Status(StatusBitsBase):
66 """
67 Support-Class with the bit assignments for the 5 status byte of the HP3478A
68 """
69
70 _fields_ = [
71 # Byte 1: Function, Range and Number of Digits
72 ("function", c_uint8, 3), # bit 5..7
73 ("range", c_uint8, 3), # bit 2..4
74 ("digits", c_uint8, 2), # bit 0..1
75 # Byte 2: Status Bits
76 ("res1", c_uint8, 1),
77 ("ext_trig", c_uint8, 1),
78 ("cal_enable", c_uint8, 1),
79 ("front_rear", c_uint8, 1),
80 ("fifty_hz", c_uint8, 1),
81 ("auto_zero", c_uint8, 1),
82 ("auto_range", c_uint8, 1),
83 ("int_trig", c_uint8, 1),
84 # Byte 3: Serial Poll Mask (SRQ)
85 # ("SRQ_PON", c_uint8, 1),
86 # ("res3", c_uint8, 1),
87 # ("SRQ_cal_error", c_uint8, 1),
88 # ("SRQ_front_panel", c_uint8, 1),
89 # ("SRQ_internal_error", c_uint8, 1),
90 # ("SRQ_syntax_error", c_uint8, 1),
91 # ("res2", c_uint8, 1),
92 # ("SRQ_data_rdy", c_uint8, 1),
93 ("SRQ", SRQ),
94 # Byte 4: Error Information
95 # ("res5", c_uint8, 1),
96 # ("res4", c_uint8, 1),
97 # ("ERR_AD_Link", c_uint8, 1),
98 # ("ERR_AD", c_uint8, 1),
99 # ("ERR_slope", c_uint8, 1),
100 # ("ERR_ROM", c_uint8, 1),
101 # ("ERR_RAM", c_uint8, 1),
102 # ("ERR_cal", c_uint8, 1),
103 ("Error_Status", c_uint8, 8),
104 # Byte 5: DAC Value
105 ("DAC_value", c_uint8, 8),
106 ]
107
108
109 class HP3478A(HPLegacyInstrument):
110 """ Represents the Hewlett Packard 3478A 5 1/2 digit multimeter
111 and provides a high-level interface for interacting
112 with the instrument.
113 """
114 status_desc = Status
115
116 def __init__(self, adapter, name="Hewlett-Packard HP3478A", **kwargs):
117 kwargs.setdefault('read_termination', '\r\n')
118 kwargs.setdefault('send_end', True)
119 super().__init__(
120 adapter,
121 name,
122 **kwargs,
123 )
124
125 # Definitions for different specifics of this instrument
126 MODES = {"DCV": "F1",
127 "ACV": "F2",
128 "R2W": "F3",
129 "R4W": "F4",
130 "DCI": "F5",
131 "ACI": "F6",
132 "Rext": "F7",
133 }
134
135 INV_MODES = {v: k for k, v in MODES.items()}
136
137 RANGES = {"DCV": {3E-2: "R-2", 3E-1: "R-1", 3: "R0", 30: "R1", 300: "R2",
138 "auto": "RA"},
139 "ACV": {3E-1: "R-1", 3: "R0", 30: "R1", 300: "R2", "auto": "RA"},
140 "R2W": {30: "R1", 300: "R2", 3E3: "R3", 3E4: "R4", 3E5: "R5",
141 3E6: "R6", 3E7: "R7", "auto": "RA"},
142 "R4W": {30: "R1", 300: "R2", 3E3: "R3", 3E4: "R4", 3E5: "R5",
143 3E6: "R6", 3E7: "R7", "auto": "RA"},
144 "DCI": {3E-1: "R-1", 3: "R0", "auto": "RA"},
145 "ACI": {3E-1: "R-1", 3: "R0", "auto": "RA"},
146 "Rext": {3E7: "R7", "auto": "RA"},
147 }
148
149 TRIGGERS = {
150 "auto": "T1",
151 "internal": "T1",
152 "external": "T2",
153 "single": "T3",
154 "hold": "T4",
155 "fast": "T5",
156 }
157
158 class ERRORS(IntFlag):
159 """Enum element for errror bit decoding
160 """
161 AD_LINK = 32 # AD link error
162 AD_SELFCHK = 16 # AD self check error
163 AD_SLOPE = 8 # AD slope error
164 ROM = 4 # Control ROM error
165 RAM = 2 # RAM selftest failed
166 CALIBRATION = 1 # Calibration checksum error or cal range issue
167 NO_ERR = 0 # Should be obvious
168
169 # commands/properties for instrument control
170 @property
171 def active_connectors(self):
172 """Return selected connectors ("front"/"back"), based on front-panel selector switch
173 """
174 selection = self.status.front_rear
175 if selection == 1:
176 return "front"
177 else:
178 return "back"
179
180 @property
181 def auto_range_enabled(self):
182 """ Property describing the auto-ranging status
183
184 ====== ============================================
185 Value Status
186 ====== ============================================
187 True auto-range function activated
188 False manual range selection / auto-range disabled
189 ====== ============================================
190
191 The range can be set with the :py:attr:`range` property
192 """
193 selection = self.status.auto_range
194 return bool(selection)
195
196 @property
197 def auto_zero_enabled(self):
198 """ Return auto-zero status, this property can be set
199
200 ====== ==================
201 Value Status
202 ====== ==================
203 True auto-zero active
204 False auto-zero disabled
205 ====== ==================
206
207 """
208 selection = self.status.auto_zero
209 return bool(selection)
210
211 @auto_zero_enabled.setter
212 def auto_zero_enabled(self, value):
213 az_set = int(value)
214 az_str = "Z" + str(int(strict_discrete_set(az_set, [0, 1])))
215 self.write(az_str)
216
217 @property
218 def calibration_enabled(self):
219 """Return calibration enable switch setting,
220 based on front-panel selector switch
221
222 ====== ===================
223 Value Status
224 ====== ===================
225 True calbration possible
226 False calibration locked
227 ====== ===================
228
229 """
230 selection = self.status.cal_enable
231 return bool(selection)
232
233 def check_errors(self):
234 """
235 Method to read the error status register
236
237 :return error_status: one byte with the error status register content
238 :rtype error_status: int
239 """
240 # Read the error status register only one time for this method, as
241 # the manual states that reading the error status register also clears it.
242 current_errors = self.error_status
243 if current_errors != 0:
244 log.error("HP3478A error detected: %s", self.ERRORS(current_errors))
245 return self.ERRORS(current_errors)
246
247 error_status = HPLegacyInstrument.measurement(
248 "E",
249 """Checks the error status register
250
251 """,
252 cast=int,
253 )
254
255 def display_reset(self):
256 """ Reset the display of the instrument.
257
258 """
259 self.write("D1")
260
261 display_text = HPLegacyInstrument.setting(
262 "D2%s",
263 """Displays up to 12 upper-case ASCII characters on the display.
264
265 """,
266 set_process=(lambda x: str.upper(x[0:12])),
267 )
268
269 display_text_no_symbol = HPLegacyInstrument.setting(
270 "D3%s",
271 """Displays up to 12 upper-case ASCII characters on the display and
272 disables all symbols on the display.
273
274 """,
275 set_process=(lambda x: str.upper(x[0:12])),
276 )
277
278 measure_ACI = HPLegacyInstrument.measurement(
279 MODES["ACI"],
280 """
281 Returns the measured value for AC current as a float in A.
282
283 """,
284 )
285
286 measure_ACV = HPLegacyInstrument.measurement(
287 MODES["ACV"],
288 """
289 Returns the measured value for AC Voltage as a float in V.
290
291 """,
292 )
293
294 measure_DCI = HPLegacyInstrument.measurement(
295 MODES["DCI"],
296 """
297 Returns the measured value for DC current as a float in A.
298
299 """,
300 )
301
302 measure_DCV = HPLegacyInstrument.measurement(
303 MODES["DCV"],
304 """
305 Returns the measured value for DC Voltage as a float in V.
306
307 """,
308 )
309
310 measure_R2W = HPLegacyInstrument.measurement(
311 MODES["R2W"],
312 """
313 Returns the measured value for 2-wire resistance as a float in Ohm.
314
315 """,
316 )
317
318 measure_R4W = HPLegacyInstrument.measurement(
319 MODES["R4W"],
320 """
321 Returns the measured value for 4-wire resistance as a float in Ohm.
322
323 """,
324 )
325
326 measure_Rext = HPLegacyInstrument.measurement(
327 MODES["Rext"],
328 """
329 Returns the measured value for extended resistance mode (>30M, 2-wire)
330 resistance as a float in Ohm.
331 """,
332 )
333
334 @property
335 def mode(self):
336 """Return current selected measurement mode, this propery can be set.
337 Allowed values are
338
339 ==== ==============================================================
340 Mode Function
341 ==== ==============================================================
342 ACI AC current
343 ACV AC voltage
344 DCI DC current
345 DCV DC voltage
346 R2W 2-wire resistance
347 R4W 4-wire resistance
348 Rext extended resistance method (requires additional 10 M resistor)
349 ==== ==============================================================
350 """
351 current_mode = self.INV_MODES["F" + str(self.status.function)]
352 return current_mode
353
354 @mode.setter
355 def mode(self, value):
356 mode_set = self.MODES[strict_discrete_set(value, self.MODES)]
357 self.write(mode_set)
358
359 @property
360 def range(self):
361 """Returns the current measurement range, this property can be set.
362
363 Valid values are :
364
365 ==== =======================================
366 Mode Range
367 ==== =======================================
368 ACI 0.3, 3, auto
369 ACV 0.3, 3, 30, 300, auto
370 DCI 0.3, 3, auto
371 DCV 0.03, 0.3, 3, 30, 300, auto
372 R2W 30, 300, 3000, 3E4, 3E5, 3E6, 3E7, auto
373 R4W 30, 300, 3000, 3E4, 3E5, 3E6, 3E7, auto
374 Rext 3E7, auto
375 ==== =======================================
376
377 """
378 cur_mode = self.INV_MODES["F" + str(self.status.function)]
379 if cur_mode == "DCV":
380 correction_factor = 3
381 elif cur_mode in ["ACV", "ACI", "DCI"]:
382 correction_factor = 2
383 else:
384 correction_factor = 0
385 current_range = 3 * math.pow(10, self.status.range - correction_factor)
386 return current_range
387
388 @range.setter
389 def range(self, value):
390 cur_mode = self.mode
391 value = strict_discrete_set(value, self.RANGES[cur_mode])
392 set_range = self.RANGES[cur_mode][value]
393 self.write(set_range)
394
395 @property
396 def resolution(self):
397 """Returns current selected resolution, this property can be set.
398
399 Possible values are 3,4 or 5 (for 3 1/2, 4 1/2 or 5 1/2 digits of resolution)
400 """
401 number_of_digit = 6 - self.status.digits
402 return number_of_digit
403
404 @resolution.setter
405 def resolution(self, value):
406 resolution_string = "N" + str(strict_discrete_set(value, [3, 4, 5]))
407 self.write(resolution_string)
408
409 @property
410 def SRQ_mask(self):
411 """Return current SRQ mask, this property can be set,
412
413 bit assigment for SRQ:
414
415 ========= ==========================
416 Bit (dec) Description
417 ========= ==========================
418 1 SRQ when Data ready
419 4 SRQ when Syntax error
420 8 SRQ when internal error
421 16 front panel SQR button
422 32 SRQ by invalid calibration
423 ========= ==========================
424
425 """
426
427 return self.status.SRQ
428
429 @SRQ_mask.setter
430 def SRQ_mask(self, value):
431 self.write(f"M{strict_range(value, [0, 63]):02o}")
432
433 @property
434 def trigger(self):
435 """Return current selected trigger mode, this property can be set
436
437 Possibe values are:
438
439 ======== ===========================================
440 Value Meaning
441 ======== ===========================================
442 auto automatic trigger (internal)
443 internal automatic trigger (internal)
444 external external trigger (connector on back or GET)
445 hold holds the measurement
446 fast fast trigger for AC measurements
447 ======== ===========================================
448
449 """
450 status = self.status
451 i_trig = status.int_trig
452 e_trig = status.ext_trig
453 if i_trig == 0:
454 if e_trig == 0:
455 trigger_mode = "hold"
456 else:
457 trigger_mode = "external"
458 else:
459 trigger_mode = "internal"
460 return trigger_mode
461
462 @trigger.setter
463 def trigger(self, value):
464 trig_set = self.TRIGGERS[strict_discrete_set(value, self.TRIGGERS)]
465 self.write(trig_set)
466
467 @property
468 def calibration_data(self):
469 """Read or write the calibration data as an array of 256 values between 0 and 15.
470
471 The calibration data of an HP 3478A is stored in a 256x4 SRAM that is
472 permanently powered by a 3v Lithium battery. When the battery runs
473 out, the calibration data is lost, and recalibration is required.
474
475 When read, this property fetches and returns the calibration data so that it can be
476 backed up.
477
478 When assigned a value, it similarly expects an array of 256 values between 0 and 15,
479 and writes the values back to the instrument.
480
481 When writing, exceptions are raised for the following conditions:
482
483 * The CAL ENABLE switch at the front of the instrument is not set to ON.
484 * The array with values does not contain exactly 256 elements.
485 * The array with values does not pass a verification check.
486
487 IMPORTANT: changing the calibration data results in permanent loss of
488 the previous data. Use with care!
489
490 """
491 cal_data = []
492 for addr in range(0, 256):
493 # To fetch one nibble: 'W<address>', where address is a raw 8-bit number.
494 cmd = bytes([ord('W'), addr])
495 self.write_bytes(cmd)
496 rvalue = self.read_bytes(1)[0]
497 # 'W' command reads a nibble from the SRAM, but then adds a value of 64 to return
498 # it as an ASCII value.
499 if rvalue < 64 or rvalue >= 80:
500 raise Exception("calibration nibble out of range")
501 cal_data.append(rvalue-64)
502
503 return cal_data
504
505 @calibration_data.setter
506 def calibration_data(self, cal_data):
507 """Setter to write the calibration data.
508
509 """
510
511 if not self.calibration_enabled:
512 raise Exception("CAL ENABLE switch not set to ON")
513
514 self.write_calibration_data(cal_data, True)
515
516 def write_calibration_data(self, cal_data, verify_calibration_data=True):
517 """Method to write calibration data.
518
519 The cal_data parameter format is the same as the ``calibration_data`` property.
520
521 Verification of the cal_data array can be bypassed by setting
522 ``verify_calibration_data`` to ``False``.
523
524 """
525 if verify_calibration_data and not self.verify_calibration_data(cal_data):
526 raise ValueError("cal_data verification fail.")
527
528 for addr in range(0, 256):
529 # To write one nibble: 'X<address><byte>', where address and byte are raw 8-bit numbers.
530 cmd = bytes([ord('X'), addr, cal_data[addr]])
531 self.write_bytes(cmd)
532 pass
533
534 def verify_calibration_entry(self, cal_data, entry_nr):
535 """Verify the checksum of one calibration entry.
536
537 Expects an array of 256 values with calibration data, and an entry
538 number from 0 to 18.
539
540 Returns True when the checksum of the specified calibration entry
541 is correct.
542
543 """
544 if len(cal_data) != 256:
545 raise Exception("cal_data must contain 256 values")
546
547 sum = 0
548 for idx in range(0, 13):
549 val = cal_data[entry_nr*13 + idx + 1]
550 if idx != 11:
551 sum += val
552 else:
553 sum += val*16
554 return sum == 255
555
556 def verify_calibration_data(self, cal_data):
557 """Verify the checksums of all calibration entries.
558
559 Expects an array of 256 values with calibration data.
560
561 :return calibration_correct: True when all checksums are correct.
562 :rtype calibration_correct: boolean
563
564 """
565 for entry_nr in range(0, 19):
566 if entry_nr in [5, 16, 18]:
567 continue
568 if not self.verify_calibration_entry(cal_data, entry_nr):
569 return False
570 return True