BasicX, Controling a Unipolar Stepping Motor


' Program Stepper_1.BAS
'
' Turns Unipolar Stepper in one direction in half step mode.
'
' This is a not a terribly functional routine and other sample routines
' wil be developed to illustrate operating a stepper in both directions,
' at varying speeds and in either the ha;f step or full step mode.
'
' The routine illustrates how to pass an array to a function.
'
' In outputting the pattern, I happened to use a bit approach.  The state
' of each of the the four bits is isolated using GetBit and output.
'
' It would be easier to do a RAMPoke, but I was interested in fooling
' with the individual bit appraoch.
'
'
' Copyright, Peter H. Anderson, Baltimore, MD, Sept, '99


Public Const PH0 as byte = 36	' connect to ULN2803 or similar
Public Const PH1 as byte = 37	' to control stepper
Public Const PH2 as byte = 38
Public Const PH3 as byte = 39
 
Sub Main()

   Dim Patts(1 to 8) as Byte

   Call OpenSerialPort(2, 9600)		' For debugging

   Patts(1) = &H01	' define stepping motor patts
   Patts(2) = &H03
   Patts(3) = &H02
   Patts(4) = &H06
   Patts(5) = &H04
   Patts(6) = &H0c
   Patts(7) = &H08
   Patts(8) = &H09

   Call Turn_Motor(Patts, 10000) ' pass the array of patterns
				 ' and the number of half steps to 
				 ' travel
                                     
End Sub

Sub Turn_Motor(ByRef Patts() as Byte, ByVal steps as Integer)

   Dim N as Integer
   Dim Y as Byte
   
   Do
   If (steps >= 0) Then
      For N = 1 To 8	' output each pattern in turn
        Y = Patts(N)
 '      Call PutI(N)	' for debugging
 '      Call PutByte(32)
 '      Call PutB(Y)
 '      Call NewLine()
        Call OutPatt(Y)
'       Call Sleep(1.0)
        steps = steps-1
      Next 
   End If
   Loop
End Sub

Sub OutPatt(ByVal Patt as Byte)
    
    Dim bit as Byte

    bit = GetBit(Patt, 0)	' isolate bit 0 of Patt and output
'   Call PutB(bit)
    Call PutPin(PH0, bit)
    
    
    bit = GetBit(Patt, 1)	' isolate bit 1 of Patt and output
'   Call PutB(bit)
    Call PutPin(PH1, bit)
     
    
    bit = GetBit(Patt, 2)	' similar
'   Call PutB(bit)
    Call PutPin(PH2, bit)
     
    bit = GetBit(Patt, 3)	' similar
'   Call PutB(bit)
    Call PutPin(PH3, bit)

'   Call NewLine()        
End Sub    

Function GetBit(ByVal val as Byte, ByVal bit_num as Byte) as Byte
' return the nth (bit_num) of val as either a 1 or 0
    Dim N as Byte
    Dim K as Byte 
    
    K = 1
    If (bit_num = 0) then
       K = 1	
    Else 
       For N=1 TO bit_num	' generate 2, 4, 8 etc as appropriate
          K = K * 2
       Next
    End If
    																	'Call NewLine()
    'Call PutB(K)
    'Call NewLine()
    GetBit = (val \ K) AND &H01	' shift and isolate the least sig bit
    
End Function