Skip to content

Instantly share code, notes, and snippets.

@avachen
Created September 26, 2018 22:17
Show Gist options
  • Save avachen/ab0c821babfb0faa31fcd1f76047a4fb to your computer and use it in GitHub Desktop.
Save avachen/ab0c821babfb0faa31fcd1f76047a4fb to your computer and use it in GitHub Desktop.
snippet ironpython <=> python2 <=> serial
import platform
if (not platform.python_implementation().lower() == 'ironpython'):
print("Wrong version of Python, use IronPython")
exit(1)
import wpf, clr, System, time, math, csv, subprocess
from System import DateTime
clr.AddReferenceToFileAndPath("C:\Users\Shamblelab\Documents\shamblelab\instron\FUTEK USB DLL.dll")
clr.AddReferenceByPartialName("IronPython")
import FUTEK_USB_DLL
from FUTEK_USB_DLL import USB_DLL
from System.Windows import Application, Window
from IronPython.Compiler import CallTarget0
from zaber.serial import AsciiSerial, AsciiDevice, AsciiCommand, AsciiReply
port = AsciiSerial("COM4")
device = AsciiDevice(port,1)
resultfile = open('results.csv','wb')
writer = csv.writer(resultfile, delimiter=' ',quotechar='|',quoting=csv.QUOTE_MINIMAL)
#Global variables
time = []
position = []
load = []
#Get default max limits from zaber
reply = device.send("set maxspeed 60000")
reply = device.send("get maxspeed")
vel_default = reply.data
# Zaber functions
def check_command_succeeded(reply):
if (reply.reply_flag != "OK") and (reply.reply_flag != "--"): # If command not accepted (zaber received "RJ")
print ("Zaber Command rejected because: {}".format(reply.data))
return False
else: #Command was accepted
return True
def clean_routine():
device.send("set maxspeed".format(vel_default))
print("End program")
port.close()
def save_data(filename):
writer.writerow(time)
writer.writerow(load)
writer.writerow(position)
resultfile.close()
result = subprocess.call(['python','plotter.py', 'results.csv', filename], shell=True)
# Instron Error Codes
class FutekError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ZaberError(Exception):
def __init__(self):
self.value = value
def __str__(self):
return repr(self.value)
# Instron Controller
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'Instron_Controller.xaml')
self.ZaberHomed = 0
self.Title = "Instron Testing Using FUTEK USB DLL " + System.Reflection.Assembly.GetAssembly(type(FUTEK_USB_DLL.USB_DLL)).GetName().Version.ToString()
self.oFUTEKUSBDLL = FUTEK_USB_DLL.USB_DLL()
self.ResultsFile = "results"
self.SerialNumber = "647386"
self.PullSpeed = ""
self.vel_microstep = ""
self.DeviceHandle = ""
self.Temp = ""
self.zaberhomepos = ""
self.testzeropos = ""
self.currentPos = ""
self.movestep = 0
self.LoadCapacity = 49 ##grams###
self.OffsetValue = 0
self.FullscaleValue = 0
self.FullscaleLoad = 0
self.DecimalPoint = 0
self.UnitCode = 0
self.Tare = 0.0
self.NormalData = 0
self.CalculatedReading = 0.0
self.OpenedConnection = False
self.dispatcherTimer = System.Windows.Threading.DispatcherTimer()
self.StartTime = DateTime.Now
return
def HomeButton_Click(self, sender, e):
reply = device.home()
reply = device.send("get pos")
self.zaberhomepos = int(reply.data)
if check_command_succeeded(reply):
device.poll_until_idle()
self.ZaberHomed = 1
print("Zaber Homed to absolute zero, ready to load sample")
else:
print("Zaber home failed.")
exit(1)
if self.OpenedConnection == True:
return
self.oFUTEKUSBDLL.Open_Device_Connection(self.SerialNumber)
if self.oFUTEKUSBDLL.DeviceStatus == "0":
print("Load Cell Connected")
pass
else:
System.Windows.MessageBox.Show("Load Cell Error " + self.oFUTEKUSBDLL.DeviceStatus)
return
self.DeviceHandle = self.oFUTEKUSBDLL.DeviceHandle
self.OpenedConnection = True
self.GetOffsetValue()
self.GetFullscaleValue()
self.GetFullscaleLoad()
self.GetDecimalPoint()
self.GetUnitCode()
self.FindUnits()
if self.OpenedConnection:
while True:
self.Temp = self.oFUTEKUSBDLL.Normal_Data_Request(self.DeviceHandle)
if self.Temp.isnumeric():
break
self.NormalData = int(self.Temp)
self.Tare = self.NormalData - self.OffsetValue
self.CalculatedReading = self.NormalData - self.OffsetValue - self.Tare
self.CalculatedReading /= float(self.FullscaleValue - self.OffsetValue)
self.CalculatedReading *= self.FullscaleLoad
self.CalculatedReading /= float(pow(10, self.DecimalPoint))
if self.CalculatedReading >= (self.LoadCapacity):
raise FutekError("Reading above Load Capacity")
elif self.CalculatedReading < (-10):
raise FutekError("Reading Excessive Compression Forces")
print("Load Cell Tared")
self.CalculatedReadingTextBox.Text = "{0:.3f}".format(self.CalculatedReading)
if self.ResultsTextBox.Text:
self.ResultsFile = self.ResultsTextBox.Text
print("Press Start when Ready")
return
def StartButton_Click(self, sender, e):
if not self.ZaberHomed or not self.OpenedConnection:
print("Home System First.")
print("Exiting Program.")
exit(1)
if self.OpenedConnection:
while True:
self.Temp = self.oFUTEKUSBDLL.Normal_Data_Request(self.DeviceHandle)
if self.Temp.isnumeric():
break
self.NormalData = int(self.Temp)
self.Tare = self.NormalData - self.OffsetValue
self.CalculatedReading = self.NormalData - self.OffsetValue - self.Tare
self.CalculatedReading /= float(self.FullscaleValue - self.OffsetValue)
self.CalculatedReading *= self.FullscaleLoad
self.CalculatedReading /= float(pow(10, self.DecimalPoint))
self.CalculatedReadingTextBox.Text = "{0:.3f}".format(self.CalculatedReading)
print("Futek Tared at Current Position")
reply = device.send("get pos")
print("Zaber Zeroed at Current Position")
self.testzeropos = int(reply.data)
self.PullSpeed = self.PullSpeedTextBox.Text # goes backwards at mm/s
self.vel_microstep = int(math.floor(float(self.PullSpeed)*826))
reply = device.send("set maxspeed {}".format(self.vel_microstep))
check_command_succeeded(reply)
self.dispatcherTimer.Interval = System.TimeSpan(0,0,0,0,100)
self.dispatcherTimer.Tick += self.dispatcherTimer_Tick
print("Moving...")
reply = device.send("move abs {}".format(self.zaberhomepos))
check_command_succeeded(reply)
time.append('00:00:00')
position.append(self.testzeropos)
load.append(self.CalculatedReading)
self.startTime = DateTime.Now
self.dispatcherTimer.Start()
return
def StopButton_Click(self, sender, e):
self.dispatcherTimer.Stop()
device.send("estop")
print("Stopped.")
self.ZaberHomed = 0
if self.OpenedConnection:
pass
else:
return
self.oFUTEKUSBDLL.Close_Device_Connection(self.DeviceHandle)
if self.oFUTEKUSBDLL.DeviceStatus == "0":
pass
else:
System.Windows.MessageBox.Show("Device Error " + self.oFUTEKUSBDLL.DeviceStatus)
return
self.OpenedConnection = False
self.Tare = 0
save_data(self.ResultsFile)
clean_routine()
return
def TareButton_Click(self, sender, e):
self.oFUTEKUSBDLL.Set_Unit_Code(self.DeviceHandle, 5) # g
self.GetUnitCode()
self.Tare = self.NormalData - self.OffsetValue
return
def GrossButton_Click(self, sender, e):
self.Tare = 0
return
# <summary>
# Gets the offset value by using the FUTEK DLL Method and
# check if it's numeric and then parse it into integer
# then store it into the memory
# </summary>
def GetOffsetValue(self):
while True:
self.Temp = self.oFUTEKUSBDLL.Get_Offset_Value(self.DeviceHandle)
if self.Temp.isnumeric():
break
self.OffsetValue = int(self.Temp)
return
# <summary>
# Gets the fullscale value by using the FUTEK DLL Method and
# check if it's numeric and then parse it into integer
# then store it into the memory
# </summary>
def GetFullscaleValue(self):
while True:
self.Temp = self.oFUTEKUSBDLL.Get_Fullscale_Value(self.DeviceHandle)
if self.Temp.isnumeric():
break
self.FullscaleValue = int(self.Temp)
return
# <summary>
# Gets the fullscale load by using the FUTEK DLL Method and
# check if it's numeric and then parse it into integer
# then store it into the memory
# </summary>
def GetFullscaleLoad(self):
while True:
self.Temp = self.oFUTEKUSBDLL.Get_Fullscale_Load(self.DeviceHandle)
if self.Temp.isnumeric():
break
self.FullscaleLoad = int(self.Temp)
return
# <summary>
# Gets the number of decimal places by using the FUTEK
# DLL Method and check if it's numeric and then parse
# it into integer then store it into the memory
# </summary>
def GetDecimalPoint(self):
while True:
self.Temp = self.oFUTEKUSBDLL.Get_Decimal_Point(self.DeviceHandle)
if self.Temp.isnumeric():
break
self.DecimalPoint = int(self.Temp)
if self.DecimalPoint > 3:
self.DecimalPoint = 0
return
# <summary>
# Gets the unit code to later find unit needed for the device
# by using the FUTEK DLL Method and check if it's numeric and
# then parse it into integer and then store it into the memory
# </summary>
def GetUnitCode(self):
while True:
self.Temp = self.oFUTEKUSBDLL.Get_Unit_Code(self.DeviceHandle)
if self.Temp.isnumeric():
break
self.UnitCode = int(self.Temp)
return
# <summary>
# Uses the UnitCode from the memory to find the correct
# unit for the device
# </summary>
# <remarks>
# For more information about unit code visit:
# http://www.futek.com/files/docs/API/FUTEK_USB_DLL/webframe.html#UnitCodes.html
# </remarks>
def FindUnits(self):
units = {
0 : "atm", 1 : "bar", 2 : "dyn", 3 : "ft-H20", 4 : "ft-lb", 5 : "g", 6 : "g-cm", 7 : "g-mm", 8 : "in-H20", 9 : "in-lb",
10 : "in-oz", 11 : "kdyn", 12 : "kg", 13 : "kg-cm", 14 : "kg/cm2", 15 : "kg-m", 16 : "klbs", 17 : "kN", 18 : "kPa", 19 : "kpsi",
20 : "lbs", 21 : "Mdyn", 22 : "mmHG", 23 : "mN-m", 24 : "MPa", 25 : "MT", 26 : "N", 27 : "N-cm", 28 : "N-m", 29 : "N-mm",
30 : "oz", 31 : "psi", 32 : "Pa", 33 : "T", 34 : "mV/V", 35 : "µA", 36 : "mA", 37 : "A", 38 : "mm", 39 : "cm",
40 : "dm", 41 : "m", 42 : "km", 43 : "in", 44 : "ft", 45 : "yd", 46 : "mi", 47 : "µg", 48 : "mg", 49 : "LT",
50 : "mbar", 51 : "˚C", 52 : "˚F", 53 : "K", 54 : "˚Ra", 55 : "kN-m", 56 : "g-m", 57 : "nV", 58 : "µV", 59 : "mV",
60 : "V", 61 : "kV", 62 : "NONE"
}
self.UnitsTextBox.Text = units.get(self.UnitCode, "Undefined")
return
def dispatcherTimer_Tick(self, sender, e):
if self.OpenedConnection:
while True:
self.Temp = self.oFUTEKUSBDLL.Normal_Data_Request(self.DeviceHandle)
if self.Temp.isnumeric():
break
try:
now = DateTime.Now
difference = now - self.StartTime
time.append(str(difference))
reply = device.send("get pos")
self.currentPos = int(reply.data)
position.append(self.currentPos)
print(self.currentPos)
self.NormalData = int(self.Temp)
self.CalculatedReading = self.NormalData - self.OffsetValue - self.Tare
self.CalculatedReading /= float(self.FullscaleValue - self.OffsetValue)
self.CalculatedReading *= self.FullscaleLoad
self.CalculatedReading /= float(pow(10, self.DecimalPoint))
load.append(self.CalculatedReading)
self.CalculatedReadingTextBox.Text = "{0:.3f}".format(self.CalculatedReading)
if self.CalculatedReading >= (self.LoadCapacity):
raise FutekError("Reading above Load Capacity")
elif self.CalculatedReading < (-10 ):
raise FutekError("Reading Excessive Compression Forces")
except FutekError as e:
self.dispatcherTimer.Stop()
device.send("estop")
print "Futek Error:", e.value
save_data(self.ResultsFile)
clean_routine()
except ZaberError as e:
self.dispatcherTimer.Stop()
device.send("estop")
print "Zaber Error:", e.value
save_data(self.ResultsFile)
clean_routine()
return
if __name__ == '__main__':
Application().Run(MyWindow()) #everything needs to run in the window, otherwise window gets confused
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment