Search code examples
pythonc++visa

Device Communication with VISA work in Python, but not in C++


I'm learning to use VISA (A National Instruments set of modules) to communicate with some NI Devices. I previously used Python, but now I'm also learning to work with C++.

I'm having difficultly connecting to a device using the VISA module in C++, but have no trouble connecting to the device using the PyVisa module in Python.

I've attached two snippets of code that I'm using. The Python code works, the C++ does not, even though they should operate in the same way. Does anyone had idea what I'm doing wrong?

###################
# PYVISA COMMANDS #
###################

import visa as vi
import time

try:
    # Create the resource manager
    rm = vi.ResourceManager()
    # Connect to resource from USB
    myI = rm.open_resource('ASRL3::INSTR')

    # Setup resource identities for NanoPZ Control Box
    myI.flow_control = 6
    myI.read_termination = 'CR'
    myI.write_termination = 'CR'
    myI.timeout = 3000
    myI.baud_rate = 19200
    myI.stopbits = 1.0

    myI = rm.open_resource('ASRL3::INSTR')
    myI.write('1MX2') # A Very simple command, this works in Python
except:
    "Hello"

# Close Communications
myI.close()

//////////////
// C++ VISA //
//////////////

#include <iostream>
#include <stdio.h>
#include <windows.h>
#include "visa.h"

int main() {

    ViSession defaultRM, instr_NanoPZ; // The device is NanoPZ

    // Open a channel with the VI Module
    viOpenDefaultRM(&defaultRM);
    Sleep(1000);

    // Open a channel with the instrument we want to use
    viOpen(defaultRM, "ASRL3::INSTR", VI_NULL, VI_NULL, &instr_NanoPZ);
    Sleep(1000);

    viSetAttribute(instr_NanoPZ, VI_ATTR_ASRL_BAUD, (ViUInt32) 19200); // Baud Rate
    viSetAttribute(instr_NanoPZ, VI_ATTR_TMO_VALUE, (ViUInt32) 3000); // Timeout
    viSetAttribute(instr_NanoPZ, VI_ATTR_TERMCHAR, 0x0D);
    viSetAttribute(instr_NanoPZ, VI_ATTR_ASRL_FLOW_CNTRL, (ViUInt16) 6); // Flow control
    viSetAttribute(instr_NanoPZ, VI_ATTR_ASRL_STOP_BITS, (ViUInt16) 1.0); // Stop bits

    viOpen(defaultRM, "ASRL3::INSTR", VI_NULL, VI_NULL, &instr_NanoPZ);
    Sleep(1000);

    viPrintf(instr_NanoPZ, "1MX2"); // The same, simple command, does not work in C++
    Sleep(1000);

    viClose(instr_NanoPZ);
    viClose(defaultRM);

    return 0;
}

Solution

  • viSetAttribute(instr_NanoPZ, VI_ATTR_ASRL_STOP_BITS, (ViUInt16) 1.0);
    

    should be

    viSetAttribute(instr_NanoPZ, VI_ATTR_ASRL_STOP_BITS, VI_ASRL_STOP_ONE);
    

    and replace 6 in

    viSetAttribute(instr_NanoPZ, VI_ATTR_ASRL_FLOW_CNTRL, (ViUInt16) 6); 
    

    with the macros defining the type of flow control you want.

    viSetAttribute(instr_NanoPZ, VI_ATTR_ASRL_FLOW_CNTRL, 
                   VI_ASRL_FLOW_RTS_CTS | VI_ASRL_FLOW_DTR_DSR);