1.. _intro-communication:
2
3Communicating with your instrument
4==================================
5
6.. include:: ../substitutions.sub
7
8.. note:: If you have been using PyVISA before version 1.5, you might want to
9          read :ref:`faq-migrating`.
10
11
12An example
13----------
14
15Let's go *in medias res* and have a look at a simple example::
16
17    >>> import pyvisa
18    >>> rm = pyvisa.ResourceManager()
19    >>> rm.list_resources()
20    ('ASRL1::INSTR', 'ASRL2::INSTR', 'GPIB0::14::INSTR')
21    >>> my_instrument = rm.open_resource('GPIB0::14::INSTR')
22    >>> print(my_instrument.query('*IDN?'))
23
24This example already shows the two main design goals of PyVISA: preferring
25simplicity over generality, and doing it the object-oriented way.
26
27After importing ``pyvisa``, we create a ``ResourceManager`` object. If called
28without arguments, PyVISA will prefer the default backend (IVI) which tries to
29find the VISA shared library for you. If it fails it will fall back to
30pyvisa-py if installed. You can check what backend is used and the location of
31the shared library used, if relevant, simply by:
32
33    >>> print(rm)
34    <ResourceManager('/path/to/visa.so')>
35
36.. note::
37
38    In some cases, PyVISA is not able to find the library for you resulting in
39    an ``OSError``. To fix it, find the library path yourself and pass it to
40    the ResourceManager constructor. You can also specify it in a configuration
41    file as discussed in :ref:`intro-configuring`.
42
43
44Once that you have a ``ResourceManager``, you can list the available resources
45using the ``list_resources`` method. The output is a tuple listing the
46:ref:`intro-resource-names`. You can use a dedicated regular expression syntax
47to filter the instruments discovered by this method. The syntax is described in
48details in |list_resources|. The default value is '?*::INSTR' which means that
49by default only instrument whose resource name ends with '::INSTR' are listed
50(in particular USB RAW resources and TCPIP SOCKET resources are not listed).
51
52In this case, there is a GPIB instrument with instrument number 14, so you ask
53the ``ResourceManager`` to open "'GPIB0::14::INSTR'" and assign the returned
54object to the *my_instrument*.
55
56Notice ``open_resource`` has given you an instance of ``GPIBInstrument`` class
57(a subclass of the more generic ``Resource``).
58
59    >>> print(my_instrument)
60    <GPIBInstrument('GPIB::14')>
61
62There many ``Resource`` subclasses representing the different types of
63resources, but you do not have to worry as the ``ResourceManager`` will provide
64you with the appropriate class. You can check the methods and attributes of
65each class in the :ref:`api_resources`
66
67Then, you query the device with the following message: ``'\*IDN?'``.
68Which is the standard GPIB message for "what are you?" or -- in some cases --
69"what's on your display at the moment?". ``query`` is a short form for a
70``write`` operation to send a message, followed by a ``read``.
71
72So::
73
74    >>> my_instrument.query("*IDN?")
75
76is the same as::
77
78    >>> my_instrument.write('*IDN?')
79    >>> print(my_instrument.read())
80
81
82.. note::
83
84    You can access all the opened resources by calling
85    ``rm.list_opened_resources()``. This will return a list of ``Resource``,
86    however note that this list is not dynamically updated.
87
88
89Getting the instrument configuration right
90------------------------------------------
91
92For most instruments, you actually need to properly configure the instrument
93so that it understands the message sent by the computer (in particular how to
94identifies the end of the commands) and so that computer knows when the
95instrument is done talking. If you don't you are likely to see a |VisaIOError|
96reporting a timeout.
97
98For message based instruments (which covers most of the use cases), this
99usually consists in properly setting the |read_termination| and
100|write_termination| attribute of the resource. Resources have more attributes
101described in :ref:`intro-resources`, but for now we will focus on those two.
102
103The first place to look for the values you should set for your instrument is
104the manual. The information you are looking is usually located close to the
105beginning of the IO operation section of the manual. If you cannot find the
106value, you can try to iterate through a couple of standard values but this is
107not recommended approach.
108
109Once you have that information you can try to configure your instrument and
110start communicating as follows::
111
112    >>> my_instrument.read_termination = '\n'
113    >>> my_instrument.write_termination = '\n'
114    >>> my_instrument.query('*IDN?')
115
116Here we use `'\n'` known as 'line feed'. This is a common value, another one is
117`'\r'` i.e. 'carriage return', and in some cases the null byte '\0' is used.
118
119In an ideal world, this will work and you will be able to get an answer from
120your instrument. If it does not, it means the settings are likely wrong (the
121documentation does not always shine by its clarity). In the following we will
122discuss common debugging tricks, if nothing works feel free to post on the
123PyVISA `issue tracker`_. If you do be sure to describe in detail your setup and
124what you already attempted.
125
126.. _`issue tracker`: https://github.com/pyvisa/pyvisa/issues
127
128.. note::
129
130    The particular case of reading back large chunk of data either in ASCII
131    or binary format is not discussed below but in :ref:`intro-rvalues`.
132
133Making sure the instrument understand the command
134^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
135
136When using query, we are testing both writing to and reading from the
137instrument. The first thing to do is to try to identify if the issue occurs
138during the write or the read operation.
139
140If your instrument has a front panel, you can check for errors (some instrument
141will display a transient message right after the read). If an error occurs,
142it may mean your command string contains a mistake or the instrument is using
143a different set of command (some instrument supports both a legacy set of
144commands and SCPI commands). If you see no error it means that either the
145instrument did not detect the end of your message or you just cannot read it.
146The next step is to determine in what situation we are.
147
148To do so, you can look for a command that would produce a visible/measurable
149change on the instrument and send it. In the absence of errors, if the expected
150change did not occur it means the instrument did not understand that the
151command was complete. This points out to an issue with the |write_termination|.
152At this stage, you can go back to the manual (some instruments allow to switch
153between the recognized values), or try standards values (such as `'\n'`,
154`'\r'`, combination of those two, `'\0'`).
155
156Assuming you were able to confirm that the instrument understood the command
157you sent, it means the reading part is the issue, which is easier to
158troubleshoot. You can try different standard values for the |read_termination|,
159but if nothing works you can use the |read_bytes| method. This method will read
160at most the number of bytes specified. So you can try reading one byte at a
161time till you encounter a time out. When that happens most likely the last
162character you read is the termination character. Here is a quick example:
163
164.. code:: python
165
166    my_instrument.write('*IDN?')
167    while True:
168        print(my_instrument.read_bytes(1))
169
170If |read_bytes| times out on the first read, it actually means that the
171instrument did not answer. If the instrument is old it may be because your are
172too fast for it, so you can try waiting a bit before reading (using
173`time.sleep` from Python standard library). Otherwise, you either use a command
174that does not cause any answer or actually your write does not work (go back
175up a couple of paragraph).
176
177.. note::
178
179    Some instruments may be slow in answering and may require you to either
180    increase the timeout or specify a delay between the write and read
181    operation. This can be done globally using |query_delay| or passing
182    ``delay=0.1`` for example to wait 100 ms after writing before reading.
183
184.. note::
185
186    When transferring large amount of data the total transfer time may exceed
187    the timeout value in which case increasing the timeout value should fix
188    the issue.
189
190.. note::
191
192    It is possible to disable the use of teh termination character to detect
193    the end of an input message by setting |read_termination| to ``""``. Care
194    has to be taken for the case of serial instrument for which the method used
195    to determine the end of input is controlled by the |end_input| attribute
196    and is set by default to use the termination character. To fully disable
197    the use of the termination character its value should be changed.
198
199The above focused on using only PyVISA,  if you are running Windows, or MacOS
200you are likely to have access to third party tools that can help. Some tips to
201use them are given in the next section.
202
203.. note::
204
205    Some instruments do not react well to a communication error, and you may
206    have to restart it to get it to work again.
207
208Using third-party softwares
209^^^^^^^^^^^^^^^^^^^^^^^^^^^
210
211The implementation of VISA from National Instruments and Keysight both come
212with tools (NIMax, Keysight Connection Expert) that can be used to figure out
213what is wrong with your communication setup.
214
215In both cases, you can open an interactive communication session to your
216instrument and tune the settings using a GUI (which can make things easier).
217The basic procedure is the one described above, if you can make it work in
218one of those tools you should be able, in most cases, to get it to work in
219PyVISA. However if it does not work using those tools, it won't work in
220PyVISA.
221
222For serial instruments (true or emulated over USB), you can also try to
223directly communicate with it using Putty or Tera Term on Windows, CoolTerm or
224Terminal / screen on macOS.
225
226
227Hopefully those simple tips will allow you to get through. In some cases, it
228may not be the case and you are always welcome to ask for help (but realize
229that the maintainers are unlikely to have access to the instrument you are
230having trouble with).
231