-
Notifications
You must be signed in to change notification settings - Fork 2
/
stepperMotor.ino
95 lines (72 loc) · 2.09 KB
/
stepperMotor.ino
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
============================================================================
Name : chStepperDriver.ino
Author : ChrisMicro
Version :
Copyright : GPL license 3
Date : June 2015
Description : Stepper motor driver with acceleration and deceleration using
the DDS principle.
============================================================================
/*
Stepper motor driver with acceleration and deceleration.
The timing is created with the DDS principle ( fractional accumulator ).
Acceleration an decelaration is done with a state machine.
Hardware
MC: Arduino Uno/Nano/Due
Motor Driver: Polulu A4988
*/
#define DIRECTION_PIN 12
#define STEPPER_PULSE_PIN 13
uint8_t Direction=0;
void setup() {
pinMode( DIRECTION_PIN, OUTPUT );
pinMode( STEPPER_PULSE_PIN, OUTPUT );
digitalWrite(DIRECTION_PIN,Direction);
}
#define MICROSTEPS 16
int32_t SpeedNow = 0;
int32_t TargetSpeed = 2000 * 65536*MICROSTEPS;
uint16_t Acceleration = 4000 * MICROSTEPS;
uint16_t DDS_Accumulator = 0;
#define HOLDSPEED_STEPS 20000
#define STATE_ACCELERATE 0
#define STATE_HOLDSPEED 1
#define STATE_DECELERATE 2
uint8_t state = STATE_ACCELERATE; // initial state
uint32_t HoldSpeed_Counter = 0;
void loop() {
DDS_Accumulator+=(SpeedNow>>16);
digitalWrite(STEPPER_PULSE_PIN,DDS_Accumulator>>15);
delayMicroseconds(10);
switch(state)
{
case STATE_ACCELERATE:{
SpeedNow+=Acceleration;
if(SpeedNow>TargetSpeed){
state=STATE_HOLDSPEED;
HoldSpeed_Counter=0;
}
}break;
case STATE_HOLDSPEED:{
HoldSpeed_Counter++;
if(HoldSpeed_Counter>HOLDSPEED_STEPS)
{
state=STATE_DECELERATE;
}
}break;
case STATE_DECELERATE:{
SpeedNow-=Acceleration;
if(SpeedNow<0)
{
SpeedNow=0;
state=STATE_ACCELERATE;
Direction^=1; // reverse direction
digitalWrite(DIRECTION_PIN,Direction);
}
}break;
default:{
state=STATE_ACCELERATE;
}
}
}