#!/usr/bin/python# -------------------------------------------# HBSTEP01B Stepper Motor control test code# -------------------------------------------## Program uses MLAB Python modules library from https://github.com/MLAB-project/pymlab#uncomment for debbug purposesimport logginglogging.basicConfig(level=logging.DEBUG)import sysimport timeimport spidev#### Script Arguments ###############################################if len(sys.argv) < 2:sys.stderr.write("Invalid number of arguments.\n")sys.stderr.write("Usage: %s PORT ADDRESS SPEED MOVE_DISTANCE\n" % (sys.argv[0], ))sys.exit(1)elif len(sys.argv) == 2:PORT = eval(sys.argv[1])SPEED = 5DISTANCE = 50elif len(sys.argv) == 3:SPEED = eval(sys.argv[2])DISTANCE = 100elif len(sys.argv) == 4:SPEED = eval(sys.argv[2])DISTANCE = eval(sys.argv[3])else:PORT = 0SPEED = 10DISTANCE = 50class axis:def __init__(self, SPI_handler, Direction, StepsPerUnit):' One axis of robot 'self.spi = SPI_handlerself.Dir = Directionself.SPU = StepsPerUnitself.Reset()def Reset(self):' Reset Axis and set default parameters for H-bridge 'self.spi.xfer([0xC0]) # reset# self.spi.xfer( 0x14) # Stall Treshold setup# self.spi.xfer( 0xFF)# self.spi.xfer( 0x13) # Over Current Treshold setup# self.spi.xfer( 0xFF)self.spi.xfer([0x15]) # Full Step speedself.spi.xfer([0xFF])self.spi.xfer([0xFF])self.spi.xfer([0x05]) # ACCself.spi.xfer([0x00])self.spi.xfer([0x10])self.spi.xfer([0x06]) # DECself.spi.xfer([0x00])self.spi.xfer([0x10])self.spi.xfer([0x0A]) # KVAL_RUNself.spi.xfer([0xFF])self.spi.xfer([0x0B]) # KVAL_ACCself.spi.xfer([0xFF])self.spi.xfer([0x0C]) # KVAL_DECself.spi.xfer([0xFF])self.spi.xfer([0x18]) # CONFIGself.spi.xfer([0b00111000])self.spi.xfer([0b00000000])def MaxSpeed(self, speed):' Setup of maximum speed 'self.spi.xfer([0x07]) # Max Speed setupself.spi.xfer([0x00])self.spi.xfer([speed])def ReleaseSW(self):' Go away from Limit Switch 'while self.ReadStatusBit(2) == 1: # is Limit Switch ON ?self.spi.xfer([0x92 | (~self.Dir & 1)]) # release SWwhile self.IsBusy():passself.MoveWait(10) # move 10 units awaydef GoZero(self, speed):' Go to Zero position 'self.ReleaseSW()self.spi.xfer([0x82 | (self.Dir & 1)]) # Go to Zeroself.spi.xfer([0x00])self.spi.xfer([speed])while self.IsBusy():passtime.sleep(0.3)self.ReleaseSW()def Move(self, units):' Move some distance units from current position 'steps = units * self.SPU # translate units to stepsif steps > 0: # look for directionself.spi.xfer([0x40 | (~self.Dir & 1)])else:self.spi.xfer([0x40 | (self.Dir & 1)])steps = int(abs(steps))self.spi.xfer([(steps >> 16) & 0xFF])self.spi.xfer([(steps >> 8) & 0xFF])self.spi.xfer([steps & 0xFF])def MoveWait(self, units):' Move some distance units from current position and wait for execution 'self.Move(units)while self.IsBusy():passtime.sleep(0.8)def Float(self):' switch H-bridge to High impedance state 'self.spi.xfer([0xA0])def ReadStatusBit(self, bit):' Report given status bit 'self.spi.xfer([0x39]) # Get status commanddata = self.spi.readbytes(1) # 1st bytedata = data + (self.spi.readbytes(1)) # 1st byteprint dataif bit > 7: # extract requested bitOutputBit = (data[0] >> (bit - 8)) & 1else:OutputBit = (data[1] >> bit) & 1return OutputBitdef IsBusy(self):""" Return True if tehre are motion """if self.ReadStatusBit(1) == 1:return Falseelse:return True# End Class axis --------------------------------------------------print "Stepper motor control test started. \r\n"print "Max motor speed: %d " % SPEEDprint "Distance to run: %d " % DISTANCEtry:print "SPI configuration.."spi = spidev.SpiDev() # create a spi objectspi.open(0, 0) # open spi port 0, device (CS) 0spi.mode = 0b01spi.lsbfirst = Falsespi.bits_per_word = 8spi.cshigh = False#spi.SPI_config(spi.I2CSPI_MSB_FIRST| spi.I2CSPI_MODE_CLK_IDLE_HIGH_DATA_EDGE_TRAILING| spi.I2CSPI_CLK_461kHz)time.sleep(1)print "Axis inicialization"X = axis(spi, 0, 641) # set Number of Steps per axis Unit and set Direction of RotationX.MaxSpeed(SPEED) # set maximal motor speedprint "Axis is running"for i in range(5):print iX.MoveWait(DISTANCE) # move forward and wait for motor stopprint "Changing direction of rotation.."time.sleep(1.1)X.MoveWait(-DISTANCE) # move backward and wait for motor stopprint "Changing direction of rotation.."time.sleep(1.1)X.Float() # release powerfinally:print "stop"