initialise git repository

This commit is contained in:
Ryan Tan 2024-10-30 12:50:26 +01:00
commit 24acef35e1
9 changed files with 1556 additions and 0 deletions

604
Dasha_LCRCode.py Normal file
View File

@ -0,0 +1,604 @@
# -*- coding: utf-8 -*-
"""
Created on 29.10.2024, 09:00 hrs
LC Controller measurement script
@author: Serdar, adjusted by Lukas and Ryan
"""
############################################
# Packages from Ryan
import re
import math
import threading
import pyvisa
import time
# from pyvisa import ResourceManager, constants
# NOTE: KLCCommandLib64.py must be in the same folder as this script!
try:
from KLCCommandLib64 import *
except OSError as ex:
print("Warning:",ex)
# TODO: add LC Controller limits as constants, as not to be exceeded
############################################
import AMC
import csv
import time
import clr
import sys
import os
import spe2py as spe
import spe_loader as sl
import pandas as pd
import time
from System.IO import *
from System import String
import numpy as np
import matplotlib.pyplot as plt
import datetime
from typing import Union
# NOTE: this is possibly not needed, remove later
#First choose your controller
IP_AMC300 = "192.168.1.1"
IP_AMC100 = "192.168.71.100"
# IP = "192.168.1.1"
IP = IP_AMC100
# Import os module
import os, glob, string
# Import System.IO for saving and opening files
from System.IO import *
from System.Threading import AutoResetEvent
# Import C compatible List and String
from System import String
from System.Collections.Generic import List
# Add needed dll references
sys.path.append(os.environ['LIGHTFIELD_ROOT'])
sys.path.append(os.environ['LIGHTFIELD_ROOT']+"\\AddInViews")
sys.path.append(r'C:\Program Files\Princeton Instruments\LightField\AddInViews') #I added them by hand -serdar
sys.path.append(r'C:\Program Files\Princeton Instruments\LightField') #this one also
clr.AddReference('PrincetonInstruments.LightFieldViewV5')
clr.AddReference('PrincetonInstruments.LightField.AutomationV5')
clr.AddReference('PrincetonInstruments.LightFieldAddInSupportServices')
os.environ['LIGHTFIELD_ROOT'] = r'C:\Program Files\Princeton Instruments\LightField'
# PI imports
from PrincetonInstruments.LightField.Automation import Automation
from PrincetonInstruments.LightField.AddIns import ExperimentSettings
from PrincetonInstruments.LightField.AddIns import CameraSettings
#from PrincetonInstruments.LightField.AddIns import DeviceType
from PrincetonInstruments.LightField.AddIns import SpectrometerSettings
from PrincetonInstruments.LightField.AddIns import RegionOfInterest
######################################################################################################### code begins from here #############################################
def set_custom_ROI():
# Get device full dimensions
dimensions = experiment.FullSensorRegion()
regions = []
# Add two ROI to regions
regions.append(
RegionOfInterest(
int(dimensions.X), int(dimensions.Y),
int(dimensions.Width), int(dimensions.Height//4), # Use // for integer division
int(dimensions.XBinning), int(dimensions.Height//4)))
# Set both ROI
experiment.SetCustomRegions(regions)
def experiment_completed(sender, event_args): #callback function which is hooked to event completed, this is the listener
print("... Acquisition Complete!")
acquireCompleted.Set() #set the event. This puts the autoresetevent false.(look at .NET library for furher info)
def InitializerFilenameParams():
experiment.SetValue(ExperimentSettings.FileNameGenerationAttachIncrement, False)
experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementNumber, 1.0)
experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementMinimumDigits, 2.0)
experiment.SetValue(ExperimentSettings.FileNameGenerationAttachDate, False)
experiment.SetValue(ExperimentSettings.FileNameGenerationAttachTime, False)
def AcquireAndLock(name):
print("Acquiring...", end = "")
# name += 'Exp{0:06.2f}ms.CWL{1:07.2f}nm'.format(\
# experiment.GetValue(CameraSettings.ShutterTimingExposureTime)\
# ,experiment.GetValue(SpectrometerSettings.GratingCenterWavelength))
experiment.SetValue(ExperimentSettings.FileNameGenerationBaseFileName, name) #this creates .spe file with the name
experiment.Acquire() # this is an ashynrchronus func.
acquireCompleted.WaitOne()
def calculate_distance(x1, y1, x2, y2):
return np.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def generate_scan_positions(center, range_val, resolution):
positive_range = np.arange(center, center + range_val + resolution, resolution)
return positive_range
def save_as_csv(filename, position_x, position_y):
file_existance = os.path.isfile(filename)
with open(filename, 'a', newline = '') as csvfile:
writer = csv.writer(csvfile)
if not file_existance:
writer.writerow(['x_coordinates','y_coordinates'])
writer.writerow([position_x, position_y])
# def move_axis(axis, target):
# """
# This function moves an axis to the specified target and stop moving after it is in the really closed
# vicinity (+- 25nm) of the target (listener hooked to it).
# """
# amc.move.setControlTargetPosition(axis, target)
# amc.control.setControlMove(axis, True)
# while not (target - 25) < amc.move.getPosition(axis) < (target + 25):
# time.sleep(0.1)
# time.sleep(0.15)
# while not (target - 25) < amc.move.getPosition(axis) < (target + 25):
# time.sleep(0.1)
# amc.control.setControlMove(axis, False)
# def move_xy(target_x, target_y): # moving in x and y direction closed to desired position
# amc.move.setControlTargetPosition(0, target_x)
# amc.control.setControlMove(0, True)
# amc.move.setControlTargetPosition(1, target_y)
# amc.control.setControlMove(1, True)
# while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25):
# time.sleep(0.1)
# time.sleep(0.15)
# while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25):
# time.sleep(0.1)
# amc.control.setControlOutput(0, False)
# amc.control.setControlOutput(1, False)
# intensity_data = [] # To store data from each scan
# data_list = []
# def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName):
# """
# This function moves the positioners to scan the sample with desired ranges and resolution in 2 dimensions.
# At the end it saves a csv file
# Parameters
# ----------
# range_x : integer in nm. max value is 5um
# Scan range in x direction.
# range_y : integer in nm. max value is 5um
# Scan range in y direction.
# resolution : integer in nm.
# Room temprature max res is 50nm. In cyrostat (4K) it is 10nm (check the Attocube manual)
# baseFileName: string. At the end the saved file will be: baseFileName_scan_data.csv and it will be saved to the current directory
# Returns
# -------
# None.
# """
# start_time = time.time()
# axis_x = 0 #first axis
# axis_y = 1 #second axis
# center_x = amc.move.getPosition(axis_x)
# center_y = amc.move.getPosition(axis_y)
# # #check if the intput range is reasonable
# # if amc.move.getPosition(axis_x) + range_x >= 5000 or amc.move.getPosition(axis_x)- range_x <= 0 or amc.move.getPosition(axis_y) + range_y >=5000 or amc.move.getPosition(axis_y) - range_y <= 5000 :
# # print("scan range is out of range!")
# # return
# # +- range from current positions for x and y directions
# array_x = generate_scan_positions(center_x, range_x, resolution)
# array_y = generate_scan_positions(center_y, range_y, resolution)
# total_points = len(array_x)*len(array_y)
# len_y = len(array_y)
# intensity_data = [] # To store data from each scan
# data_list = []
# cwd = os.getcwd() # save original directory
# #This gives a directory, in which the script will save the spectrum of each spot as spe
# #However, it will open the spectrum, convert it to txt, add it to the intensity_data and delete the spe file
# temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test"
# #scanning loop
# for i, x_positions in enumerate(array_x):
# move_axis(axis_x, x_positions)
# y = False
# for j, y_positions in enumerate(array_y):
# move_axis(axis_y, y_positions)
# #each time when the positioner comes to the beggining of a new line
# #this if will make the positioner wait a bit longer to really go to the target.
# if y == False:
# move_axis(axis_y, y_positions)
# y = True
# #we acquire with the LF
# acquire_name_spe = f'{baseFileName}_X{x_positions}_Y{y_positions}'
# AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name.
# #read the .spe file and get the data as loaded_files
# cwd = os.getcwd() # save original directory
# os.chdir(temp_folder_path) #change directory
# loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable
# os.chdir(cwd) # go back to original directory
# # Delete the created .spe file from acquiring after getting necessary info
# spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe')
# os.remove(spe_file_path)
# distance = calculate_distance(x_positions, y_positions,amc.move.getPosition(axis_x), amc.move.getPosition(axis_y))
# points_left = total_points - (i * len_y + (j+1)) + 1
# print('Points left in the scan: ', points_left)
# #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins)
# intensity_data.append(loaded_files.data[0][0][0])
# data_list.append({
# 'position_x': x_positions,
# 'position_y': y_positions,
# 'actual_x': amc.move.getPosition(axis_x),
# 'actual_y': amc.move.getPosition(axis_y),
# 'distance': distance,
# })
# #moves back to starting position
# move_axis(axis_x, center_x)
# move_axis(axis_y, center_y)
# #prints total time the mapping lasted
# end_time = time.time()
# elapsed_time = (end_time - start_time) / 60
# print('Scan time: ', elapsed_time, 'minutes')
# # df = pd.DataFrame(data_list)
# #save intensity & WL data as .txt
# os.chdir('C:/Users/localadmin/Desktop/Users/Lukas')
# # creates new folder for MAP data
# new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}"
# os.mkdir(new_folder_name)
# # Here the things will be saved in a new folder under user Lukas !
# # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!!
# os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name)
# intensity_data = np.array(intensity_data)
# np.savetxt(Settings + str(center_x) + '_' + str(center_y) + experiment_name +'.txt', intensity_data)
# wl = np.array(loaded_files.wavelength)
# np.savetxt("Wavelength.txt", wl)
################################################################# RYAN'S FUNCTIONS HERE ##########################################################################################
def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True):
# TODO: DOCS
"""Creates a list of discrete cartesian coordinates (x,y), given the radius, start- and end angles, the angle step size, and the direction of rotation.
Function then returns a list of two lists: list of angles and list of cartesian coordinates (x,y coordinates in a tuple).
Args:
radius (_type_): _description_
start_angle (_type_): _description_
end_angle (_type_): _description_
step_size (_type_): _description_
clockwise (bool, optional): _description_. Defaults to True.
Returns:
_type_: _description_
""" """"""
# Initialize lists to hold angles and (x, y) pairs
angles = []
coordinates = []
# Normalize angles to the range [0, 360)
start_angle = start_angle % 360
end_angle = end_angle % 360
if clockwise:
# Clockwise rotation
current_angle = start_angle
while True:
# Append the current angle to the angles list
angles.append(current_angle % 360)
# Convert the current angle to radians
current_angle_rad = math.radians(current_angle % 360)
# Convert polar to Cartesian coordinates
x = radius * math.cos(current_angle_rad)
y = radius * math.sin(current_angle_rad)
# Append the (x, y) pair to the list
coordinates.append((x, y))
# Check if we've reached the end_angle (handling wrap-around) (current_angle - step_size) % 360 == end_angle or
if current_angle % 360 == end_angle:
break
# Decrement the current angle by the step size
current_angle -= step_size
if current_angle < 0:
current_angle += 360
else:
# Counterclockwise rotation
current_angle = start_angle
while True:
# Append the current angle to the angles list
angles.append(current_angle % 360)
# Convert the current angle to radians
current_angle_rad = math.radians(current_angle % 360)
# Convert polar to Cartesian coordinates
x = radius * math.cos(current_angle_rad)
y = radius * math.sin(current_angle_rad)
# Append the (x, y) pair to the list
coordinates.append((x, y))
# Check if we've reached the end_angle (handling wrap-around) (current_angle + step_size) % 360 == end_angle or
if current_angle % 360 == end_angle:
break
# Increment the current angle by the step size
current_angle += step_size
if current_angle >= 360:
current_angle -= 360
return [angles, coordinates]
################################################################# DASHA'S CODE HERE ##############################################################################################
# TODO: modify b field scan script for Dasha, to be used for the KLC controller
def LCR_scan_func(instr:KLC, min_bval:float, max_bval:float,
res:float, magnet_coil:str, Settings:str, base_file_name='',
reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False)->None:
def pyramid_list(lst) -> Union[list, np.ndarray]:
"""reverses the list and removes the first element of reversed list. Then, this is appended to
the end of the original list and returned as the 'pyramid' list.
Args:
lst (list or np.ndarray):
Raises:
TypeError: if the input object isn't a list or np.ndarray
Returns:
Union[list, np.ndarray]: the pyramid list
""" ''''''
if isinstance(lst, list):
return lst + lst[-2::-1]
elif isinstance(lst, np.ndarray):
return np.append(lst, lst[-2::-1])
else:
raise TypeError('Please input a list!')
# defines the folder, in which the data from the spectrometer is temporarily stored in
temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test"
# if path_save =='':
# path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_")
if base_file_name =='':
base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')
start_time = time.time() # start of the scan function
instr_info = query_no_echo(instr, '*IDN?')
instr_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element list of lists containing the set unit, llim and ulim
if instr_bsettings[0][0] == 'T':
instr_bsettings[1][0] = instr_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T
instr_bsettings[2][0] = instr_bsettings[2][0]*0.1
# if singlepowersupply_bool: # checks limits of Bx or By
# if (min_bval< -BY_MAX) or (max_bval > BY_MAX):
# raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.')
# elif '1' in query_no_echo(instr, 'CHAN?'): # check if its the coils for Bz
# if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX):
# raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.')
# else: # checks limits of Bx
# if (min_bval< -BX_MAX) or (max_bval > BX_MAX):
# raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.')
if '2101014' in instr_info and (magnet_coil=='y-axis'): # single power supply
if (min_bval< -BY_MAX) or (max_bval > BY_MAX):
raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.')
elif '2301034' in instr_info: # dual power supply
if magnet_coil=='z-axis': # check if its the coils for Bz
if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX):
raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.')
write_no_echo(instr, 'CHAN 1')
elif magnet_coil=='x-axis': # checks limits of Bx
if (min_bval< -BX_MAX) or (max_bval > BX_MAX):
raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.')
write_no_echo(instr, 'CHAN 2')
else:
raise ConnectionError('Device is not connected!')
write_no_echo(instr, f'LLIM {min_bval*10};ULIM {max_bval*10}') # sets the given limits, must convert to kG for the device to read
bval_lst = np.arange(min_bval, max_bval + res, res) # creates list of B values to measure at, with given resolution, in T
# TODO: unused, see if can remove
# init_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # queries the initial B value of the coil, rescale from kG to T
init_lim, subsequent_lim = 'LLIM', 'ULIM'
init_sweep, subsequent_sweep = 'DOWN', 'UP'
####################################################
# TODO: decide whether to start at min b val or max b val, depending on which one is nearer, IMPLEMENT THIS LATER
# nearest_bval = (abs(init_bval - min_bval), abs(init_bval - max_bval))
# if nearest_bval[0] <= nearest_bval[1]:
# reversescan_bool = True
####################################################
# if reverse scan, then flip the values in the b list, and swap the initial limit and sweep conditions
if reversescan_bool:
bval_lst = bval_lst[::-1]
init_lim, subsequent_lim = subsequent_lim, init_lim
init_sweep, subsequent_sweep = subsequent_sweep, init_sweep
# creates the pyramid list of B vals if one were to perform a hysteresis measurement
if loopscan_bool:
bval_lst = pyramid_list(bval_lst)
total_points = len(bval_lst)
middle_index_bval_lst = total_points // 2
intensity_data = [] # To store data from each scan
cwd = os.getcwd() # save original directory
# NOTE: helper function for the scanning loop
def helper_scan_func(idx, bval, instr=instr, init_lim=init_lim, init_sweep=init_sweep,
subsequent_lim=subsequent_lim, subsequent_sweep=subsequent_sweep, sleep=5):
if idx == 0: # for first iteration, sweep to one of the limits
write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG
write_no_echo(instr, f'SWEEP {init_sweep}')
else:
write_no_echo(instr, f'{subsequent_lim} {bval*10}') # convert back to kG
write_no_echo(instr, f'SWEEP {subsequent_sweep}')
actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # convert kG to T
print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T')
while abs(actual_bval - bval) > 0.0001:
time.sleep(5) # little break
actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1
# update the actual bval
print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T')
#scanning loop
for i, bval in enumerate(bval_lst):
if not loopscan_bool:
helper_scan_func(i, bval)
else:
if i <= middle_index_bval_lst:
helper_scan_func(i, bval)
else:
helper_scan_func(i, bval, instr=instr, init_lim=subsequent_lim, init_sweep=subsequent_sweep,
subsequent_lim=init_lim, subsequent_sweep=init_sweep, sleep=5)
time.sleep(5)
# we acquire with the LF
acquire_name_spe = f'{base_file_name}_{bval}T'
AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name.
# read the .spe file and get the data as loaded_files
cwd = os.getcwd() # save original directory
os.chdir(temp_folder_path) #change directory
loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable
os.chdir(cwd) # go back to original directory
# Delete the created .spe file from acquiring after getting necessary info
spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe')
os.remove(spe_file_path)
points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT
print('Points left in the scan: ', points_left)
#append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins)
intensity_data.append(loaded_files.data[0][0][0])
#prints total time the mapping lasted
end_time = time.time()
elapsed_time = (end_time - start_time) / 60
print('Scan time: ', elapsed_time, 'minutes')
write_no_echo(instr, f'LLIM {instr_bsettings[1][0]*10};ULIM {instr_bsettings[2][0]*10}') # reset the initial limits of the device after the scan
if zerowhenfin_bool:
write_no_echo(instr, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above
#save intensity & WL data as .txt
os.chdir('C:/Users/localadmin/Desktop/Users/Lukas')
# creates new folder for MAP data
new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}"
os.mkdir(new_folder_name)
# Here the things will be saved in a new folder under user Lukas !
# IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!!
os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name)
intensity_data = np.array(intensity_data)
np.savetxt(Settings + str(min_bval) + 'T_to_' + str(max_bval) + 'T' + experiment_name +'.txt', intensity_data)
wl = np.array(loaded_files.wavelength)
np.savetxt("Wavelength.txt", wl)
################################################################# END OF FUNCTION DEFS ###########################################################################################
# NOTE: RYAN INTRODUCED SOME FUNCTIONS HERE TO PERFORM THE SCAN
try:
# initialise KLC connection
#Find devices
devs = klcListDevices()
print("Found devices:",devs,"\n")
if(len(devs)<=0):
print('There is no device connected')
sys.exit()
klc = devs[0]
serialnumber = klc[0]
#Connect device
KLC_handle = klcOpen(serialnumber, 115200, 3)
if(KLC_handle<0):
print("open ", serialnumber, " failed")
sys.exit()
if(klcIsOpen(serialnumber) == 0):
print("klcIsOpen failed")
klcClose(KLC_handle)
sys.exit()
print("Connected to serial number ", serialnumber)
# TODO: continue editing the code below this
# Initialise PYVISA ResourceManager
rm = pyvisa.ResourceManager()
# print(rm.list_resources())
# 'ASRL8::INSTR' for dual power supply, 'ASRL9::INSTR' for single power supply (online PC)
# 'ASRL10::INSTR' for dual power supply, 'ASRL12::INSTR' for single power supply (offline PC)
auto = Automation(True, List[String]())
experiment = auto.LightFieldApplication.Experiment
acquireCompleted = AutoResetEvent(False)
experiment.Load("Lukas_experiment_2024_02_06")
experiment.ExperimentCompleted += experiment_completed # we are hooking a listener.
# experiment.SetValue(SpectrometerSettings.GratingSelected, '[750nm,1200][0][0]')
# InitializerFilenameParams()
#set scan range and resolution in nanometers
range_x = 20000
range_y = 20000
resolution = 1000
# set B-field scan range and resolution (all in T)
set_llim_bval = -0.01
set_ulim_bval = 0.01
set_res_bval = 0.01
# TODO: add the start-, end angles, as well as angle step size here (alternatively, add it above)
#Here you can specify the filename of the map e.g. put experiment type, exposure time, used filters, etc....
experiment_settings = 'PL_SP_700_LP_700_HeNe_52muW_exp_2s_Start_'
#The program adds the range of the scan as well as the resolution and the date and time of the measurement
experiment_name = f"{set_llim_bval}T_to_{set_ulim_bval}T_{set_res_bval}T_{datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}"
# TODO: insert LCR rotation scan function here
except Exception() as e:
print(e)
finally:
#close connection to device
klcClose(KLC_handle)
print("Connection closed")

