from StanfordResearchSystems import SR830
import visa
import math
import matplotlib.pyplot as plt
import time
import csv
import datetime

#this script conects to the SR830 Lock In Amplifier and performs a measurement of the impedance of the sample at different frequencies

######################################################################
# Connect to the lock-in amplifier
######################################################################

# 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 SR830 Lock-in Amplifier
######################################################################

sr830.use_internal_reference()

# disable line filters
sr830.disable_line_filters()
#sr830.enable_line_filters()

# set the input to measure 
sr830.set_input_mode_A_1uA()
#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
######################################################################


amplitude = 0.01
sr830.set_sine_output_level(amplitude)
#sr830.set_reference_frequency(freq)

 # define the sweep parameters
f_start = 10000
f_stop =  40000
f_step = 500       
delay = 3


# define variables we store the measurement in
data_impedance = []                # impedance
#data_BiasVoltage = []            # Bias voltage we set
data_phi = []                       # phaseshift
#data_1_over_C_squared = []  # to save one over Capacity^2
freq = []                               # frequency

# Creat unique filenames for saving the data
time_for_name = datetime.datetime.now().strftime("%Y_%m_%d_%H%M%S")
filename_csv = 'impedance_longer_cable' + time_for_name +'.csv'
filename_pdf = 'impedance_longer_cable' + 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(["Frequency / Hz" , "Impedance / Ohm", "Phase / °"])

# Some parameters for the SR830
sr830.set_time_constant(0.1)
sr830.set_sensitivity(1)
sr830.set_reference_frequency(f_start)
time.sleep(delay)


######################################################################
# step through the frequencies
######################################################################

# positive sweep
steps = int((f_stop - f_start)/f_step)
for nr in range(steps):
    f = f_start + nr * f_step
    sr830.set_reference_frequency(f)
    freq.append(f)
    time.sleep(1)
    # read the data from the SR830
    value_r = sr830.read_r()
    phi = sr830.read_phi()
    #sr830.set_sensitivity(2*value_r)
    # calculate the capacity
    Z = amplitude/value_r
    data_impedance.append(Z)
    data_phi.append(phi)

    # Write the data in a csv
    with open(filename_csv, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';',  lineterminator='\n')
        writer.writerow([f, Z, phi])


######################################################################
# Plot the Data and save the figure as a .pdf
######################################################################

# plot the data
f, fig = plt.subplots(2, sharex = True)
fig[0].plot(freq, data_impedance,'o-')
fig[1].plot(freq, data_phi,'*')

# set labels and a title
plt.xlabel('Frequency / Hz')
plt.axes(fig[0])
plt.ylabel('Z / Ohm')
plt.axes(fig[1])
plt.ylabel('Phi / °')
#plt.title('Characteristic curve of a diode')

plt.savefig(filename_pdf)
plt.show()


######################################################################
# Clean up
######################################################################

# reset and disconnect the SR830
sr830.reset()
sr830.disconnect()




















