Hello!
Some remarks about your code:
1. You have a bunch of #defines in a function. That's not the way to do it. #defines should be on top
because they are preprocessor directives, not code.
2. Better than a for loop to make a delay, you should use a timer.
The timer interrupt routine is called at regular intervals, and then in your interrupt service routine,
you can step forwards or backwards.
3. Your stepper functions (forl and backl) make 4 steps at a time. This means that if you buy
a 400 steps / rev motor, you will end up with 100 steps per / rev only.
What about this (without timer):
Code C - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| #define BACKWARDS 0
#define DELAY 150
uint8 sequence[4] = {0x08, 0x02, 0x04, 0x01};
#define COUNT 1000
void main(void) {
uint8 current_step = 0;
uint16 i;
initialize();
// Spin forwards
while(i < COUNT) {
PORTB = sequence[current_step];
current_step++;
if(current_step > 3) current_step = 0;
delay(DELAY);
}
// Spin backwards
while(i < COUNT) {
PORTB = sequence[current_step];
current_step--;
if(current_step > 3) current_step = 3; // (see (1))
delay(DELAY);
}
} |
(1) Note that this is not a mistake: If you do current_step-- on 0, then you will get 255, and therefore
current_step will be back to 3.
Now if you use a timer interrupt, it's even simpler: you set up an interrupt so that the function timer_isr
will be called.
You should therefore declare current_step as static or global, then:
Code C - [expand] |
1
2
3
4
5
| void timer_isr(void) {
current_step += step; // step is +1 or -1, depending on the direction
if(current_step ==4) current_step = 0;
if(current_step ==255) current_step = 3;
} |
Note that in this case you don't need a delay because the function is called by a timer.
Dora.