Pages

Thursday, May 30, 2013

GPi stepping motor functions - none found!

So I searched my old long program for stepping motor functions.  To my surprise, there was no GPi stepping motor functions.  Actually I only GPi for servo motors but not stepping motors.  For stepping motors I only use MCP23008 (or MCP23017, I forgot).

So now I have 2 choices, (1) convert the MCP230xx functions for GPi, (2) play with GPi servo motor first, and consider stepping motor later.

So I skimmed the GPi functions.  To my surprise again, I found the GPi stepper motor function, which is very short, compared to MCP230xx.  I need to read it again to see why it was so short, or whether it is an incomplete function, and of course short!


# *** Stepping motor test using MCP23008 **************************************

# *** Unipolar Stepping Motor 28BYJ48/NPM-PF35/PX245 **************************

# Unipolar Stepping Motor Switching Sequence
# 1. Wave sequence = 1 - 3 - 2 - 4 (A-, B-, A+, B+)
# 2. Full step sequence = 13 - 14 - 24 - 23 (A-B-, A-B+, A+B+, A+B-)
# 3. Half step sequence  = 13 - 1 - 14 - 4 - 24 - 2 - 23 - 3
# 4. One step swing = 1 - 3 - 1 - 3 (A-, B-, A-, B-)
# Winding        A-(1)    A+(2)    B-(3)   B+(4)    COM
# NPM PF35       Black    Yellow   Brown   Orange   Red
# 28BYJ48        Pink     Orange   Blue    Yellow   Red
# PX245          Black    Green    Blue    Red      Yelow/White

# * Convert decimal pin number to hex *
def convert1PinToHex(p): # convert 1 of 8 high pin to hex
    hexString = 0x01
    for count in range(p-1):
    hexString = hexString << 1
    return hexString

def convert2PinToHex(p1, p2):  # convert 2 of 8 high pins to hex
    return (convert1PinToHex(p1) | convert1PinToHex(p2))

def convert2PinToHighNibble(p1, p2):  # convert 2 of 8 high pins to high nibble
    lowNibble = convert1PinToHex(p1) | convert1PinToHex(p2)
    highNibble = lowNibble << 4
    return highNibble

# * Move unipolar stepping motor *

def WriteMotorWindingWaveSequence1324(RegisterBaseAddress, NibbleType, StepCount, StepTime): # move motor using 13-24 sequence
    # Set port all output

    WriteDataByte(Mcp23008BaseAddress1, RegisterAddressOffsetArrayBank0, InputOutputDirection, PortA, AllOutputByte)

    if NibbleType == LowNibble:
hexString1 =  convert2PinToHex(1, 3)
  hexString2 =  convert2PinToHex(2, 4)
    else:
hexString1 = convert2PinToHighNibble(1, 3)
hexString2 = convert2PinToHighNibble(2, 4)
    for i in range(StepCount):
        WriteDataByte(Mcp23008BaseAddress1, RegisterAddressOffsetArrayBank0, OutputLatch, PortA, hexString1)
    time.sleep(StepTime)
        WriteDataByte(Mcp23008BaseAddress1, RegisterAddressOffsetArrayBank0, OutputLatch, PortA, hexString2)
        time.sleep(StepTime)

def WriteMotorWindingFullStepSequence13232414(RegisterBaseAddress, NibbleType, StepCount, StepTime): #move motor using 13-23-24-14 sequence
    # Set port all output
    WriteDataByte(Mcp23008BaseAddress1, RegisterAddressOffsetArrayBank0, InputOutputDirection, PortA, AllOutputByte)

    if NibbleType == LowNibble:
    motorWindingActivationPatternArray = (0x05, 0x06, 0x0a, 0x09)
    else:
motorWindingActivationPatternArray = (0x50, 0x60, 0xa0, 0x90)
    for i in range(StepCount):
for pattern in motorWindingActivationPatternArray:
            WriteDataByte(Mcp23008BaseAddress1, RegisterAddressOffsetArrayBank0, OutputLatch, PortA, pattern)
   time.sleep(StepTime)

def TestConvert1PinToHex(): # test convert 1 high pin to hex
    print "*** Testing 1 pin number decimal 0 ~ 7 converted to hexdecimal 0x01 ~ 0x80"
    for d in range(8):
    print hex(convert1PinToHex(d))

def TestConvert2PinToHex(p1, p2): # test convert 2 high pins to hex
    print "*** Testing 2 pin numbers decimal 0 ~ 7 converted to hexdecimal"
    print "Pin 1 = ", p1, "Pin 2 = ", p2
    print "Hex = ", hex(convert2PinToHex(p1, p2))

def TestConvert2PinToHighNibble(p1, p2): # test convert 2 of 8 high pins to high nibble
    print "*** Testing 2 pin numbers decimal 0 ~ 7 converted to high nibble"
    print "Pin 1 = ", p1, "Pin 2 = ", p2
    print "HighNibble = ", hex(convert2PinToHighNibble(p1, p2))

def MoveTwoMotors(RegisterBaseAddress):
OneBeep()
WriteMotorWindingWaveSequence1324(Mcp23008BaseAddress1, LowNibble, TwentyTimes, FiftyMilliSeconds)
OneBeep()
WriteMotorWindingWaveSequence1324(Mcp23008BaseAddress1, HighNibble, TwentyTimes, FiftyMilliSeconds)
OneBeep()
WriteMotorWindingFullStepSequence13232414(Mcp23008BaseAddress1, LowNibble, TwentyTimes, OneHundredMilliSeconds)
OneBeep()
WriteMotorWindingFullStepSequence13232414(Mcp23008BaseAddress1, HighNibble, TwentyTimes, OneHundredMilliSeconds)

def TestMotor():
    MotorRegisterBaseAddress = Mcp23008BaseAddress1
    MoveTwoMotors(MotorRegisterBaseAddress)