116
KLC101_basic_example.py Normal file
View File

@ -0,0 +1,116 @@
import sys
import time
from ctypes import *
try:
from KLCCommandLib64 import *
import time
except OSError as ex:
print("Warning:",ex)
def main():
try:
#Find devices
devs = klcListDevices()
print("Found devices:",devs,"\n")
if(len(devs)<=0):
print('There is no device connected')
sys.exit()
klc = devs[0]
serialnumber = klc[0]
#Connect device
KLC_handle = klcOpen(serialnumber, 115200, 3)
if(KLC_handle<0):
print("open ", serialnumber, " failed")
sys.exit()
if(klcIsOpen(serialnumber) == 0):
print("klcIsOpen failed")
klcClose(KLC_handle)
sys.exit()
print("Connected to serial number ", serialnumber)
# ------------ Disable/Enable global output -------------- #
klcSetEnable(KLC_handle,2) # 1 enable, 2 disable
print("Enable output\n")
if(klcSetEnable(KLC_handle, 1)<0):
print("klcSetEnable failed")
en=[0]
if(klcGetEnable(KLC_handle, en)<0):
print("klcGetEnable failed")
# ------------ Preset1 mode ----------------------------- #
print("Enable V1")
klcSetChannelEnable(KLC_handle, 1) # 0x01 V1 Enable , 0x02 V2 Enable, 0x03 SW Enable, 0x00 channel output disable.
#Set voltage 1
if(klcSetVoltage1(KLC_handle, 1)<0):
print("klcSetVoltage1 failed")
vol1=[0]
if(klcGetVoltage1(KLC_handle, vol1)<0):
print("klcGetVoltage1 failed")
else:
print("Set voltage 1 to ",vol1[0],"V")
#set freqency 1
if(klcSetFrequency1(KLC_handle, 2000)<0):
print("klcSetFrequency1 failed")
freq1=[0]
if(klcGetFrequency1(KLC_handle, freq1)<0):
print("klcGetFrequency1 failed")
else:
print("Frequency 1 set to", freq1[0]," Hz\n")
time.sleep(1)
# ------------ Preset2 mode ----------------------------- #
print("Enable V2")
klcSetChannelEnable(KLC_handle, 2)
#set voltage 2
if(klcSetVoltage2(KLC_handle, 10)<0):
print("klcSetVoltage2 failed")
vol2=[0]
if(klcGetVoltage2(KLC_handle, vol2)<0):
print("klcGetVoltage2 failed")
else:
print("Set voltage 2 to", vol2[0], " V")
#set freq2
if(klcSetFrequency2(KLC_handle, 2000)<0):
print("klcSetFrequency2 failed")
freq2=[0]
if(klcGetFrequency2(KLC_handle, freq2)<0):
print("klcGetFrequency2 failed")
else:
print("Frequency 2 set to ", freq2[0]," Hz\n")
time.sleep(1)
print("Enable V1")
klcSetChannelEnable(KLC_handle, 1)
time.sleep(1)
print("Enable V2")
klcSetChannelEnable(KLC_handle, 2)
time.sleep(1)
#close connection to device
klcClose(KLC_handle)
print("Connection closed")
except Exception as ex:
print("Warning:", ex)
if __name__ == "__main__":
main()

