I wanted to build an analogue display for a digital compass so decided to use a stepper motor for the pointer. I couldn't find any code to directly set a stepper position so wrote the attached. Hope it will save someone a few minutes
Best regards
Peter
Best regards
Peter
Code:
#picaxe 18X
setfreq m4
'
' Demo program to demonstrate driving a stepper motor to a specific position
' in the shortest direction
'
symbol current=w0
symbol last=w1
symbol move=w2
symbol steppos=b6
symbol steppulse=b7
symbol direction=b8
symbol stepcount=800 ' 1/2 steps per revolution for stepper used
symbol half=stepcount/2
symbol clockwise=0
symbol anticlockwise=1
'
last=0
current=0
gosub position
pause 5000
'
' ideally there should be some mechanism of setting the motor to a known position
' a opto switch would be ideal running the stepper in a specific direction until the switch activates and input
'
'
do
random current
current=current//stepcount 'pick a position to move to
gosub position
debug
pause 1000
loop
position:
if current=last then : return :endif'nothing to do
if last>current then
move=last-current
if move<half then ' havent gone forwards through zero
direction = anticlockwise
else
direction = clockwise
move=stepcount-move
endif
else
move=current-last
if move<half then ' havent gone backwards through zero
direction = clockwise
else
direction = anticlockwise
move=stepcount-move
endif
endif
steppos=last//8 'get the current position in the stepper sequence
do
dec move
if direction=clockwise then
inc steppos
else
dec steppos
endif
steppos=steppos & %00000111
LOOKUP steppos, (%1010, %1000, %1001, %0001, %0101, %0100, %0110, %0010), steppulse
pins = steppulse*16
pause 2
loop until move=0
last=current
return