﻿from StanfordResearchSystems import SR830
import visa
import math
import matplotlib.pyplot as plt
import time
import csv
import datetime

######################################################################
# Connect to the measurment instruments
######################################################################

# Connect to the SR570
rm = visa.ResourceManager()
sr570 = rm.open_resource('ASRL1::INSTR')

# connect to the SR830 Lock In Amplifier
sr830 = SR830()
sr830.connect("GPIB0::8::INSTR")
# Enable debug output so we see the commands that are sent to the instrument
sr830.enable_debug_output()
# Reset the device
#sr830.reset()

######################################################################
# Setup of the SR570 Current Amplifier
######################################################################

# disable the filters
sr570.write('FLTT 5')

# set the gain mode to high bw
sr570.write('GNMD 1')


######################################################################
# Setup of the SR830 Lock-in Amplifier
######################################################################

sr830.use_internal_reference()

# disable line filters
#sr830.disable_line_filters()
sr830.enable_line_filters()

# set the input to measure a voltage
sr830.set_input_mode_A()
sr830.set_input_shield_to_floating()
sr830.set_input_coupling_ac()

# set the reserve
#sr830.set_reserve_low_noise()
sr830.set_reserve_normal()


# set the displays to interesting things
sr830.display_ch1_r()
sr830.display_ch2_phi()

######################################################################
# define the parameters for the measurement
######################################################################

freq = 1.111e3
amplitude = 0.1
sr830.set_sine_output_level(amplitude)
sr830.set_reference_frequency(freq)

 # define the sweep parameters
sweep_pos = 0
sweep_neg = 5
sweep_step = 0.5        # for every direction
delay = 30


# define variables we store the measurement in
data_capacity = []                # Capacity 
data_BiasVoltage = []            # Bias voltage we set
data_phi = []                       # phaseshift
data_1_over_C_squared = []  # to save one over Capacity^2

# 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\diode' + time_for_name +'.csv'
filename_pdf = 'D:\Data\Praktikum\WS17\Group8\diode' + time_for_name +'.pdf'

# Header for csv
with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow(["f / Hz :" , str(freq)])
        writer.writerow(["Ue / V :" , str(amplitude)])
        writer.writerow(["Biasvoltage / V" , "Capacity / F", "Phase / °"])

# Some parameters for the SR830
sr830.set_time_constant(3)
#sr830.set_sensitivity(500e-6)

time.sleep(delay)

# amplification from the SR570
A_per_V = 100e-9


######################################################################
# step through the voltages
######################################################################

# turn on the biasvoltage
sr570.write('BSON 1')

# positiv sweep
steps = int(sweep_pos / sweep_step)
for nr in range(steps):
    voltage_to_set = 0 + nr * sweep_step
    V = int(voltage_to_set * 1000)
    cmd = 'BSLV ' + str(V)
    print(str(voltage_to_set))
    sr570.write(cmd)

    # read the data from the SR830
    value_r = sr830.read_r()
    phi = sr830.read_phi()
    #sr830.set_sensitivity(2*value_r)
    # calculate the capacity
    I = value_r * A_per_V
    C = I /(amplitude * 2 * math.pi * freq)
    C_2 = 1/math.pow(C,2)

    # append the new data to the list to plot it later
    data_BiasVoltage.append(voltage_to_set)
    data_capacity.append(C)
    data_phi.append(phi)
    data_1_over_C_squared.append(C_2)

    # Write the data in a csv
    with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow([voltage_to_set, C, phi])


# return positiv sweep
for nr in range(steps+1):
    voltage_to_set = sweep_pos - nr * sweep_step
    V = int(voltage_to_set * 1000)
    cmd = 'BSLV ' + str(V)
    sr570.write(cmd)
    print(str(voltage_to_set))
    time.sleep(delay)

    # read the data from the SR830
    value_r = sr830.read_r()
    phi = sr830.read_phi()
    #sr830.set_sensitivity(2*value_r)
    # calculate the capacity
    I = value_r * A_per_V
    C = I /(amplitude * 2 * math.pi * freq)
    C_2 = 1/math.pow(C,2)

    # append the new data to the list to plot it later
    data_BiasVoltage.append(voltage_to_set)
    data_capacity.append(C)
    data_phi.append(phi)
    data_1_over_C_squared.append(C_2)

    # Write the data in a csv
    with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow([voltage_to_set, C, phi])

# negative sweep
steps = int(abs(sweep_neg) / sweep_step)
for nr in range(steps):
    voltage_to_set = 0 - nr * sweep_step
    V = int(voltage_to_set * 1000)
    cmd = 'BSLV ' + str(V)
    sr570.write(cmd)
    print(str(voltage_to_set))
    time.sleep(delay)

    # read the data from the SR830
    value_r = sr830.read_r()
    phi = sr830.read_phi()
    #sr830.set_sensitivity(2*value_r)
    # calculate the capacity
    I = value_r * A_per_V
    C = I /(amplitude * 2 * math.pi * freq)
    C_2 = 1/math.pow(C,2)

    # append the new data to the list to plot it later
    data_BiasVoltage.append(voltage_to_set)
    data_capacity.append(C)
    data_phi.append(phi)
    data_1_over_C_squared.append(C_2)

    # Write the data in a csv
    with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow([voltage_to_set, C, phi])


# return negative sweep
for nr in range(steps):
    voltage_to_set = - sweep_neg + nr * sweep_step
    V = int(voltage_to_set * 1000)
    cmd = 'BSLV ' + str(V)
    sr570.write(cmd)
    print(str(voltage_to_set))
    time.sleep(delay)

    # read the data from the SR830
    value_r = sr830.read_r()
    phi = sr830.read_phi()
    #sr830.set_sensitivity(2*value_r)
    # calculate the capacity
    I = value_r * A_per_V
    C = I /(amplitude * 2 * math.pi * freq)
    C_2 = 1/math.pow(C,2)

    # append the new data to the list to plot it later
    data_BiasVoltage.append(voltage_to_set)
    data_capacity.append(C)
    data_phi.append(phi)
    data_1_over_C_squared.append(C_2)

    # Write the data in a csv
    with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow([voltage_to_set, C, phi])        



######################################################################
# Plot the Data and save the figure as a .pdf
######################################################################

# plot the data
f, fig = plt.subplots(2, sharex = True)
fig[0].plot(data_BiasVoltage, data_capacity,'o-', linewidth=2)
fig[1].plot(data_BiasVoltage, data_1_over_C_squared,'*', linewidth=2)

# set labels and a title
plt.xlabel('Voltage / V', fontsize=12)
plt.axes(fig[0])
plt.ylabel('Capacity / F', fontsize=12)
plt.axes(fig[1])
plt.ylabel('1/C^2', fontsize=12)
#plt.title('Characteristic curve of a diode', fontsize=14)
plt.tick_params(labelsize = 30)

plt.savefig(filename_pdf)
plt.show()


######################################################################
# Clean up
######################################################################
    
# turn off the biasvoltage
sr570.write('BSON 0')

# reset and disconnect the SR830
sr830.reset()
sr830.disconnect()




















