Software/Python
From ZaberWiki
Currently we have limited experience with Python, but here are a few simple programs to get you started communicating with Zaber devices. Note that in order to use the serial port in python you must install the pyserial module. See http://pyserial.sourceforge.net/ for more information.
Contents |
[edit] Displaying a list of available serial ports
The following program will work in Windows or Linux. It should display all resident serial ports, but in Linux it may miss virtual ports (ex USB to serial converters).
#! /usr/bin/env python
import serial
def scan():
# scan for available ports. return a list of tuples (num, name)
available = []
for i in range(256):
try:
s = serial.Serial(i)
available.append( (i, s.portstr))
s.close()
except serial.SerialException:
pass
return available
print "Found ports:"
for n,s in scan(): print "(%d) %s" % (n,s)
The following program will work only in Linux. It will display all serial ports including virtual ports (ex USB to serial converters).
#! /usr/bin/env python
import serial, glob
def scan():
# scan for available ports. return a list of device names.
return glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*')
print "Found ports:"
for name in scan(): print name
[edit] Openning a serial port, sending an instruction, and receiving a reply
The following code opens the serial port "/dev/ttyUSB0" (a USB to serial adapter installed on a Linux machine) and sends an instruction to a Zaber device to return its power supply voltage. After 1 second, the program checks for a response and displays it.
#!/usr/bin/env python
import serial, sys, time, glob
def scan():
# scan for available ports. return a list of device names
return glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*')
def send(inst):
# send instruction
# inst must be a list of 6 bytes (no error checking)
for i in range (6):
ser.write(chr(inst[i]))
return
def receive():
# return 6 bytes from the receive buffer
# there must be 6 bytes to receive (no error checking)
r = [0,0,0,0,0,0]
for i in range (6):
r[i] = ord(ser.read(1))
return r
# open serial port
# replace "/dev/ttyUSB0" with "COM1", "COM2", etc in Windows
try:
ser = serial.Serial("/dev/ttyUSB0", 9600, 8, 'N', 1, timeout=5)
except:
print "Error opening com port. Quitting."
sys.exit(0)
print "Opening " + ser.portstr
instruction = [1,52,0,0,0,0] # return power supply voltage
print "Sending instruction", instruction
send(instruction)
time.sleep(1) # wait for 1 second
try:
reply = receive()
print "Receiving reply", reply
print "Device number:", reply[0]
print "Command number:", reply[1]
print "Supply voltage:", reply[2]/10.0, "V"
except:
print "No reply was received."
print "Closing " + ser.portstr
ser.close()
[edit] Open-Source Zaber Python Library
One of our customers kindly created an open-source Zaber library for Python.
