################################################
# Module: motor.py
# Created: 21 April 2009
# Author: Daniel Thompson
# http://danthompsonsblog.blogspot.com/
# Version: 0.2
# License: GPLv3
# http://www.fsf.org/licensing/
'''Provides a serial connection abstraction layer
for use with Arduino "MultipleSteppers" sketch.
'''
#######################fhgjfhjfghjfghjgfhjfghjgfhjghjghjghj#########################
import motor
import serial

#setup the serial port
usbport = 'COM4'
ser = serial.Serial(usbport, 115200, timeout=1)

# convert a decimal (denary, base 10) integer to a binary string (base 2)
def d2b(n):
'''convert denary integer n to binary string bStr'''
bStr = ''
if n < 0: raise ValueError, "must be a positive integer"
if n == 0:
return '0'
while n > 0:
bStr = str(n % 2) + bStr
n = n >> 1
return bStr

'''Returns the number of bit bytes (eighths) in binary string.
Always rounds up, never rounds down.'''
def binaryCount(number):
sNumber = str(number)
length = len(sNumber)
numBytes = length / 8.0
numBytesInt = length / 8
if numBytes > numBytesInt:
return numBytesInt + 1
else:
return numBytesInt

'''This function gets the first byte, removes it from the string and
returns a new value'''
def shiftLeft(binary):
sBinary = str(binary)
firstByte = int(sBinary,2) & int('11111111',2)
newBinary = int(sBinary,2) >> 8
nBinary = motor.d2b(newBinary)
print "I took away", firstByte
print "And now I'm left with", nBinary
return nBinary

# Wraps several functions to split
# the "steps" integer into bytes ready for sending
# Then it write packet header (255) and then
# all the other bytes

'''The final move command. I combines all the other functions in this
module to move the motor to the specified position'''
def position(num,degsPerStepFloat,stepsFloat):
steps = int(stepsFloat / degsPerStepFloat)
if(steps < 65535 and steps > -1):
binary = motor.d2b(steps)
numBytes = motor.binaryCount(binary)
# from the shiftLef def
ser.write(chr(255))
# note: the 2 in (0,2,1) is critical for alowing two bytes through every time.
for i in range(0,2,1):
sBinary = str(binary)
firstByte = int(sBinary,2) & int('11111111',2)
newBinary = int(sBinary,2) >> 8
binary = motor.d2b(newBinary)
ser.write(chr(firstByte))
if(steps > -65535 and steps < 0):
stepsNeg = steps * -1
binary = motor.d2b(stepsNeg)
numBytes = motor.binaryCount(binary)
# from the shiftLef def
ser.write(chr(220))
# note: the 2 in (0,2,1) is critical for alowing two bytes through every time.
for i in range(0,2,1):
sBinary = str(binary)
firstByte = int(sBinary,2) & int('11111111',2)
newBinary = int(sBinary,2) >> 8
binary = motor.d2b(newBinary)
ser.write(chr(firstByte))
return stepsFloat

No comments:

Post a Comment