def MoveUnipolarSteppingMotor(registerBaseAddress, NibbleType, StepCount, StepTime):
    SetupPortAoutputPortBinputPullUpMcp23017(registerBaseAddress)

    if NibbleType == LowNibble:
hexString1 =  convert2PinToHex(1, 3)
  hexString2 =  convert2PinToHex(2, 4)
    else:
hexString1 = convert2PinToHighNibble(1, 3)
hexString2 = convert2PinToHighNibble(2, 4)

    for i in range(StepCount):
        WriteDataByte(registerBaseAddress, RegisterAddressOffsetArrayBank0, OutputLatch, PortA, hexString1)
    time.sleep(StepTime)
        WriteDataByte(registerBaseAddress, RegisterAddressOffsetArrayBank0, OutputLatch, PortA, hexString2)
        time.sleep(StepTime)

def TestMoveMotor():
    registerBaseAddress = Mcp23017BaseAddressSystemB1
    nibbleType = LowNibble
    stepCount = OneHundredTimes
    stepTime = OneHundredMilliSeconds
    MoveUnipolarSteppingMotor(registerBaseAddress, nibbleType, 500, 0.05)


# *** Guzunty Pi CPLD (XC9572XL) Functions ************************************

# *** Core 16o8i **************************************************************

# https://raw.github.com/Guzunty/Pi/master/src/gz_16o8i/gz_16o8i.rpt

# * 16o8i Fitter Report Summary *

# * 17 Outputs **

# Signal Name         Loc     Pin
# outputs<0>          FB1_2   1  
# outputs<1>          FB1_5   2  
# outputs<2>          FB1_6   3  
# outputs<3>          FB1_8   4  
# outputs<4>          FB1_15  8  
# outputs<5>          FB1_17  9  
# outputs<6>          FB2_2   35  
# outputs<7>          FB2_5   36  
# outputs<8>          FB2_6   37  
# outputs<9>          FB2_8   38  
# outputs<10>         FB2_15  43  
# outputs<11>         FB2_17  44  
# outputs<12>         FB3_2   11  
# outputs<13>         FB3_5   12  
# outputs<14>         FB3_8   13  
# outputs<15>         FB3_9   14  
# miso                FB4_17  34  

# ** 11 Inputs **

# Signal Name         Loc     Pin  Type      
# inputs<6>           FB1_11  6~   GCK/I/O [GCK2]
# inputs<7>           FB1_14  7~   GCK/I/O [GCK3]
# inputs<0>           FB3_14  19   I/O    
# inputs<1>           FB3_15  20   I/O    
# inputs<2>           FB3_16  24   I/O    
# inputs<3>           FB3_17  22   I/O    
# inputs<4>           FB4_2   25   I/O    
# inputs<5>           FB4_5   26   I/O    
# sclk                FB4_11  28   I/O    
# mosi                FB4_14  29   I/O    
# sel                 FB4_15  33   I/O    

# * Guzunty Pi 16o8i Pin numbering ********************************************

# Pin O0  = Winding 1 (Unipolar stepping motor A- winding)
# Pin O1  = Winding 2 (Unipolar stepping motor A+ winding)
# Pin O2  = Winding 3 (Unipolar stepping motor B- winding)
# Pin O3  = Winding 4 (Unipolar stepping motor B+ winding)

# Pin O4  = Column 0 (Decimal keypad Column 0)
# Pin O5  = Column 1 (Decimal keypad Column 1)
# Pin O5  = Column 2 (Decimal keypad Column 2)
# Pin O7  = Reserved

# Pin O8  = RegisterSelect (LCD1602A)
# Pin O9  = WriteEnable (LCD1602A)
# Pin O10 = DataBit4 (LCD1602A)
# Pin O11 = DataBit5 (LCD1602A)

# Pin O12 = DataBit6 (LCD1602A)
# Pin O13 = DataBit7 (LCD1602A)
# Pin O14 = Reserved
# Pin O15 = Reserved

# Pin I0  = Row 0 (Decimal keypad Row 0)
# Pin I1  = Row 1 (Decimal keypad Row 1)
# Pin I2  = Row 2 (Decimal keypad Row 2)
# Pin I3  = Row 2 (Decimal keypad Row 3)

# Pin I4  = Reserved
# Pin I5  = Reserved
# Pin I6  = Reserved
# Pin I7  = Reserved

# *** Guzunty Pi 28BYJ48 Unipolar Stepping Motor Functions ********************

def WindingHex(windingTuple):
    windingHex0 = 0x01 << (windingTuple[0] - 1)
    windingHex1 = 0x01 << (windingTuple[1] - 1)
    windingHex = windingHex0 | windingHex1
    return windingHex

def TestGuzuntyPiSteppingMotor(windingTuple0, windingTuple1, stepCount, stepTime):
    PrintDoubleSpaceLine("*** Start testing Guzunty Pi Stepping Motor ***")  
    windingHex0 = WindingHex(windingTuple0)
    windingHex1 = WindingHex(windingTuple1)
    guzuntypiSpi = spidev.SpiDev()
    guzuntypiSpi.open(0, 0)
    Beep(4)
    for i in range(stepCount):
        guzuntypiSpi.xfer2([windingHex0, 0x00])
        time.sleep(stepTime)
        guzuntypiSpi.xfer2([windingHex1, 0x00])
        time.sleep(stepTime)
    guzuntypiSpi.close()
    PrintDoubleSpaceLine("*** Stop testing GuzuntyPi ***")


# *** Guzunty Pi Decimal Keypad Fuctions **************************************

AllColumnLowTuple   = (0b01110000, 0b00000000)
Column0LowTuple     = (0b00010000, 0b00000000)
Column1LowTuple     = (0b00100000, 0b00000000)
Column2LowTuple     = (0b01000000, 0b00000000)
ColumnLowTupleTuple = (Column0LowTuple, Column1LowTuple, Column2LowTuple)

