#copied from jasmin spettel (she refined peter luitolds version)


from KeithleyV15 import SMU26xx
import matplotlib.pyplot as plt
import time
import datetime
import csv
import numpy as np

"""
EXAMPLE: characteristic curve of a diode

Schematic:

    --------------
    |            |
  -----         -|-
  | A | SMU     \|/
  -----         -|-
    |            |
    --------------

"""

""" ******* Connect to the SMU ******** """

# initialize the SMU and connect to it
smu = SMU26xx("TCPIP0::129.27.158.189::inst0::INSTR")

# get one channel of the SMU (we only need one for this measurement)
smua = smu.get_channel(smu.CHANNEL_A)

""" ******* Configure the SMU Channel A ******** """

# reset to default settings
smua.reset()
# setup the operation mode
smua.set_mode_voltage_source()
# set the voltage and current parameters
smua.set_voltage_range(20)
smua.set_voltage_limit(20)
smua.set_voltage(0)
smua.set_current_range(10e-5)
smua.set_current_limit(10e-5)
smua.set_current(0)

# display the current
smua.display_current()

# smua.set_measurement_speed_fast()


""" ******* For saving the data ******** """

# Creat unique filenames for saving the data
time_for_name = datetime.datetime.now().strftime("%Y_%m_%d_%H%M%S")
filename_csv = 'D:\Data\Praktikum\WS17\Group8\measurement' + time_for_name +'.csv'
filename_pdf = 'D:\Data\Praktikum\WS17\Group8\measurement' + time_for_name +'.pdf'

# Header for csv
with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow(["Voltage / V", "Current / A"])


""" ******* Make a voltage-sweep and do some measurements ******** """

# enable the output
smua.enable_output()

# define variables we store the measurement in
data_current = []
data_voltage = []

# define positive sweep parameters
smua.set_voltage(0)
sweep_pos = 1.5
sweep_neg = -5
sweep_step = 0.1
steps = int(sweep_pos  / sweep_step)
delay = 0.3# delay in seconds

# step through the voltages and get the values from the device
for nr in range(steps):
    # calculate the new voltage we want to set
    voltage_to_set = 0 + (sweep_step * nr)
    # set the new voltage to the SMU
    smua.set_voltage(voltage_to_set)
    time.sleep(delay)
    # get current and voltage from the SMU and append it to the list so we can plot it later
    [current, voltage] = smua.measure_current_and_voltage()
    print(str(voltage_to_set) +' V '+ str(current) + ' A')
    data_voltage.append(voltage)
    data_current.append(current)

    # Write the data in a csv
    with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow([voltage, current])
    

# return positive sweep
# step through the voltages and get the values from the device
for nr in range(steps):
    # calculate the new voltage we want to set
    voltage_to_set = sweep_pos - (sweep_step * nr)
    # set the new voltage to the SMU
    smua.set_voltage(voltage_to_set)
    time.sleep(delay)
    # get current and voltage from the SMU and append it to the list so we can plot it later
    [current, voltage] = smua.measure_current_and_voltage()
    print(str(voltage_to_set) +' V '+ str(current) + ' A')
    data_voltage.append(voltage)
    data_current.append(current)

    # Write the data in a csv
    with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow([voltage, current])

# negative sweep

steps = int(-sweep_neg  / sweep_step)
# step through the voltages and get the values from the device
for nr in range(steps):
    # calculate the new voltage we want to set
    voltage_to_set = 0 - (sweep_step * nr)
    # set the new voltage to the SMU
    smua.set_voltage(voltage_to_set)
    time.sleep(delay)
    # get current and voltage from the SMU and append it to the list so we can plot it later
    [current, voltage] = smua.measure_current_and_voltage()
    print(str(voltage_to_set) +' V '+ str(current) + ' A')
    data_voltage.append(voltage)
    data_current.append(current)

    # Write the data in a csv
    with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow([voltage, current])

# step through the voltages and get the values from the device
for nr in range(steps):
    # calculate the new voltage we want to set
    voltage_to_set = sweep_neg + (sweep_step * nr)
    # set the new voltage to the SMU
    smua.set_voltage(voltage_to_set)
    time.sleep(delay)
    # get current and voltage from the SMU and append it to the list so we can plot it later
    [current, voltage] = smua.measure_current_and_voltage()
    print(str(voltage_to_set) +' V '+ str(current) + ' A')
    data_voltage.append(voltage)
    data_current.append(current)

    # Write the data in a csv
    with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow([voltage, current])
    
# disable the output
smua.disable_output()

# properly disconnect from the device
smu.disconnect()

""" ******* Plot the Data we obtained ******** """

data_voltage_array = np.asarray(data_voltage)
data_current_array = np.asarray(data_current)
data_voltage_sat = abs(data_voltage_array)
data_current_sat = abs(data_current_array)

# plot the data
plt.plot(data_voltage_sat, data_current_sat,'x-', linewidth=2)

# set labels and a title
plt.xlabel('Voltage / V', fontsize=12)
plt.ylabel('Current / A', fontsize=12)
plt.title('Characteristic curve of a diode', fontsize=14)
plt.tick_params(labelsize = 30)
#plt.yscale('log')

plt.savefig(filename_pdf)
plt.show()

