Project

General

Profile

Statistics
| Branch: | Revision:

root / scout_avr / src / stepper.cpp @ 958699af

History | View | Annotate | Download (1.79 KB)

1 a07a0b55 Julian Binder
extern "C"
2
{
3
#include <avr/io.h>
4 85dff67b Julian Binder
#include <util/delay.h>
5 a07a0b55 Julian Binder
}
6
#include "stepper.h"
7
8
/*  Stepper Motor:
9
 *  Provides interface to stepper motor.
10
 *  Can set direction. Outputs pulse to stepper upon call of step func
11
 *  Also provides variable speed sweep
12
 */
13
14
struct step_t {
15
  int pos; // position in rotation.
16
  int dir; // direction. -1 CCW. 1 CW. 0 OFF
17 2853d46b Tom Mullins
  int step_size; // amount to add to position each step
18 a07a0b55 Julian Binder
  int ccw;
19
  int cw;
20 2853d46b Tom Mullins
} step;
21 a07a0b55 Julian Binder
22
23 2853d46b Tom Mullins
void step_init()
24 a07a0b55 Julian Binder
{
25 2853d46b Tom Mullins
  /* init pos and dir to 0 */
26 a07a0b55 Julian Binder
  step.pos = 0;
27 85dff67b Julian Binder
  step.dir = 0;
28 a07a0b55 Julian Binder
29
  //set control pins as output
30
  DDRD |= ((1<<S_STEP) | (1<<S_DIR));
31
  DDRB |= ((1<<S_MS));
32
33
  //initiate to full steps
34 2853d46b Tom Mullins
  step_set_size(STEP_WHOLE);
35 a07a0b55 Julian Binder
 
36
  //initiate the step pin to be low. stepper steps on low to high
37
  PORTD &= (~(1<<S_STEP));
38 2853d46b Tom Mullins
}
39 a07a0b55 Julian Binder
40 2853d46b Tom Mullins
void step_set_size(char size)
41
{
42
  if (size == STEP_WHOLE)
43
  {
44
    PORTB &= ~_BV(S_MS);
45
    step.step_size = 2;
46
  }
47
  else
48
  {
49
    PORTB |= _BV(S_MS);
50
    step.step_size = 1;
51
  }
52 a07a0b55 Julian Binder
}
53
54
/* set direction pin */
55
void step_dir(int dir)
56
{
57
  step.dir = dir;
58
  switch(dir)
59
  {
60
    case 1:
61 2853d46b Tom Mullins
      PORTD |= (1<<S_DIR);
62 a07a0b55 Julian Binder
      break;
63
    case -1:
64 2853d46b Tom Mullins
      PORTD &= (~(1<<S_DIR));
65 a07a0b55 Julian Binder
      break;
66
  }
67
}
68
69 2853d46b Tom Mullins
void step_do_step()
70 a07a0b55 Julian Binder
{
71 85dff67b Julian Binder
  if(step.dir==0) return; //do not step if not enabled
72 a07a0b55 Julian Binder
  PORTD |= (1<<S_STEP); //step once 
73 85dff67b Julian Binder
  _delay_us(1); //conform with step timing
74 a07a0b55 Julian Binder
  PORTD &= (~(1<<S_STEP)); //bring the step bin back down
75 2853d46b Tom Mullins
  if(step.dir==1) step.pos += step.step_size;
76
  else step.pos -= step.step_size;
77 a07a0b55 Julian Binder
}
78
79
void step_flush()
80
{
81
  PORTD &= (~(1<<S_STEP)); //bring the step bin back down
82
}
83
84
//ccw must be less than 0 and cw must be greater than 0
85
void step_sweep_bounds(int ccw, int cw)
86
{
87
  step.ccw = ccw;
88
  step.cw = cw;
89
}
90
91
void step_sweep()
92
{
93 2853d46b Tom Mullins
  step_do_step();
94
  if((step.dir == 1) && (step.cw <= step.pos)) step_dir(-1);
95
  else if((step.dir == -1) && (step.ccw >= step.pos)) step_dir(1);
96 a07a0b55 Julian Binder
}