def LoopUntilKeypadRowDataNibbleChangeGuzuntyPi(spi, allColumnLowTuple):
    NoKeyPressedNibble = 0x0f    
    rowDataNibble = NoKeyPressedNibble
    while (rowDataNibble == NoKeyPressedNibble):
        rowDataNibble = GetKeypadRowDataNibbleGuzuntyPi(spi, allColumnLowTuple)            
    time.sleep(0.05) # debouncing time 50mS

def GetKeypadRowDataNibbleGuzuntyPi(spi, twoByteTuple):
    twoByteList = [twoByteTuple[0], twoByteTuple[1]]
    rowDataByteList = spi.xfer2(twoByteList)
    rowDataNibble = 0x0f & (rowDataByteList[0])
    return rowDataNibble

def GetKeypadColumnNumberGuzuntyPi(spi):
    NoKeyPressRowDataNibble = 0b1111  
    for i in range(3):
        rowDataNibble = GetKeypadRowDataNibbleGuzuntyPi(spi, ColumnLowTupleTuple[i])
        if rowDataNibble != NoKeyPressRowDataNibble:
   break
    columnNumber = i
    print "Column number = ", columnNumber
    return columnNumber

def GetKeypadRowNumberGuzuntyPi(spi):
    rowDataNibble = GetKeypadRowDataNibbleGuzuntyPi(spi, AllColumnLowTuple)
    DataNibbleTuple = (0b00001110, 0b00001101, 0b00001011, 0b00000111)
    for dataNibble in (DataNibbleTuple):
        if (dataNibble == rowDataNibble):
            break
    rowNumber = DataNibbleTuple.index(dataNibble)
    # PrintFourBitPattern("Row data nibble = ", rowDataNibble)
    print "Row number = ", rowNumber
    return rowNumber

def GetKeyNumberGuzuntyPi(rowNumber, columnNumber):
    keyNumber = (rowNumber * 3) + (columnNumber + 1)
    print "Key number = ", keyNumber
    return keyNumber

def TestKeypadGuzuntyPi():

    # *** setup GuzuntyPi ***
    spiGuzuntyPi = spidev.SpiDev()
    spiGuzuntyPi.open(0, 0)

    keyNumber = 99
    while (keyNumber != 12):
        print "\nPress any key between 0 and 9.  Press # to exit, ...\n"
        LoopUntilKeypadRowDataNibbleChangeGuzuntyPi(spiGuzuntyPi, AllColumnLowTuple)
        columnNumber = GetKeypadColumnNumberGuzuntyPi(spiGuzuntyPi)
        rowNumber = GetKeypadRowNumberGuzuntyPi(spiGuzuntyPi)
        keyNumber = GetKeyNumberGuzuntyPi(rowNumber, columnNumber)
time.sleep(0.5)
 
    # *** End of keypad test ***
    spiGuzuntyPi.close()


# LCD1602 software initialization procedure

# Part A - Pseudo 8 bit instructions to config 4 bit instruction mode (0x30, 0x30, 0x30, 0x20)

# 1. Power on, wait 20mS (> 15mS)
# 2. Write 0x3, wait 5mS (> 4.1mS) # set 8 bit interface
# 3. Write 0x3, wait 1mS (> 100uS) # set 8 bit interface
# 4. Write 0x3, wait 1mS (> 37uS)  # set 8 bit interface
# 5. Write 0x2, wait 1mS (> 37uS)  # set 4 bit interface

# Part B - 4 bit instructions to config display characteristics (0x28, 0x08, 0x01, 0x06, 0x02)

# 6. Write 0x2, wait 1mS (> 37uS) 0x8 wait 1mS (> 37uS) (2 lines, 5x8 dot)
# 7. Write 0x0, wait 1mS (> 37uS) 0x8 wait 1mS (> 37uS) (cursor on, no blinking, blank screen)
# 8. Write 0x0, wait 1mS (> 37uS) 0x1 wait 2mS (> 1.52mS)(clear display)
# 9. Write 0x0, wait 1mS (> 37uS) 0xe (DisplayOnCursorOnCursorBlinkOff)
# a. Write 0x0, wait 1mS (> 37uS) 0x2 wait 2mS (cursor home)

# RegisterSelect = 0 # 0 = instruction register, 1 = data register
# WriteEnable = 1 # 1 = enable, 0 = disable
# DataBit4 = 2
# DataBit5 = 3
# DataBit6 = 4
# DataBit7 = 5

# AllZeroDataByte = 0x00
# AllOneDataByte = 0xff

# EnableWriteMask  = 0x02 # 0b 0000 0010
# DisableWriteMask = 0xfd # 0b 1111 1101

# SelectDataRegisterMask        = 0x01 # 0b 0000 0001
# SelectInstructionRegisterMask = 0xfe # 0b 1111 1110

# InstructionRegister = 0
# DataRegister = 1

# EightBitInstructionMode = 0x3
# FourBitInstructionMode  = 0x2

# TwoLineFiveTimesEightDot1 = 0x2
# TwoLineFiveTimesEightDot2 = 0x8

# DisplayOnCursorOnCursorBlinkOff1 = 0x0
# DisplayOnCursorOnCursorBlinkOff2 = 0xe

# ClearDisplay1 = 0x0
# ClearDisplay2 = 0x1

# CursorIncrementDisplayNoShift1 = 0x0
# CursorIncrementDisplayNoShift2 = 0x6

# CursorHome1 = 0x0
# CursorHome2 = 0x2

# PowerOnResetDelay      = 0.05    # 50mS
# VeryLongOperationDelay = 0.005   # 5mS
# LongOperationDelay     = 0.002   # 2mS
# ShortOperationDelay    = 0.00005 # 50uS
# WritePulseLength       = 0.00005 # 50uS

# * Guzunty Pi LCD1602 Functions **********************************************

