-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
137 lines (110 loc) · 2.43 KB
/
main.cpp
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include "gpio.h"
using namespace io;
extern "C" {
#include <util/delay.h>
}
class Motor {
public:
Motor(gpio& pul, gpio& dir, gpio& ena)
: pul(pul)
, dir(dir)
, ena(ena)
{
pul.clear();
dir.clear();
}
void cw() {
dir.clear();
}
void ccw() {
dir.set();
}
void enable() {
ena.clear();
}
void disable() {
ena.set();
}
void step() {
pul.set();
_delay_us(10);
pul.clear();
}
protected:
gpio &pul, &dir, &ena;
};
class Control {
public:
Control(Motor &motor, uint16_t min_sps=250, uint16_t max_sps=4000, uint16_t ramp_angle=4)
: motor(motor)
, min_sps(min_sps)
, max_sps(max_sps)
, ramp_angle(ramp_angle)
{}
void move(int32_t input, uint16_t speed=0) {
uint32_t sps = min_sps;
uint32_t step = 0;
uint32_t steps;
if (input == 0) {
return;
} else if (input < 0) {
motor.ccw();
steps = input * -1;
} else {
steps = input;
motor.cw();
}
if (speed == 0) {
speed = max_sps;
}
uint32_t ramp = (speed - min_sps) / ramp_angle;
while (step < steps) {
motor.step();
wait10us(100000 / sps);
if (step <= (steps / 2) && step < ramp) {
sps += ramp_angle;
}
if (step > (steps / 2) && (steps - step) < ramp) {
sps -= ramp_angle;
}
step++;
}
}
protected:
void wait10us(uint32_t us) {
while(us--) {
_delay_us(10);
}
}
protected:
Motor &motor;
uint16_t min_sps;
uint16_t max_sps;
uint16_t ramp_angle;
};
void idle(Motor &motor, gpio& led) {
_delay_ms(250);
motor.disable();
led.clear();
_delay_ms(2000);
led.set();
motor.enable();
_delay_ms(250);
}
int main() {
gpio ena(gpio::portd, gpio::pin2, gpio::out);
gpio dir(gpio::portd, gpio::pin4, gpio::out);
gpio pul(gpio::portd, gpio::pin6, gpio::out);
gpio led(gpio::portb, gpio::pin5, gpio::out);
led.set();
Motor motor(pul, dir, ena);
motor.enable();
Control control(motor);
while (true) {
control.move(8000, 6000);
idle(motor, led);
control.move(-8000, 6000);
idle(motor, led);
}
return 0;
}