606
KLCCommandLib64.py Normal file
View File

@ -0,0 +1,606 @@
from ctypes import *
import os,sys
#region import dll functions; NOTE: ENTER ABSOLUTE PATH BELOW
klcLib=cdll.LoadLibrary(r"C:\Users\rtan\Documents\RyanWork2024\Dasha-LCR_Code\Thorlabs_KLC_PythonSDK\"KLCCommandLib_x64.dll")
cmdList = klcLib.List
cmdList.argtypes=[c_char_p, c_int]
cmdList.restype=c_int
cmdOpen = klcLib.Open
cmdOpen.restype=c_int
cmdOpen.argtypes=[c_char_p, c_int, c_int]
cmdSetEnable = klcLib.SetEnable
cmdSetEnable.restype=c_int
cmdSetEnable.argtypes=[c_int, c_byte]
cmdGetEnable = klcLib.GetEnable
cmdGetEnable.restype=c_int
cmdGetEnable.argtypes=[c_int, POINTER(c_byte)]
cmdSetVoltage1 = klcLib.SetVoltage1
cmdSetVoltage1.restype=c_int
cmdSetVoltage1.argtypes=[c_int, c_float]
cmdSetVoltage2 = klcLib.SetVoltage2
cmdSetVoltage2.restype=c_int
cmdSetVoltage2.argtypes=[c_int, c_float]
cmdGetVoltage1 = klcLib.GetVoltage1
cmdGetVoltage1.restype=c_int
cmdGetVoltage1.argtypes=[c_int, POINTER(c_float)]
cmdGetVoltage2 = klcLib.GetVoltage2
cmdGetVoltage2.restype=c_int
cmdGetVoltage2.argtypes=[c_int, POINTER(c_float)]
cmdSetFrequency1 = klcLib.SetFrequency1
cmdSetFrequency1.restype=c_int
cmdSetFrequency1.argtypes=[c_int, c_ushort]
cmdSetFrequency2 = klcLib.SetFrequency2
cmdSetFrequency2.restype=c_int
cmdSetFrequency2.argtypes=[c_int, c_ushort]
cmdGetFrequency1 = klcLib.GetFrequency1
cmdGetFrequency1.restype=c_int
cmdGetFrequency1.argtypes=[c_int, POINTER(c_ushort)]
cmdGetFrequency2 = klcLib.GetFrequency2
cmdGetFrequency2.restype=c_int
cmdGetFrequency2.argtypes=[c_int, POINTER(c_ushort)]
cmdSetSWFrequency = klcLib.SetSWFrequency
cmdSetSWFrequency.restype=c_int
cmdSetSWFrequency.argtypes=[c_int, c_float]
cmdGetSWFrequency = klcLib.GetSWFrequency
cmdGetSWFrequency.restype=c_int
cmdGetSWFrequency.argtypes=[c_int, POINTER(c_float)]
cmdSetInputMode = klcLib.SetInputMode
cmdSetInputMode.restype=c_int
cmdSetInputMode.argtypes=[c_int, c_ubyte]
cmdGetInputMode = klcLib.GetInputMode
cmdGetInputMode.restype=c_int
cmdGetInputMode.argtypes=[c_int, POINTER(c_ubyte)]
cmdSetTrigIOConfigure = klcLib.SetTrigIOConfigure
cmdSetTrigIOConfigure.restype=c_int
cmdSetTrigIOConfigure.argtypes=[c_int, c_ubyte]
cmdGetTrigIOConfigure = klcLib.GetTrigIOConfigure
cmdGetTrigIOConfigure.restype=c_int
cmdGetTrigIOConfigure.argtypes=[c_int, POINTER(c_ubyte)]
cmdSetChannelEnable = klcLib.SetChannelEnable
cmdSetChannelEnable.restype=c_int
cmdSetChannelEnable.argtypes=[c_int, c_ubyte]
cmdGetChannelEnable = klcLib.GetChannelEnable
cmdGetChannelEnable.restype=c_int
cmdGetChannelEnable.argtypes=[c_int, POINTER(c_ubyte)]
cmdSetKcubeMMIParams = klcLib.SetKcubeMMIParams
cmdSetKcubeMMIParams.restype=c_int
cmdSetKcubeMMIParams.argtypes=[c_int, c_ushort, c_ushort]
cmdGetKcubeMMIParams = klcLib.GetKcubeMMIParams
cmdGetKcubeMMIParams.restype=c_int
cmdGetKcubeMMIParams.argtypes=[c_int, POINTER(c_ushort), POINTER(c_ushort)]
cmdSetKcubeMMILock = klcLib.SetKcubeMMILock
cmdSetKcubeMMILock.restype=c_int
cmdSetKcubeMMILock.argtypes=[c_int, c_ubyte]
cmdGetKcubeMMILock = klcLib.GetKcubeMMILock
cmdGetKcubeMMILock.restype=c_int
cmdGetKcubeMMILock.argtypes=[c_int, POINTER(c_ubyte)]
cmdGetOutPutStatus = klcLib.GetOutPutStatus
cmdGetOutPutStatus.restype=c_int
cmdGetOutPutStatus.argtypes=[c_int, POINTER(c_ushort), POINTER(c_float), POINTER(c_ushort),POINTER(c_ushort)]
cmdGetStatus = klcLib.GetStatus
cmdGetStatus.restype=c_int
cmdGetStatus.argtypes=[c_int, POINTER(c_ubyte), POINTER(c_float), POINTER(c_ushort), POINTER(c_float), POINTER(c_ushort), POINTER(c_float), POINTER(c_ushort),POINTER(c_ushort),POINTER(c_ubyte),POINTER(c_ubyte),POINTER(c_ubyte),POINTER(c_ushort)]
cmdUpdateOutputLUT = klcLib.UpdateOutputLUT
cmdUpdateOutputLUT.restype=c_int
cmdUpdateOutputLUT.argtypes=[c_int, c_ushort, c_float]
cmdRemoveLastOutputLUT = klcLib.RemoveLastOutputLUT
cmdRemoveLastOutputLUT.restype=c_int
cmdRemoveLastOutputLUT.argtypes=[c_int, c_ushort]
cmdSetOutputLUT = klcLib.SetOutputLUT
cmdSetOutputLUT.restype=c_int
cmdSetOutputLUT.argtypes=[c_int, POINTER(c_float), c_ushort]
cmdSetOutputLUTParams = klcLib.SetOutputLUTParams
cmdSetOutputLUTParams.restype= c_int
cmdSetOutputLUTParams.argtypes=[c_int, c_ushort, c_ulong, c_ulong, c_ulong]
cmdGetOutputLUTParams = klcLib.GetOutputLUTParams
cmdGetOutputLUTParams.restype=c_int
cmdGetOutputLUTParams.argtypes=[c_int, POINTER(c_ushort), POINTER(c_ulong), POINTER(c_ulong), POINTER(c_ulong)]
#endregion
def klcListDevices():
""" List all connected KLC devices
Returns:
The klc device list, each deice item is serialNumber/COM
"""
str = create_string_buffer(1024, '\0')
result = cmdList(str,1024)
devicesStr = str.raw.decode("utf-8","ignore").rstrip('\x00').split(',')
length = len(devicesStr)
i=0
devices=[]
devInfo=["",""]
discription="Kinesis LC Controller"
while(i<length):
str = devicesStr[i]
if (i%2 == 0):
if str != '':
devInfo[0] = str
else:
i+=1
else:
if(str.find(discription)>=0):
#info = str.split('&')
devInfo[1] = discription
devices.append(devInfo.copy())
i+=1
return devices
def klcOpen(serialNo, nBaud, timeout):
""" Open device
Args:
serialNo: serial number of KLC device
nBaud: bit per second of port
timeout: set timeout value in (s)
Returns:
non-negative number: hdl number returned Successful; negative number: failed.
"""
return cmdOpen(serialNo.encode('utf-8'), nBaud, timeout)
def klcIsOpen(serialNo):
""" Check opened status of device
Args:
serialNo: serial number of device
Returns:
0: device is not opened; 1: device is opened.
"""
return klcLib.IsOpen(serialNo.encode('utf-8'))
def klcClose(hdl):
""" Close opened device
Args:
hdl: the handle of opened device
Returns:
0: Success; negative number: failed.
"""
return klcLib.Close(hdl)
def klcSetEnable(hdl, enable):
""" Set output enable state
Args:
hdl: the handle of opened device
enable: 0x01 enable, 0x02 disable
Returns:
0: Success; negative number: failed.
"""
return cmdSetEnable(hdl, enable);
def klcGetEnable(hdl, enable):
""" Get output enable state
Args:
hdl: the handle of opened device
enable: 0x01 enable, 0x02 disable
Returns:
0: Success; negative number: failed.
"""
e = c_byte(0)
ret = cmdGetEnable(hdl, e)
enable[0] = e.value
return ret
def klcGetVoltage1(hdl, voltage):
""" Get output Voltage 1.
Args:
hdl: the handle of opened device
voltage: the output voltage
Returns:
0: Success; negative number: failed.
"""
vol = c_float(0)
ret = cmdGetVoltage1(hdl, vol)
voltage[0] = vol.value
return ret
def klcSetVoltage1(hdl, voltage):
""" Set the output voltage 1.
Args:
hdl: the handle of opened device
voltage: the output voltage 0~25 V.
Returns:
0: Success; negative number: failed.
"""
return cmdSetVoltage1(hdl, voltage)
def klcGetVoltage2(hdl, voltage):
""" Get output Voltage 2.
Args:
hdl: the handle of opened device
voltage: the output voltage
Returns:
0: Success; negative number: failed.
"""
vol = c_float(0)
ret = cmdGetVoltage2(hdl, vol)
voltage[0] = vol.value
return ret
def klcSetVoltage2(hdl, voltage):
""" Set the output voltage 2.
Args:
hdl: the handle of opened device
voltage: the output voltage 0~25 V.
Returns:
0: Success; negative number: failed.
"""
return cmdSetVoltage2(hdl, voltage)
def klcGetFrequency1(hdl, freqency):
""" Get output Frequency 1.
Args:
hdl: the handle of opened device
freqency: the output voltage
Returns:
0: Success; negative number: failed.
"""
freq = c_ushort(0)
ret = cmdGetFrequency1(hdl, freq)
freqency[0] = freq.value
return ret
def klcSetFrequency1(hdl, freqency):
""" Set the output Frequency 1.
Args:
hdl: the handle of opened device
freqency: the output frequency 500~10000 Hz.
Returns:
0: Success; negative number: failed.
"""
return cmdSetFrequency1(hdl, freqency)
def klcGetFrequency2(hdl, freqency):
""" Get output Frequency 2.
Args:
hdl: the handle of opened device
freqency: the output freqency
Returns:
0: Success; negative number: failed.
"""
freq = c_ushort(0)
ret = cmdGetFrequency2(hdl, freq)
freqency[0] = freq.value
return ret
def klcSetFrequency2(hdl, freqency):
""" Set the output Frequency 2.
Args:
hdl: the handle of opened device
freqency: the output frequency 500~10000 Hz.
Returns:
0: Success; negative number: failed.
"""
return cmdSetFrequency2(hdl, freqency)
def klcGetSWFrequency(hdl, freqency):
""" Get frequency of switch mode.
Args:
hdl: the handle of opened device
freqency: the output frequency
Returns:
0: Success; negative number: failed.
"""
freq = c_float(0)
ret = cmdGetSWFrequency(hdl, freq)
freqency[0] = freq.value
return ret
def klcSetSWFrequency(hdl, freqency):
""" Set frequency of switch mode.
Args:
hdl: the handle of opened device
freqency: the output frequency 0.1~150 Hz.
Returns:
0: Success; negative number: failed.
"""
return cmdSetSWFrequency(hdl, freqency)
def klcGetInputMode(hdl, mode):
""" Get device analog input mode.
Args:
hdl: the handle of opened device
mode: 0 disable; 1 enable
Returns:
0: Success; negative number: failed.
"""
m = c_ubyte(0)
ret = cmdGetInputMode(hdl, m)
mode[0] = m.value
return ret
def klcSetInputMode(hdl, mode):
""" Set device analog input mode.
Args:
hdl: the handle of opened device
mode: 0 disable; 1 enable
Returns:
0: Success; negative number: failed.
"""
return cmdSetInputMode(hdl, mode)
def klcGetTrigIOConfigure(hdl, mode):
""" Get device trigger pin mode.
Args:
hdl: the handle of opened device
mode: 01 -Trigger Pin1 output, Pin2 output; 02- Trigger Pin1 In, Pin2 out; 03- Trigger Pin1 out, Pin2 in
Returns:
0: Success; negative number: failed.
"""
m = c_ubyte(0)
ret = cmdGetTrigIOConfigure(hdl, m)
mode[0] = m.value
return ret
def klcSetTrigIOConfigure(hdl, mode):
""" Set device trigger pin mode.
Args:
hdl: the handle of opened device
mode: 01 -Trigger Pin1 output, Pin2 output; 02- Trigger Pin1 In, Pin2 out; 03- Trigger Pin1 out, Pin2 in.
Returns:
0: Success; negative number: failed.
"""
return cmdSetTrigIOConfigure(hdl, mode)
def klcGetChannelEnable(hdl, enable):
""" Get device channel enable state.
Args:
hdl: the handle of opened device
enable: 0x01 V1 Enable , 0x02 V2 Enable, 0x03 SW Enable, 0x00 channel output disable.
Returns:
0: Success; negative number: failed.
"""
e = c_ubyte(0)
ret = cmdGetChannelEnable(hdl, e)
enable[0] = e.value
return ret
def klcSetChannelEnable(hdl, enable):
""" Set device channel enable state.
Args:
hdl: the handle of opened device
enable: 0x01 V1 Enable , 0x02 V2 Enable, 0x03 SW Enable, 0x00 channel output disable.
Returns:
0: Success; negative number: failed.
"""
return cmdSetChannelEnable(hdl, enable)
def klcGetKcubeMMIParams(hdl, dispBrightness, dispTimeout):
""" Get device configure the operating parameters.
Args:
hdl: the handle of opened device
dispBrightness: display brightness
dispTimeout: display timeout
Returns:
0: Success; negative number: failed.
"""
db = c_ushort(0)
dt = c_ushort(0)
ret = cmdGetKcubeMMIParams(hdl, db, dt)
dispBrightness[0] = db.value
dispTimeout[0] = dt.value
return ret
def klcSetKcubeMMIParams(hdl, dispBrightness, dispTimeout):
""" Set device configure the operating parameters.
Args:
hdl: the handle of opened device
dispBrightness: display brightness 0~100
dispTimeout: display timeout 1~480; set nerver should set to 0xFFFF
Returns:
0: Success; negative number: failed.
"""
return cmdSetKcubeMMIParams(hdl, dispBrightness, dispTimeout)
def klcGetKcubeMMILock(hdl, lock):
""" Get the device lock/unlock the wheel control on the top pannel.
Args:
hdl: the handle of opened device
lock: x02 unlock the wheel; 0x01 Lock the wheel
Returns:
0: Success; negative number: failed.
"""
l = c_ubyte(0)
ret = cmdGetKcubeMMILock(hdl, l)
lock[0] = l.value
return ret
def klcSetKcubeMMILock(hdl, lock):
""" Set the device lock/unlock the wheel control on the top pannel .
Args:
hdl: the handle of opened device
lock: x02 unlock the wheel; 0x01 Lock the wheel
Returns:
0: Success; negative number: failed.
"""
return cmdSetKcubeMMILock(hdl, lock)
def klcGetOutPutStatus(hdl, isOutputActive, outputVoltage, outputFrequency, errFlag):
""" Get the device output status.
Args:
hdl: the handle of opened device
isOutputActive: 0x00 Inactive; 0x01 Active
outputVoltage: output voltage
outputFrequency: output frequency
Returns:
0: Success; negative number: failed.
"""
active = c_ushort(0)
vol = c_float(0)
freq = c_ushort(0)
err = c_ushort(0)
ret = cmdGetOutPutStatus(hdl, active, vol, freq, err)
isOutputActive[0] = active.value
outputVoltage[0] = vol.value
outputFrequency[0] = freq.value
errFlag[0] = err.value
return ret
def klcGetStatus(hdl, channelenable, v1, freq1, v2, freq2, swFreq, dispBrightness, dipTimeout, adcMod, trigConfig, wheelMod, errFlag):
""" Get the device status update value.
Args:
hdl: the handle of opened device
channelenable: channel enable state
v1: output voltage 1
freq1: output frequency 1
v2: output voltage 2
freq2: output frequency 2
swFreq: switch frequency
dispBrightness: display pannel brightness
dipTimeout: display pannel timeout
adcMod: ADC mod in
trigConfig: trigger config
wheelMod: wheel locked mode
errFlag: error flag
Returns:
0: Success; negative number: failed.
"""
enable = c_ubyte(0)
vol1 = c_float(0)
f1 = c_ushort(0)
vol2 = c_float(0)
f2 = c_ushort(0)
sw = c_float(0)
db = c_ushort(0)
dt = c_ushort(0)
am = c_ubyte(0)
t = c_ubyte(0)
w = c_ubyte(0)
err = c_ushort(0)
ret = cmdGetStatus(hdl, enable, vol1, f1,vol2,f2,sw,db,dt,am,t,w, err)
channelenable[0] = enable.value
v1[0] = vol1.value
freq1[0] = f1.value
v2[0] = vol2.value
freq2[0] = f2.value
swFreq[0] = sw.value
dispBrightness[0] = db.value
dipTimeout[0] = dt.value
adcMod[0] = am.value
trigConfig[0] = t.value
wheelMod[0] = w.value
errFlag[0] = err.value
return ret
def klcRestoreFactorySettings(hdl):
""" Reset default factory seetings.
Args:
hdl: the handle of opened device
Returns:
0: Success; negative number: failed.
"""
return klcLib.RestoreFactorySettings(hdl)
def klcUpdateOutputLUT(hdl, index, voltage):
""" Update LUT value.
Args:
hdl: the handle of opened device
index: index of the LUT array
voltage: output voltage 0~25
Returns:
0: Success; negative number: failed.
"""
return cmdUpdateOutputLUT(hdl, index, voltage)
def klcRemoveLastOutputLUT(hdl, count):
""" Remove the last of LUT array.
Args:
hdl: the handle of opened device
count: the count values will be removed from LUT array
Returns:
0: Success; negative number: failed.
"""
return cmdRemoveLastOutputLUT(hdl, count)
def klcSetOutputLUT(hdl, vols, size):
""" Set the LUT array data.
Args:
hdl: the handle of opened device
vols: the LUT values array
size: the count of the array 0~512
Returns:
0: Success; negative number: failed.
"""
return cmdSetOutputLUT(hdl, vols, size)
def klcStartLUTOutput(hdl):
""" Start LUT output.
Args:
hdl: the handle of opened device
Returns:
0: Success; negative number: failed.
"""
return klcLib.StartLUTOutput(hdl)
def klcStopLUTOutput(hdl):
""" Stop LUT output.
Args:
hdl: the handle of opened device
Returns:
0: Success; negative number: failed.
"""
return klcLib.StopLUTOutput(hdl)
def klcSetOutputLUTParams(hdl, mode, numCycles, delayTime,preCycleRest):
""" Set LUT parameters.
Args:
hdl: the handle of opened device
mode: 1 continuous; 2 cycle
numCycles: number of cycles 1~ 2147483648
delayTime: the sample intervals[ms] 1~ 2147483648
preCycleRest: the delay time before the cycle start[ms] 0~ 2147483648
Returns:
0: Success; negative number: failed.
"""
return cmdSetOutputLUTParams(hdl, mode, numCycles, delayTime,preCycleRest)
def klcGetOutputLUTParams(hdl, mode, numCycles, delayTime,preCycleRest):
""" Get LUT parameters.
Args:
hdl: the handle of opened device
mode: 1 continuous; 2 cycle
numCycles: number of cycles 1~ 2147483648
delayTime: the sample intervals[ms] 1~ 2147483648
preCycleRest: the delay time before the cycle start[ms] 0~ 2147483648
Returns:
0: Success; negative number: failed.
"""
m = c_ushort(0)
n = c_ulong(0)
d = c_ulong(0)
p = c_ulong(0)
ret = cmdGetOutputLUTParams(hdl, m, n, d,p)
mode[0] = m.value
numCycles[0] = n.value
delayTime[0] = d.value
preCycleRest[0] = p.value
return ret