def LcdConfigurationGuzuntyPi(spi):

    dataControlByte = 0x00
    LcdDisableWriteGuzuntyPi(spi, dataControlByte)
    time.sleep(PowerOnResetDelay)

    LcdWriteDataNibbleGuzuntyPi(spi, EightBitInstructionMode, InstructionRegister, VeryLongOperationDelay)
    LcdWriteDataNibbleGuzuntyPi(spi, EightBitInstructionMode, InstructionRegister, LongOperationDelay)
    LcdWriteDataNibbleGuzuntyPi(spi, EightBitInstructionMode, InstructionRegister, LongOperationDelay)
    LcdWriteDataNibbleGuzuntyPi(spi, FourBitInstructionMode, InstructionRegister, LongOperationDelay)

    LcdWriteDataNibbleGuzuntyPi(spi, TwoLineFiveTimesEightDot1, InstructionRegister, LongOperationDelay)
    LcdWriteDataNibbleGuzuntyPi(spi, TwoLineFiveTimesEightDot2, InstructionRegister, LongOperationDelay)
   
    LcdWriteDataNibbleGuzuntyPi(spi, DisplayOnCursorOnCursorBlinkOff1, InstructionRegister, LongOperationDelay)
    LcdWriteDataNibbleGuzuntyPi(spi, DisplayOnCursorOnCursorBlinkOff2, InstructionRegister, LongOperationDelay)
   
    LcdWriteDataNibbleGuzuntyPi(spi, ClearDisplay1, InstructionRegister, LongOperationDelay)
    LcdWriteDataNibbleGuzuntyPi(spi, ClearDisplay2, InstructionRegister, LongOperationDelay)
   
    LcdWriteDataNibbleGuzuntyPi(spi, CursorIncrementDisplayNoShift1, InstructionRegister, LongOperationDelay)
    LcdWriteDataNibbleGuzuntyPi(spi, CursorIncrementDisplayNoShift2, InstructionRegister, LongOperationDelay)
   
    LcdWriteDataNibbleGuzuntyPi(spi, CursorHome1, InstructionRegister, LongOperationDelay)
    LcdWriteDataNibbleGuzuntyPi(spi, CursorHome2, InstructionRegister, LongOperationDelay)

def LcdWriteDataControlByteGuzuntyPi(spi, dataControlByte):
    twoByteList = [0x00, dataControlByte]
    rowDataByteList = spi.xfer2(twoByteList)

def LcdDisableWriteGuzuntyPi(spi, dataControlByte):
    DisableWriteAndMask = 0xfd # 0b 1111 1101
    dataControlByte = dataControlByte & DisableWriteAndMask
    LcdWriteDataControlByteGuzuntyPi(spi, dataControlByte)

def LcdEnableWriteGuzuntyPi(spi, dataControlByte):
    EnableWriteOrMask = 0x02 # 0b 0000 0010
    dataControlByte = dataControlByte | EnableWriteOrMask
    LcdWriteDataControlByteGuzuntyPi(spi, dataControlByte)

def LcdWritePulseGuzuntyPi(spi, dataControlByte):
    LcdEnableWriteGuzuntyPi(spi, dataControlByte)
    time.sleep(WritePulseLength)
    LcdDisableWriteGuzuntyPi(spi, dataControlByte)

def LcdSelectInstructionRegisterGuzuntyPi(spi, dataControlByte):
    SelectInstructionRegisterAndMask = 0xfe # 0b 1111 1110
    dataControlByte = dataControlByte & SelectInstructionRegisterAndMask
    LcdWriteDataControlByteGuzuntyPi(spi, dataControlByte)

def LcdSelectDataRegisterGuzuntyPi(spi, dataControlByte):
    SelectDataRegisterOrMask = 0x01 # 0b 0000 0001
    dataControlByte = dataControlByte | SelectDataRegisterOrMask
    LcdWriteDataControlByteGuzuntyPi(spi, dataControlByte)

def LcdWriteDataNibbleGuzuntyPi(spi, dataNibbleByte, registerType, operationDelay):
    dataControlByte = dataNibbleByte << 2
    if (registerType == InstructionRegister):
       LcdSelectInstructionRegisterGuzuntyPi(spi, dataControlByte)
    #elif (registerType == DataRegister):
    else:
       LcdSelectDataRegisterGuzuntyPi(spi, dataControlByte)
       #print "dataControlByte = ", hex(dataControlByte)
       #pdb.set_trace()

    LcdDisableWriteGuzuntyPi(spi, dataControlByte)
    LcdWriteDataControlByteGuzuntyPi(spi, dataControlByte)
    LcdWritePulseGuzuntyPi(spi, dataControlByte) # perhaps include it in LcdWriteDataByteGuzuntyPi()
    time.sleep(operationDelay)

#def LcdWriteDataNibbleMcp23017(registerBaseAddress, dataByte, dataNibble, registerType, operationDelay):
#    dataNibble = dataNibble << 2
#    dataByte = dataByte & 0b11000011
#    dataByte = dataByte | dataNibble
#    if (registerType == InstructionRegister):
#       dataByte = LcdSelectInstructionRegisterMcp23017(registerBaseAddress, dataByte)
#    elif (registerType == DataRegister):
#       dataByte = LcdSelectDataRegisterMcp23017(registerBaseAddress, dataByte)
#    LcdDisableWriteMcp23017(registerBaseAddress, dataByte)
#    dataByte = LcdWriteDataByteMcp23017(registerBaseAddress, dataByte)
#    LcdWritePulseMcp23017(registerBaseAddress, dataByte)
#    time.sleep(operationDelay)
#    return dataByte

