-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathA4988_DC.h
96 lines (79 loc) · 2.34 KB
/
A4988_DC.h
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
/*
* DC MOTOR CLASS FOR A4988 DRIVER
* Based on: http://www.robotshop.com/letsmakerobots/files/A4988RobotV2.txt
* Created By Pablo Luaces <[email protected]>
*
* ¿How to use?
*
* 1 - Declare Motor type var after setup() [Motor* myMotor]
* 2 - Instantiate new Motor in var created before [myMotor = new Motor()]
* 3 - Use predefined public methods [myMotor->method()]
*
* Public Methods
*
* setPins((int) step, (int) enable, (int) reset)
* setDirection((bool) direction) [0 Forward, 1 Reverse]
* setSpeed((int) speed) [Min 0, Max 255]
* toggleDirection()
* run()
* stop()
*
*/
class Motor{
private:
uint8_t _stPin, _enPin, _rstPin; // Wiring
int _pwmSpeed = 255; // 0~255
bool _turnDirection = 0; // 0 Forward, 1 Reverse
void _setPins(){
pinMode(this->_stPin, OUTPUT);
pinMode(this->_rstPin, OUTPUT);
pinMode(this->_enPin, OUTPUT);
digitalWrite(this->_rstPin, HIGH); // Active low
digitalWrite(this->_enPin, HIGH); // Active low
}
void _motorDirection(){
unsigned int pulseModulation = (this->_turnDirection)? 2:0;
digitalWrite(this->_rstPin, LOW);
delayMicroseconds(5);
digitalWrite(this->_rstPin, HIGH);
for(int i=0;i<pulseModulation;i++){
digitalWrite(this->_stPin, HIGH);
delayMicroseconds(800);
digitalWrite(this->_stPin, LOW);
delayMicroseconds(800);
}
}
void _motorSpeed(){
analogWrite(this->_enPin, this->_pwmSpeed);
}
void _motorStop(){
digitalWrite(this->_enPin, HIGH);
}
public:
void setPins(uint8_t stPin, uint8_t enPin, uint8_t rstPin){
this->_stPin = stPin;
this->_rstPin = rstPin;
this->_enPin = enPin;
this->_setPins();
}
void setDirection(bool turnDirection){ // 0 Forward, 1 Reverse
this->_turnDirection = turnDirection;
this->_motorDirection();
}
void setSpeed(int pwmSpeed){ // 0~255
this->_pwmSpeed = (255 - pwmSpeed);
this->_motorSpeed();
}
void toggleDirection(){
if (this->_turnDirection) this->_turnDirection = 0; // Forward
else this->_turnDirection = 1; // Reverse
this->_motorDirection();
}
void run(){
this->_motorDirection();
this->_motorSpeed();
}
void stop(){
this->_motorStop();
}
};