프로그래밍/Python

[Python] GPIB 를 통한 계측기 제어 실패기

채윤아빠 2023. 8. 29. 09:04
728x90
반응형

이더넷을 통한 TCPIP 연결로 계측기 제어는 아무런 문제 없이 잘 수행해 왔었는데, 꼭 GPIB로 계측기를 제어해야할 상황이 발생하였습니다. 연결 문자열만 변경하면 특별한 문제 없이 바로 계측기 제어에 문제가 없을줄 알았지만, 연결부터 되지 않아서 몇 일을 헤맸습니다.

GPIB 를 통한 계측기 연결을 위해 헤맸던 그 상황들을 기록해 둡니다.


GPIB 연결 오류 발생 확인

파이썬을 설치하면 기본 제공되는 "IDLE Shell"에서 "ResourceManager.list_resources()"로 연결된 계측기를 다음과 같이 확인해 보았습니다.

Python 3.10.0 (tags/v3.10.0:b494f59, Oct  4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.

import pyvisa
rm = pyvisa.ResourceManager()
rm.list_resources()
('TCPIP0::K-N5224B-13293.local::hislip0::INSTR', 'TCPIP0::K-N5224B-13293.local::inst0::INSTR')

TCPIP로 설정된 계측기가 목록에 표시되었지만, GPIB로 연결된 계측기들이 나타나지 않아서 다음과 같이 직접 연결을 시도하였으나 오류가 발생하였습니다.

client = rm.open_resource('GPIB0::9::INSTR')
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in 
    client = rm.open_resource('GPIB0::9::INSTR')
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 3284, in open_resource
    res.open(access_mode, open_timeout)
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\resources\resource.py", line 282, in open
    self.session, status = self._resource_manager.open_bare_resource(
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 3209, in open_bare_resource
    return self.visalib.open(self.session, resource_name, access_mode, open_timeout)
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\ctwrapper\functions.py", line 1851, in open
    ret = library.viOpen(
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 226, in _return_handler
    return self.handle_return_value(session, ret_value)  # type: ignore
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 251, in handle_return_value
    raise errors.VisaIOError(rv)
pyvisa.errors.VisaIOError: VI_ERROR_RSRC_NFOUND (-1073807343): Insufficient location information or the requested device or resource is not present in the system.

"ResourceManager.list_resources()"로 확인된 계측기 중 하나를 연결하여 확인해 보니 잘 동작합니다. ㅠ.ㅠ

client= rm.open_resource('TCPIP0::K-N5224B-13293.local::hislip0::INSTR')
client.query('*IDN?')
'Keysight Technologies,N5225B,MY58421913,A.13.80.12\n'
client.close()
client= rm.open_resource('TCPIP0::192.168.0.6::INSTR')
client.close()
print(rm)
Resource Manager of Visa Library at C:\WINDOWS\system32\visa32.dll

여러 문서를 찾아 보니, "ResourceManager" 객체를 생성할 때, VISA Library를 직접 지정해 줄 수가 있어서, PC에 존재하는 VISA 관련 Library를 입력하여 연결을 시도하여 보았으나, 다음과 같은 오류들만 발생하였습니다.

rm = pyvisa.ResourceManager('C:\Program Files\IVI Foundation\VISA\Win64\agvisa\agbin\visa32.dll')
Traceback (most recent call last):
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 162, in _init
    lib = Library(self.library_path)
  File "C:\Dev\Python\Python310\lib\ctypes\__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'C:\Program Files\IVI Foundation\VISA\Win64gvisagbinisa32.dll' (or one of its dependencies). Try using the full path with constructor syntax.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in 
    rm = pyvisa.ResourceManager('C:\Program Files\IVI Foundation\VISA\Win64\agvisa\agbin\visa32.dll')
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 2992, in __new__
    visa_library = open_visa_library(visa_library)
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 2904, in open_visa_library
    return cls(argument)
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 191, in __new__
    obj._init()
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 164, in _init
    raise errors.LibraryError.from_exception(exc, self.library_path)
pyvisa.errors.LibraryError: Error while accessing C:\Program Files\IVI Foundation\VISA\Win64gvisagbinisa32.dll: Could not find module 'C:\Program Files\IVI Foundation\VISA\Win64gvisagbinisa32.dll' (or one of its dependencies). Try using the full path with constructor syntax.

로딩이 된 라이브러이에서는 GPIB로 연결된 계측기 목록은 표시되지 않았습니다.

m = pyvisa.ResourceManager('C:/Program Files/IVI Foundation/VISA/Win64/agvisa/agbin/visa32.dll')
rm.list_resources()
('TCPIP0::K-N5224B-13293.local::hislip0::INSTR', 'TCPIP0::K-N5224B-13293.local::inst0::INSTR')
rm = pyvisa.ResourceManager('C:/Program Files/IVI Foundation/VISA/Win64/agvisa/agbin/agvisa32.dll')
rm.list_resources()
()
rm = pyvisa.ResourceManager('C:/Program Files (x86)/IVI Foundation/VISA/WinNT/agvisa/agbin/agvisa32.dll')
Traceback (most recent call last):
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 162, in _init
    lib = Library(self.library_path)
  File "C:\Dev\Python\Python310\lib\ctypes\__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1은(는) 올바른 Win32 응용 프로그램이 아닙니다

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#23>", line 1, in 
    rm = pyvisa.ResourceManager('C:/Program Files (x86)/IVI Foundation/VISA/WinNT/agvisa/agbin/agvisa32.dll')
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 2992, in __new__
    visa_library = open_visa_library(visa_library)
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 2904, in open_visa_library
    return cls(argument)
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 191, in __new__
    obj._init()
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 164, in _init
    raise errors.LibraryError.from_exception(exc, self.library_path)
pyvisa.errors.LibraryError: Error while accessing C:/Program Files (x86)/IVI Foundation/VISA/WinNT/agvisa/agbin/agvisa32.dll: [WinError 193] %1은(는) 올바른 Win32 응용 프로그램이 아닙니다
rm = pyvisa.ResourceManager('C:/Program Files (x86)/IVI Foundation/VISA/WinNT/agvisa/agbin/visa32.dll')
rm.list_resources()
()
rm = pyvisa.ResourceManager('C:/Windows/SysWOW64/visa32.dll')
Traceback (most recent call last):
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 162, in _init
    lib = Library(self.library_path)
  File "C:\Dev\Python\Python310\lib\ctypes\__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1은(는) 올바른 Win32 응용 프로그램이 아닙니다

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#26>", line 1, in 
    rm = pyvisa.ResourceManager('C:/Windows/SysWOW64/visa32.dll')
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 2992, in __new__
    visa_library = open_visa_library(visa_library)
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 2904, in open_visa_library
    return cls(argument)
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\highlevel.py", line 191, in __new__
    obj._init()
  File "C:\Dev\Python\Python310\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 164, in _init
    raise errors.LibraryError.from_exception(exc, self.library_path)
pyvisa.errors.LibraryError: Error while accessing C:/Windows/SysWOW64/visa32.dll: [WinError 193] %1은(는) 올바른 Win32 응용 프로그램이 아닙니다
rm = pyvisa.ResourceManager('C:/Windows/System32/visa32.dll')
rm.list_resources()
('TCPIP0::K-N5224B-13293.local::hislip0::INSTR', 'TCPIP0::K-N5224B-13293.local::inst0::INSTR')
rm = pyvisa.ResourceManager('C:/Program Files/IVI Foundation/VISA/Win64/agvisa/agbin/agvisa32.dll')
rm.list_resources()
()

GPIB 연결문제 해결~

몇 일을 잊고 있다가 다시 인터넷을 검색하던 중 아래 소스를 참조하여 예제를 작성하여 동작시켜보니, 드디어 GPIB 계측기 연결에 성공하였습니다.

https://rfmw.em.keysight.com/digitalphotonics/flexdca/pg/content/topics/Python/a_python.htm

 

적용한 코드는 다음과 같습니다.

# -*- coding: utf-8 -*-
"""
pyvisa_test_and_show.py (Python 3.X)
Requires:
    - FlexDCA running on a PC or instrument. Edit the ADDRESS constant
    if not running on a PC.
    - Python 3.X
    - PyVISA to use VISA in Python 'https://sourceforge.net/projects/pyvisa/'
Python and the VISA library must have the same "bitness": 32 or
64-bit. Both 32 and 64-bit versions the VISA library are
installed by Keysight Connection Expert. PyVISA is the frontend for the
VISA library.
This script prints the installed Python and VISA versions and
checks the VISA environment and opens a connection with
FlexDCA that is running on a PC.
________________________________________________________________________
Copyright © 2016 Keysight Technologies Inc. All rights reserved.
You have a royalty-free right to use, modify, reproduce and distribute this
example files (and/or any modified version) in any way you find useful,
provided that you agree that Keysight has no warranty, obligations or
liability for any Sample Application Files.
_________________________________________________________________________
"""

import sys
import pyvisa as visa  # PyVISA library

ADDRESS = 'TCPIP0::localhost::hislip0,4880::INSTR'

rm = visa.ResourceManager(r'C:\WINDOWS\system32\visa64.dll')
print('\nVISA library version:\n  ', rm)
print('\nPython version:\n  ', sys.version)
print('\nList of instruments discovered by Keysight Connection Expert:')
i = 1
for key, value in rm.list_resources_info().items():
    print('\nInstrument ', str(i), ': ', key)
    print('  Interface type: ', value.interface_type)
    print('  Interface board number: ', value.interface_board_number)
    print('  Resource class: ', value.resource_class)
    print('  Resource name: ', value.resource_name)
    print('  Resource alias: ', value.alias)
    i += 1

위 코드를 실행결과는 다음과 같습니다.

VISA library version:
   Resource Manager of Visa Library at C:\WINDOWS\system32\visa64.dll

Python version:
   3.10.0 (tags/v3.10.0:b494f59, Oct  4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)]

List of instruments discovered by Keysight Connection Expert:

Instrument  1 :  GPIB0::2::INSTR
  Interface type:  InterfaceType.gpib
  Interface board number:  0
  Resource class:  INSTR
  Resource name:  GPIB0::2::INSTR
  Resource alias:  None

Instrument  2 :  GPIB0::8::INSTR
  Interface type:  InterfaceType.gpib
  Interface board number:  0
  Resource class:  INSTR
  Resource name:  GPIB0::8::INSTR
  Resource alias:  None

Instrument  3 :  GPIB0::9::INSTR
  Interface type:  InterfaceType.gpib
  Interface board number:  0
  Resource class:  INSTR
  Resource name:  GPIB0::9::INSTR
  Resource alias:  None

대부분의 DLL을 다 확인했었는데, 단 하나 "C:\WINDOWS\system32\visa64.dll"를 확인하지 못해서 해결하는데 더 오래 걸리고 말았습니다. 처음 파일을 검색할 때, "visa32.dll"로 검색하여... ㅠ.ㅠ


GPIB 관련 기타 삽질...

Keysight의 USB로 연결할 수 있는 GPIB 장치를 이용하였는데, 계측기를 옮겨 노트북에서 연결 하면 녹색불과 빨강색 불이 함께 들어오고, Keysight의 "IO Libraries"에서도 연결된 계측기를 확인할 수 없는 문제가 있었습니다.
재부팅을 해도 동일한 현상이 계속 발생하였는데... GPIB 케이블을 교체하고 연결 부위를 해제했다가 다시 단단히 체결하니, 정상적으로 연결을 할 수 있었습니다. 설마 케이블이 문제일 줄은...

그리고 노트북에서 처음 했을 때는 잘 동작하던 것이, USB 케이블을 뺐다가 다시 연결했을 때는 USB GPIB 장치에 빨강색 LED에 불이 들어오면서 연결이 안되었습니다. 장치 관리자 등에서는 모두 정상으로 보이는데 빨강색 LED가 꺼지지 않았습니다. 그래서 노트북을 재부팅하였더니 그제서야 빨강색 LED가 꺼지고 다시 정상적으로 연결이 가능했습니다.

마지막으로... Keysight의 "IO Libraries" 최신 버전을 구하여 설치할 것을 권고 드립니다. 간혹 몇몇 PC에서 Keysight의 "IO Libraries" 구 버전이 설치된 경우, GPIB 장치를 제대로 찾지 못하는 문제가 있었는데, Keysight의 "IO Libraries" 최신 버전을 설치하니 정상적으로 동작하였습니다.