def LcdMoveCursorGuzuntyPi(spi, rowNumber, columnNumber):
    if (rowNumber == 1):
       cursorByte = 0x80 | (0x00 + (columnNumber - 1)) # command = 0x80, row 1 DDRAM start address = 0x10
    elif (rowNumber == 2):
       cursorByte = 0x80 | (0x40 + (columnNumber - 1)) # row 2 DDRAM start address = 0x40
    LcdWriteDataByteFourBitModeGuzuntyPi(spi, cursorByte, InstructionRegister)

def LcdWriteDataByteFourBitModeGuzuntyPi(spi, dataByte, registerType):
    upperNibble = dataByte >> 4
    lowerNibble = dataByte & 0x0f
    LcdWriteCharTwoNibblesGuzuntyPi(spi, upperNibble, lowerNibble, registerType)

def LcdWriteCharTwoNibblesGuzuntyPi(spi, upperNibble, lowerNibble, registerType):
    LcdWriteDataNibbleGuzuntyPi(spi, upperNibble, registerType, ShortOperationDelay)
    LcdWriteDataNibbleGuzuntyPi(spi, lowerNibble, registerType, ShortOperationDelay)

def LcdWriteCharStringGuzuntyPi(spi, string):
    for asciiChar in (string):
        LcdWriteCharFourBitModeGuzuntyPi(spi, asciiChar)

def LcdWriteCharFourBitModeGuzuntyPi(spi, asciiChar):
    charUpperNibble = ord(asciiChar) >> 4
    charLowerNibble = ord(asciiChar) & 0x0f
    LcdWriteCharTwoNibblesGuzuntyPi(spi, charUpperNibble, charLowerNibble, DataRegister)

def TestLcdGuzuntyPi():

    spiGuzuntyPi = spidev.SpiDev()
    spiGuzuntyPi.open(0, 0)    

    LcdConfigurationGuzuntyPi(spiGuzuntyPi)
   
    LcdMoveCursorGuzuntyPi(spiGuzuntyPi, 1, 1)
    #pdb.set_trace()

    #LcdMoveCursorGuzuntyPi(spiGuzuntyPi, 2, 1)
    #pdb.set_trace()

    #LcdWriteCharFourBitModeGuzuntyPi(spiGuzuntyPi, "A")
    #pdb.set_trace()

    #LcdWriteCharFourBitModeGuzuntyPi(spiGuzuntyPi, "A")
    #pdb.set_trace()

    #LcdWriteCharFourBitModeGuzuntyPi(spiGuzuntyPi, "A")
    #pdb.set_trace()

    LcdWriteCharStringGuzuntyPi(spiGuzuntyPi, ProgramTitle1)

    spiGuzuntyPi.close()

# * Guzunty Pi 8p8i core PWM functions ****************************************

# * Robot Arm Functions *

# * Set 1 Robot Arm pwm duty cycle
def SetPwmDutyCycle0(spiChannel, stateVector, index):
     spiChannel.xfer2([index, stateVector[index]])
   
# * Set all Robot Arm pwm duty cycles
def SetRobotArmPwmDutyCycle(spiChannel, robotArmStateVector):
    for i in range(len(robotArmStateVector)):
SetPwmDutyCycle0(spiChannel, robotArmStateVector, i)

# * Robot Neck Functions *

# * Set 1 Robot Neck pwm duty cycle
def SetPwmDutyCycle4(spiChannel, stateVector, index):
     spiChannel.xfer2([index + 4, stateVector[index]]) # *** Robot Neck PWM start at 4
   
# * Set all Robot Neck pwm duty cycles
def SetRobotNeckPwmDutyCycle(spiChannel, robotNeckStateVector):
    for i in range(len(robotNeckStateVector)):
SetPwmDutyCycle4(spiChannel, robotNeckStateVector, i)

# * Move servo *
def MoveServo(spiChannel, PwmNumber, PwmDutyCycle):
    spiChannel.xfer2([PwmNumber, PwmDutyCycle])
   
# *****************************************************************************
# *****************************************************************************
# *****************************************************************************
# *****************************************************************************
# *****************************************************************************
# * Test reset, all left most, right most, middle, shoulder only *

