-
Notifications
You must be signed in to change notification settings - Fork 0
/
L289N.cpp
80 lines (70 loc) · 1.17 KB
/
L289N.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
#include "L289N.h"
#ifdef ESP32
#include "analogWrite.h"
#endif // ESP32
L289N::L289N(int _dir1, int _dir2, int _pwm, bool _invert)
{
dir1 = _dir1;
dir2 = _dir2;
pwm = _pwm ;
invert = _invert;
if (!invert)
{
forwardDirection = 1;
backwardDirection = 0;
}
else
{
forwardDirection = 0;
backwardDirection = 1;
}
}
/**
* Initialize the controller pins.
*/
void L289N::init()
{
pinMode(dir1, OUTPUT);
pinMode(dir2, OUTPUT);
pinMode(pwm, OUTPUT);
}
void L289N::forwards()
{
digitalWrite(dir1, forwardDirection);
digitalWrite(dir2, backwardDirection);
}
void L289N::backwards()
{
digitalWrite(dir1, backwardDirection);
digitalWrite(dir2, forwardDirection);
}
void L289N::setSpeed(int speed)
{
analogWrite(pwm, constrain(speed, 0, 255));
}
void L289N::setSpeedDirection(int speed, bool softStart)
{
if (softStart && millis() > softStartPrevTime + softStartPeriod)
{
if (softStartSpeed < speed)
{
softStartSpeed++;
}
else if (softStartSpeed > speed)
{
softStartSpeed--;
}
speed = softStartSpeed;
softStartPrevTime = millis();
}
if (speed >= 0)
{
forwards();
setSpeed(speed);
}
else
{
backwards();
setSpeed(abs(speed));
}
}