4

I'm still new to python and instrument controlling and I'm facing some issues that I couldn't find answers to yet. I'm using PyVisa to control a monochromator (Spectral Products dk240) via rs232. (Python 3.5, PyVisa 1.8)

I can write commands and read the response by setting the right termination character. The problem is that sometimes the instrument response is a single byte without termination, and then I get a timeout (even though I see the response I want on a port monitor).

I tried to use read_raw to get the single byte but it doesn't work. Here's a simple version of my code:

import pyvisa
rm = pyvisa.ResourceManager()
instrument = rm.open_resource('ASRL1::INSTR')
instrument.baud_rate= 9600
instrument.data_bits=8
instrument.stop_bits = pyvisa.constants.StopBits.one
instrument.parity = pyvisa.constants.Parity.none
instrument.read_termination = chr(24)   #specified in the manual

instrument.write(chr(33))    # command to get the serial number
instrument.read()            # this works!

instrument.write(chr(27))    # echo command
                             # instrument replies one byte echo (seen on port monitor)
instrument.read_raw(1)       # I get a timeout here

and the error:

raise errors.VisaIOError(ret_value)
pyvisa.errors.VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.

I also tried to set the termination character to "none" so visa wouldn't wait for it, but still get the timeout. Additionally, I tried to read the serial number with read_raw(1), but instead of one byte I get the full answer from the instrument, why is that?

any help will be greatly appreciated!!!

sgmotti
  • 41
  • 1
  • 5

1 Answers1

3

It's probably a little late for that but I helped myself while I was having this problem with an own function that depends on the bytes_in_buffer attribute.

def read_all(devicehandle):

    with devicehandle.ignore_warning(constants.VI_SUCCESS_DEV_NPRESENT, constants.VI_SUCCESS_MAX_CNT):

        try:
            data , status = devicehandle.visalib.read(devicehandle.session, devicehandle.bytes_in_buffer)
        except:
            pass
    return data

Remark: it doesn't work with ethernet connections. The attribute is not present.

Nander Speerstra
  • 1,496
  • 6
  • 24
  • 29
Bacid
  • 31
  • 5
  • Thank you for this. I encountered a weird instrument that timeouts when using `instrument.query(...)` but works fine with an infinite loop of your `instrument.visalib.read(instrument.session, 1)` that I break when the returned value is `"\r"`. Your solution is a good workaround this sorcery. – Guimoute Oct 08 '20 at 15:26