def TestGuzuntyPiRobotArm():

    PrintDoubleSpaceLine("*** Start testing Guzunty Pi Robot Arm ***")  

    # Open SPI Channel 0,0 for Guzunty Pi
    spiGuzuntyPi = spidev.SpiDev()
    # spiGuzuntyPi.open(0, 0)
    spiGuzuntyPi.open(0, 1)

    # * PWM duty cycle calibration *
    # CwMax = 13 # for 14.4 KHz clock
    # CcwMax = 30

    CwMax = 6 # for 7.2 KHz clock
    CcwMax = 16
    RightMost = CwMax
    LeftMost = CcwMax
    Middle = (RightMost + LeftMost) / 2

    OpenFully = RightMost
    CloseFully = LeftMost
    OpenHalf = Middle

    UpMost = RightMost
    DownMost = LeftMost

    # * Robot arm parts numbering *
    Shoulder = 0
    Elbow = 1
    Wrist = 2
    Hand = 3

    # * Robot neck parts numbering *
    NeckLeftRight = 4
    NeckUpDown = 5

    # * Bobot head parts numbering *
    HeadEye = 6
    HeadEar = 7

    # * Robot arm state vector constants *
    RobotArmStateVectorReset        = [RightMost, Middle, RightMost, LeftMost]
    RobotArmStateVectorAllMiddle    = [Middle, Middle, Middle, Middle, Middle]
    RobotArmStateVectorAllRightMost = [RightMost, RightMost, RightMost, RightMost]
    RobotArmStateVectorAllLeftMost  = [LeftMost, LeftMost, LeftMost, LeftMost]

    # * Robot neck state vector constants *
    RobotNeckStateVectorReset              = [Middle, Middle]
    RobotNeckStateVectorAllMiddle          = [Middle, Middle]
    RobotNeckStateVectorAllRightMostUpMost = [RightMost, UpMost]
    RobotNeckStateVectorAllLeftMostDownMost = [LeftMost, DownMost]

    # *** Robot arm functions *************************************************

    # Robot arm state vector variable *
    robotArmStateVector = []

    # * Robot arm reset *
    robotArmStateVector = RobotArmStateVectorReset[:]
    SetRobotArmPwmDutyCycle(spiGuzuntyPi, robotArmStateVector)
    time.sleep(1)

    # * All servos left most *
    robotArmStateVector = RobotArmStateVectorAllLeftMost[:]
    SetRobotArmPwmDutyCycle(spiGuzuntyPi, robotArmStateVector)
    time.sleep(1)

    # * All servos right most *
    robotArmStateVector = RobotArmStateVectorAllRightMost[:]
    SetRobotArmPwmDutyCycle(spiGuzuntyPi, robotArmStateVector)
    time.sleep(1)

    # * All servos middle *
    robotArmStateVector = RobotArmStateVectorAllMiddle[:]
    SetRobotArmPwmDutyCycle(spiGuzuntyPi, robotArmStateVector)
    time.sleep(1)

    # * Robot arm reset *
    robotArmStateVector = RobotArmStateVectorReset[:]
    SetRobotArmPwmDutyCycle(spiGuzuntyPi, robotArmStateVector)
    time.sleep(1)

    # * Shoulder middle *  
    robotArmStateVector[Shoulder] = Middle
    SetPwmDutyCycle0(spiGuzuntyPi, robotArmStateVector, Shoulder)
    time.sleep(1)

    # * Shoulder right most *  
    robotArmStateVector[Shoulder] = RightMost
    SetPwmDutyCycle0(spiGuzuntyPi, robotArmStateVector, Shoulder)
    time.sleep(1)

    # * Shoulder left most *  
    robotArmStateVector[Shoulder] = LeftMost
    SetPwmDutyCycle0(spiGuzuntyPi, robotArmStateVector, Shoulder)
    time.sleep(1)

    # * Hand fully open *  
    robotArmStateVector[Hand] = OpenFully
    SetPwmDutyCycle0(spiGuzuntyPi, robotArmStateVector, Hand)
    time.sleep(1)

    # * Hand fully close *  
    robotArmStateVector[Hand] = CloseFully
    SetPwmDutyCycle0(spiGuzuntyPi, robotArmStateVector, Hand)
    time.sleep(1)

    # * Hand half open *  
    robotArmStateVector[Hand] = OpenHalf
    SetPwmDutyCycle0(spiGuzuntyPi, robotArmStateVector, Hand)
    time.sleep(1)

    # * Robot arm reset *
    robotArmStateVector = RobotArmStateVectorReset[:]
    SetRobotArmPwmDutyCycle(spiGuzuntyPi, robotArmStateVector)
    time.sleep(1)

    # *** Robot Neck Functions ************************************************

    # Robot neck state vector variable *
    robotNeckStateVector = []

    # * Robot neck reset *
    robotNeckStateVector = RobotNeckStateVectorReset[:]
    SetRobotNeckPwmDutyCycle(spiGuzuntyPi, robotNeckStateVector)
    time.sleep(1)

    # * All servos right most up most *
    robotNeckStateVector = RobotNeckStateVectorAllRightMostUpMost[:]
    SetRobotNeckPwmDutyCycle(spiGuzuntyPi, robotNeckStateVector)
    time.sleep(1)

    # * All servos left most down most *
    robotNeckStateVector = RobotNeckStateVectorAllLeftMostDownMost[:]
    SetRobotNeckPwmDutyCycle(spiGuzuntyPi, robotNeckStateVector)
    time.sleep(1)

    spiGuzuntyPi.close()

    PrintDoubleSpaceLine("*** Stop testing Guzunty Pi ***")

# *****************************************************************************

# * Test one servo *

def TestGuzuntyPiServo(testTime):

    PrintDoubleSpaceLine("*** Start testing Guzunty Pi Servo ***")  

    spiGuzuntyPi = spidev.SpiDev()
    spiGuzuntyPi.open(0, 1)

    for i in range(2, 32):
       print "Duty cycle = ", i
       MoveServo(spiGuzuntyPi, PwmNumber = 6, PwmDutyCycle = i)
       time.sleep(testTime)

    spiGuzuntyPi.close()

    PrintDoubleSpaceLine("*** Stop testing Guzunty Pi ***")

# *** 7-segment LED functions *********************************************

def TestSetGpClk0WiringPi1(frequency):
    io = wiringpi.GPIO(wiringpi.GPIO.WPI_MODE_PINS)

    # io.pinMode(7, io.OUTPUT)
    # io.digitalWrite(7, io.HIGH)

    io.pinMode(7, io.GPIO_CLOCK)  # not working !!!
    io.gpioClockSet (7, frequency) # not working !!!

def TestSetGpClk0WiringPi2(frequency):
    wiringpi2.wiringPiSetupSys
    wiringpi2.pinMode(7, 1)       # OK
    wiringpi2.digitalWrite(7, 1)  # OK

    # wiringpi2.pinMode(7, GPIO_CLOCK)     # not working !!!
    # wiringpi2.digitalWrite(7, frequency) # not working !!!

def TestSetGpClk0Subprocess(frequency):

    returnCode = call(["gpio mode 7 clock", "gpio clock 7 960000"], shell = True)
    time.sleep(4)
    returnCode = call("gpio clock 7 4800000", shell=True)
    time.sleep(4)  
    returnCode = call("gpio clock 7 2400000", shell=True)
    time.sleep(4)
    returnCode = call("gpio clock 7 15000", shell=True)
    time.sleep(4)

# *** Backup 2013apr17 ***
#def TestLedDriverCore():
#
#    # *** Set GPCLK0 pin to 4.68 KHz ***
#    returnCode = call(["gpio mode 7 clock"], shell = True)
#    returnCode = call("gpio clock 7 4688", shell=True)

