Recording Position

This example demonstrates how can you record position of the device as it is being moved manually by the knob. Communication to the device is using ASCII protocol.

The position is recorded into CSV file along with timestamp. CSV file named “position_log.csv” is created in the same directory the script is executed from. If the program is executed repeatedly, file will be overwritten. CSV file can be later opened by e.g. Microsoft Excel.

Position is recorded in microsteps. Microstep size is value specific to the device. In order to convert position to e.g. millimeters appropriate constant “Microstep Size (Default Resolution)” from device datasheet must be used.

Please change the port in the code to appropriate port on you computer (e.g. COM3). Note that when the program is running, no other program can access the computer port.

# choose appropriate port on your computer (currently COM5)
SERIAL_PORT = "COM5"

Example code (Download):

import time
from datetime import datetime
from zaber.serial import AsciiSerial, AsciiDevice

# choose appropriate port on your computer (currently COM5)
SERIAL_PORT = "COM5"

# assuming the device has number 1
DEVICE_NUMBER = 1

# name of the file position is written to
FILE_NAME = 'position_log.csv'


def main():
    # print the initial instructions for the user
    print("Recording position.")
    print("Press Ctrl + C to stop the program...")

    # create and open serial port
    port = AsciiSerial(SERIAL_PORT)
    # address connected device you want to record position of (currently 1)
    device = AsciiDevice(port, DEVICE_NUMBER)

    # create new file or overwrite the old one in the current directory
    with open(FILE_NAME, mode='w+') as position_log:
        # write header to the CSV file
        position_log.write("Timestamp,Position\n")

        # do indefinitely
        while True:
            # query position in microsteps and current time
            position = device.get_position()
            now = datetime.now()

            # write time and position to the CSV file
            position_log.write("{},{}\n".format(now, position))

            # wait 1 second before querying position again
            time.sleep(1)


# run main function on program start
if __name__ == '__main__':
    main()