python-3.xpyvisa

How to set a voltage sweep effectively in just one command? Python


I am trying to do a Current-Voltage sweep using PyVisa with a Keithley 6430 doing a complete loop of voltages going from zero to both positive and negative values: from 0 to +5, back to 0 and from 0 to -5 and back to 0 again.

To do that I basically used 4 different ranges and 4 different for loops like so:

 #Voltage values
 low = -5
 middle = 0
 high = 5
 step = 1

 voltage_range1 = np.arange(middle,high,step)
 voltage_range2 = np.arange(high,middle,-step)
 voltage_range3 = np.arange(middle,low,-step)
 voltage_range4 = np.arange(low,middle+1,step)

 data = [] 

 for voltage in voltage_range1:
 keithley.write('source:voltage:level {}'.format(voltage)) 
 data.append(keithley.query_ascii_values('read?'))

 for voltage in voltage_range2:
 keithley.write('source:voltage:level {}'.format(voltage)) 
 data.append(keithley.query_ascii_values('read?'))

 for voltage in voltage_range3:
 keithley.write('source:voltage:level {}'.format(voltage)) 
 data.append(keithley.query_ascii_values('read?'))

 for voltage in voltage_range4:
 keithley.write('source:voltage:level {}'.format(voltage)) 
 data.append(keithley.query_ascii_values('read?'))

The program works properly, but I couldn't find a more functional way to do this, like setting the whole process in just one voltage_range and avoid using 4 loops. Do you have any ideas?


Solution

  • I think this could work:

    voltage_range = np.array([]) # initialize
    
    for array in (voltage_range1,
                  voltage_range2,
                  voltage_range3,
                  voltage_range4)
        voltage_range = np.append(voltage_range, array)
    

    And then you only have one loop iterating over voltage_range. You can replace the voltage_rangeN directly with the np.arange() too and basically you can make any sequence of values you'd like just by changing their position in the parenthesis.

    So after modification your program looks like this:

    # Voltage values
    low = -5
    middle = 0
    high = 5
    step = 1
    
    data = [] 
    voltage_range = np.array([]) # initialize
    
    for array in (np.arange(middle,high,step),
                  np.arange(high,middle,-step),
                  np.arange(middle,low,-step),
                  np.arange(low,middle+1,step)):
        voltage_range = np.append(voltage_range, array)
    
    for voltage in voltage_range:
        keithley.write('source:voltage:level {}'.format(voltage)) 
        data.append(keithley.query_ascii_values('read?'))
    

    You can merge the ranges 2 and 3 too:

    for array in (np.arange(middle,high,step),
                  np.arange(high,low-1,-step),
                  np.arange(low,middle+1,step)):