#    # *** Setup SPI channel ***
#    spiGuzuntyPi = spidev.SpiDev()
#    spiGuzuntyPi.open(0, 0)

#    # *** Load 4 7-segment patterns to digit pattern list ***
#    SevenSegments0 = 0x3f
#    SevenSegments1 = 0x06
#    SevenSegments2 = 0x5b
#    SevenSegments3 = 0x4f
#    sevenSegmentsList = [SevenSegments0, SevenSegments1, SevenSegments2, SevenSegments3]

#    sevenSegmentsListAllHigh = [0xff, 0xff, 0xff, 0xff]
#    sevenSegmentsListAllLow  = [0x00, 0x00, 0x00, 0x00]

#    # *** Write digit pattern list to Guzunty Pi ***
#    for i in range(10):
#        spiGuzuntyPi.xfer2(sevenSegmentsListAllHigh)
#        time.sleep(1)
#        spiGuzuntyPi.xfer2(sevenSegmentsListAllLow)
#        time.sleep(1)

def SetRpiPin7GpClk0Frequency4688Hz():
    returnCode = call(["gpio mode 7 clock"], shell = True)
    returnCode = call("gpio clock 7 4688", shell=True)

def TestGuzuntyPiLedDriver01(spiChannel):

    SetRpiPin7GpClk0Frequency4688Hz()

    # *** 7 segment patterns ***
    #PatternDigit0     = ~0x3f
    #PatternDigit1     = ~0x06
    #PatternDigit2     = ~0x5b
    #PatternDigit3     = ~0x4f
    #PatternSpace      = 0xff
    #PatternAllOn      = 0x00

    PatternBigG       = 0x3d
    PatternSmallG     = 0x6f
    PatternSmallO     = 0x5c
    PatternSmallD     = 0x5e

    PatternDigit0     = 0x3f
    PatternDigit1     = 0x06
    PatternDigit2     = 0x5b
    PatternDigit3     = 0x4f
    PatternSpace      = ~0xff
    PatternAllOn      = ~0x00

    PatternBigG       = 0x3d
    PatternSmallG     = 0x6f
    PatternSmallO     = 0x5c
    PatternSmallD     = 0x5e

    PatternListAllOff = [PatternSpace, PatternSpace, PatternSpace, PatternSpace]
    PatternListAllOn  = [PatternAllOn, PatternAllOn, PatternAllOn, PatternAllOn]
    PatternList0123   = [PatternDigit0, PatternDigit1, PatternDigit2, PatternDigit3]
    PatternListGood   = [PatternBigG, PatternSmallO, PatternSmallO, PatternSmallD]    

    # *** time digits ***
    timeString =  time.asctime(time.localtime(time.time()))
    print timeString

    print "Hour   digit 1 = ", timeString[11:12]
    print "Hour   digit 2 = ", timeString[12:13]
    print "Minute digit 1 = ", timeString[14:15]
    print "Minute digit 2 = ", timeString[15:16]
    print "Second digit 1 = ", timeString[17:18]
    print "Second digit 2 = ", timeString[18:19]

    hourDoubleDigit = [timeString[11:12], timeString[12:13]]
    print "hourDoubleDigit 0 = ", hourDoubleDigit[0]
    print "hourDoubleDigit 1 = ", hourDoubleDigit[1]

    minuteDoubleDigit = [timeString[14:15], timeString[15:16]]
    print "minuteDoubleDigit 0 = ", minuteDoubleDigit[0]
    print "minuteDoubleDigit 1 = ", minuteDoubleDigit[1]

    secondDoubleDigit = [timeString[17:18], timeString[18:19]]
    print "secondDoubleDigit 0 = ", secondDoubleDigit[0]
    print "secondDoubleDigit 1 = ", secondDoubleDigit[1]

    timeHexDigit = [hourDoubleDigit, minuteDoubleDigit, secondDoubleDigit]
    print "hour = ", (timeHexDigit[0])[0], (timeHexDigit[0])[1]

    timeHexDigit = [minuteDoubleDigit, minuteDoubleDigit, secondDoubleDigit]
    print "minute = ", (timeHexDigit[0])[0], (timeHexDigit[0])[1]

    timeHexDigit = [secondDoubleDigit, minuteDoubleDigit, secondDoubleDigit]
    print "second = ", (timeHexDigit[0])[0], (timeHexDigit[0])[1]

    # *** 4 digit 7-segment LED displays ***  

#    spiGuzuntyPi.xfer2(PatternListAllOff)  
#    time.sleep(1)
#    spiGuzuntyPi.xfer2(PatternListAllOn)  
#    time.sleep(1)
#    spiGuzuntyPi.xfer2(PatternList0123)  
#    time.sleep(2)
#    spiGuzuntyPi.xfer2(PatternListGood)  
#    time.sleep(2)

    SpiWrite(spiChannel, PatternListAllOff)
    time.sleep(1)

    SpiWrite(spiChannel, PatternListAllOn)  
    time.sleep(1)

    SpiWrite(spiChannel, PatternList0123)  
    time.sleep(2)

    SpiWrite(spiChannel, PatternListGood)  
    time.sleep(2)

    # SevenSegmentPatternNumbers = [~0x3f, ~0x06, ~0x5b, ~0x4f, ~0x66, ~0x6d, ~0x7d, ~0x07, ~0x7f, ~0x6f]
    SevenSegmentPatternNumbers = [0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f]
   
    decimalPoint = 0

    for i in range(2):
        timeString =  time.asctime(time.localtime(time.time()))

        hourDoubleDigit = [timeString[11:12], timeString[12:13]]
        minuteDoubleDigit = [timeString[14:15], timeString[15:16]]