226
KLCCommandLibTest.py Normal file
View File

@ -0,0 +1,226 @@
import time
try:
from KLCCommandLib64 import *
except OSError as ex:
print("Warning:",ex)
def main():
print("*** KLC device python example ***")
try:
devs = klcListDevices()
print(devs)
if(len(devs)<=0):
print('There is no devices connected')
exit()
klc = devs[0]
sn = klc[0]
print("connect ", sn)
hdl = klcOpen(sn, 115200, 3)
if(hdl<0):
print("open ", sn, " failed")
exit()
if(klcIsOpen(sn) == 0):
print("klcIsOpen failed")
klcClose(hdl)
exit()
# ------------ Example Disable/Enable global output -------------- #
klcSetEnable(hdl,2)
print("set output to enable")
if(klcSetEnable(hdl, 1)<0):
print("klcSetEnable failed")
en=[0]
if(klcGetEnable(hdl, en)<0):
print("klcGetEnable failed")
else:
print("klcGetEnable ", en)
# ---------------------------------------------------------------- #
# ------------ Example Present1 mode ----------------------------- #
print("Enable V1")
klcSetChannelEnable(hdl, 1)
print("set vol1 to 5.0")
if(klcSetVoltage1(hdl, 5)<0):
print("klcSetVoltage1 failed")
vol1=[0]
if(klcGetVoltage1(hdl, vol1)<0):
print("klcGetVoltage1 failed")
else:
print("klcGetVoltage1 ", vol1)
print("set freq 1 to 2005")
if(klcSetFrequency1(hdl, 2005)<0):
print("klcSetFrequency1 failed")
freq1=[0]
if(klcGetFrequency1(hdl, freq1)<0):
print("klcGetFrequency1 failed")
else:
print("klcGetFrequency1 ", freq1)
# ---------------------------------------------------------------- #
# ------------ Example Present2 mode ----------------------------- #
print("Enable V2")
klcSetChannelEnable(hdl, 2)
print("set vol2 to 10.0")
if(klcSetVoltage2(hdl, 10)<0):
print("klcSetVoltage2 failed")
vol2=[0]
if(klcGetVoltage2(hdl, vol2)<0):
print("klcGetVoltage2 failed")
else:
print("klcGetVoltage2 ", vol2)
print("set freq 2 to 3005")
if(klcSetFrequency2(hdl, 3005)<0):
print("klcSetFrequency2 failed")
freq2=[0]
if(klcGetFrequency2(hdl, freq2)<0):
print("klcGetFrequency2 failed")
else:
print("klcGetFrequency2 ", freq2)
# ---------------------------------------------------------------- #
# ------------ Example Switching mode ---------------------------- #
print("set to sw mode")
if(klcSetChannelEnable(hdl, 3)<0):
print("klcSetChannelEnable failed")
print("set sw frequency to 99")
if(klcSetSWFrequency(hdl, 99)<0):
print("klcSetSWFrequency failed")
swf=[0]
if(klcGetSWFrequency(hdl, swf)<0):
print("klcGetSWFrequency failed")
else:
print("klcGetSWFrequency ", swf)
# ---------------------------------------------------------------- #
time.sleep(5)
# ------------ Example Mode in mode ------------------------------ #
print("set input mode to enable")
if(klcSetInputMode(hdl, 1)<0):
print("klcSetInputMode failed")
im=[0]
if(klcGetInputMode(hdl, im)<0):
print("klcGetInputMode failed")
else:
print("klcGetInputMode ", im)
print("set mode in frequency")
if(klcSetFrequency1(hdl, 5000)<0):
print("klcSetFrequency1 failed")
# ---------------------------------------------------------------- #
# ------------ Example Trigger mode ------------------------------ #
print("set trigger mode to Pin 1")
if(klcSetTrigIOConfigure(hdl, 2)<0):
print("klcSetTrigIOConfigure failed")
trigger=[0]
if(klcGetTrigIOConfigure(hdl, trigger)<0):
print("klcGetTrigIOConfigure failed")
else:
print("klcGetTrigIOConfigure ", trigger)
# ---------------------------------------------------------------- #
# --------- Example Wheel lock, pannel brightness/timeout -------- #
print("set wheel lock to locked")
if(klcSetKcubeMMILock(hdl, 1)<0):
print("klcSetKcubeMMILock failed")
lock=[0]
if(klcGetKcubeMMILock(hdl, im)<0):
print("klcGetKcubeMMILock failed")
else:
print("klcGetKcubeMMILock ", im)
print("set pannel brightness to 90, timeout to never")
if(klcSetKcubeMMIParams(hdl, 90, 0xFFFF)<0):
print("klcSetKcubeMMIParams failed")
dbrightness=[0]
dtimeout=[0]
if(klcGetKcubeMMIParams(hdl, dbrightness, dtimeout)<0):
print("klcGetKcubeMMIParams failed")
else:
print("klcGetKcubeMMIParams dbrightness: ", dbrightness ," dtimeout:", dtimeout)
# ---------------------------------------------------------------- #
# ------------ Example get output status ------------------------- #
active=[0]
v=[0]
f=[0]
err=[0]
ch=[0]
if(klcGetOutPutStatus(hdl, active, v, f, err)<0):
print("klcGetOutPutStatus failed")
else:
print("klcGetOutPutStatus active: ", active ," voltage: ", v ," frequency: " , f, " errFlag ",err)
if(klcGetStatus(hdl, ch, vol1, freq1, vol2, freq2, swf, dbrightness, dtimeout, im, trigger, lock, err)<0):
print("klcGetStatus failed")
else:
print("klcGetStatus channel: ", ch ," vol1: ", vol1 ," freq1: " , freq1," vol2: ", vol2 ," freq2: " , freq2," swf: ", swf ," dbrightness: " , dbrightness," dtimeout: ", dtimeout ," im: " , im," trigger: ", trigger ," lock: " , lock, " errFlag ",err)
# ---------------------------------------------------------------- #
# ------------ Example run LUT ---------------------------------- #
print("Test LUT Array")
#disbale trigger mode
klcSetTrigIOConfigure(hdl, 1)
#disable mode in mode
klcSetInputMode(hdl, 0)
klcSetChannelEnable(hdl, 1)
#init array 2,4,6,8,10
vols = [2,4,6,8,10]
volarr = (c_float * len(vols))(*vols)
print("set LUT array")
if(klcSetOutputLUT(hdl, volarr, 5)<0):
print("klcSetOutputLUT failed")
#update second 4 to 5
if(klcUpdateOutputLUT(hdl, 1, 5)<0):
print("klcUpdateOutputLUT failed")
#remove last one the arry will be 2,5,6,8
if(klcRemoveLastOutputLUT(hdl, 1)<0):
print("klcRemoveLastOutputLUT failed")
print("set LUT parameters")
if(klcSetOutputLUTParams(hdl, 2, 3, 1000, 0)<0):
print("klcSetOutputLUTParams failed")
lut_mode=[0]
lut_cyclenumber=[0]
lut_delay=[0]
lut_precycle_rest=[0]
if(klcGetOutputLUTParams(hdl, lut_mode, lut_cyclenumber, lut_delay, lut_precycle_rest)<0):
print("klcGetOutputLUTParams failed")
else:
print("klcGetOutputLUTParams mode: ", lut_mode ," lut_cyclenumber:", lut_cyclenumber," lut_delay:", lut_delay," lut_precycle_rest:", lut_precycle_rest)
print("start LUT")
if(klcStartLUTOutput(hdl)<0):
print("klcStartLUTOutput failed")
t=0
while(t<20):
klcGetOutPutStatus(hdl, active, v, f, err)
print("Get LUT output: ", active ," voltage: ", v ," frequency: " , f, " errFlag ", err)
time.sleep(1)
t+=1
print("stop LUT")
if(klcStopLUTOutput(hdl)<0):
print("klcStopLUTOutput failed")
# ---------------------------------------------------------------- #
klcClose(hdl)
except Exception as ex:
print("Warning:", ex)
print("*** End ***")
input()
main()

BIN
KLCCommandLib_x64.dll Normal file

Binary file not shown.

BIN
KLCCommandLib_x64.lib Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

4
readme.txt Normal file
View File

@ -0,0 +1,4 @@
For the code to work, change the directory to load the KLCCommandLib_x64.dll file in 'KLCCommandLib64.py', line 5.
The line of code is as follows:
klcLib=cdll.LoadLibrary(r"C:\Users\rtan\Documents\RyanWork2024\Dasha-LCR_Code\Thorlabs_KLC_PythonSDK\"KLCCommandLib_x64.dll")