secondDoubleDigit = [timeString[17:18], timeString[18:19]]

        minuteDigit0 = SevenSegmentPatternNumbers[int(minuteDoubleDigit[0])]
        minuteDigit1 = SevenSegmentPatternNumbers[int(minuteDoubleDigit[1])]
        secondDigit0 = SevenSegmentPatternNumbers[int(secondDoubleDigit[0])]
        secondDigit1 = SevenSegmentPatternNumbers[int(secondDoubleDigit[1])]

        if (decimalPoint == 0):
   #minuteDigit1 &= ~0x80
   minuteDigit1 |= 0x80
   decimalPoint = 1
        else:
            decimalPoint = 0

        minuteSecondQuadDigitList = [minuteDigit0, minuteDigit1, secondDigit0, secondDigit1]      
SpiWrite(spiChannel, minuteSecondQuadDigitList)          
time.sleep(1)


def TestGuzuntyPiLedDriver00(spiChannel, channelNumber, chipEnableNumber):

    SetRpiPin7GpClk0Frequency4688Hz()
   
    spiGuzuntyPi = spidev.SpiDev()
    spiGuzuntyPi.open(0, 1)

    # *** 7 segment patterns ***
    #PatternDigit0     = ~0x3f
    #PatternDigit1     = ~0x06
    #PatternDigit2     = ~0x5b
    #PatternDigit3     = ~0x4f
    #PatternSpace      = 0xff
    #PatternAllOn      = 0x00

    PatternBigG       = 0x3d
    PatternSmallG     = 0x6f
    PatternSmallO     = 0x5c
    PatternSmallD     = 0x5e

    PatternDigit0     = 0x3f
    PatternDigit1     = 0x06
    PatternDigit2     = 0x5b
    PatternDigit3     = 0x4f
    PatternSpace      = ~0xff
    PatternAllOn      = ~0x00

    PatternBigG       = 0x3d
    PatternSmallG     = 0x6f
    PatternSmallO     = 0x5c
    PatternSmallD     = 0x5e

    PatternListAllOff = [PatternSpace, PatternSpace, PatternSpace, PatternSpace]
    PatternListAllOn  = [PatternAllOn, PatternAllOn, PatternAllOn, PatternAllOn]
    PatternList0123   = [PatternDigit0, PatternDigit1, PatternDigit2, PatternDigit3]
    PatternListGood   = [PatternBigG, PatternSmallO, PatternSmallO, PatternSmallD]    

    # *** time digits ***
    timeString =  time.asctime(time.localtime(time.time()))
    print timeString

    print "Hour   digit 1 = ", timeString[11:12]
    print "Hour   digit 2 = ", timeString[12:13]
    print "Minute digit 1 = ", timeString[14:15]
    print "Minute digit 2 = ", timeString[15:16]
    print "Second digit 1 = ", timeString[17:18]
    print "Second digit 2 = ", timeString[18:19]

    hourDoubleDigit = [timeString[11:12], timeString[12:13]]
    print "hourDoubleDigit 0 = ", hourDoubleDigit[0]
    print "hourDoubleDigit 1 = ", hourDoubleDigit[1]

    minuteDoubleDigit = [timeString[14:15], timeString[15:16]]
    print "minuteDoubleDigit 0 = ", minuteDoubleDigit[0]
    print "minuteDoubleDigit 1 = ", minuteDoubleDigit[1]

    secondDoubleDigit = [timeString[17:18], timeString[18:19]]
    print "secondDoubleDigit 0 = ", secondDoubleDigit[0]
    print "secondDoubleDigit 1 = ", secondDoubleDigit[1]

    timeHexDigit = [hourDoubleDigit, minuteDoubleDigit, secondDoubleDigit]
    print "hour = ", (timeHexDigit[0])[0], (timeHexDigit[0])[1]

    timeHexDigit = [minuteDoubleDigit, minuteDoubleDigit, secondDoubleDigit]
    print "minute = ", (timeHexDigit[0])[0], (timeHexDigit[0])[1]

    timeHexDigit = [secondDoubleDigit, minuteDoubleDigit, secondDoubleDigit]
    print "second = ", (timeHexDigit[0])[0], (timeHexDigit[0])[1]

    # *** 4 digit 7-segment LED displays ***  

    spiGuzuntyPi.xfer2(PatternListAllOff)  
    time.sleep(1)

    spiGuzuntyPi.xfer2(PatternListAllOn)  
    time.sleep(1)

    spiGuzuntyPi.xfer2(PatternList0123)  
    time.sleep(2)

    spiGuzuntyPi.xfer2(PatternListGood)  
    time.sleep(2)

    # SevenSegmentPatternNumbers = [~0x3f, ~0x06, ~0x5b, ~0x4f, ~0x66, ~0x6d, ~0x7d, ~0x07, ~0x7f, ~0x6f]
    SevenSegmentPatternNumbers = [0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f]
   
    decimalPoint = 0

    for i in range(2):
        timeString =  time.asctime(time.localtime(time.time()))

        hourDoubleDigit = [timeString[11:12], timeString[12:13]]
        minuteDoubleDigit = [timeString[14:15], timeString[15:16]]
secondDoubleDigit = [timeString[17:18], timeString[18:19]]

        minuteDigit0 = SevenSegmentPatternNumbers[int(minuteDoubleDigit[0])]
        minuteDigit1 = SevenSegmentPatternNumbers[int(minuteDoubleDigit[1])]
        secondDigit0 = SevenSegmentPatternNumbers[int(secondDoubleDigit[0])]
        secondDigit1 = SevenSegmentPatternNumbers[int(secondDoubleDigit[1])]

        if (decimalPoint == 0):
   #minuteDigit1 &= ~0x80
   minuteDigit1 |= 0x80
   decimalPoint = 1
        else:
            decimalPoint = 0

        minuteSecondQuadDigitList = [minuteDigit0, minuteDigit1, secondDigit0, secondDigit1]
       
spiGuzuntyPi.xfer2(minuteSecondQuadDigitList)  
       
time.sleep(1)

.END

No comments:

Post a Comment