-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDCMotor.cpp
More file actions
48 lines (36 loc) · 1.03 KB
/
Copy pathDCMotor.cpp
File metadata and controls
48 lines (36 loc) · 1.03 KB
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
/*
DCMotor.h - implementation
Copyright (c) 2023 Graziano Blasilli.
*/
#include "DCMotor.h"
DCMotor::DCMotor(uint8_t pinA, uint8_t pinB, uint8_t pinS) {
this->pinA = pinA;
this->pinB = pinB;
this->pinS = pinS;
pinMode(this->pinA, OUTPUT);
pinMode(this->pinB, OUTPUT);
pinMode(this->pinS, OUTPUT);
}
// Turn the motor on with a specified speed.
void DCMotor::on(int speed) {
this->off();
// Ensure speed is within valid range (0-255)
speed = constrain(speed, -255, 255);
// Set the motor direction based on the sign of the speed
digitalWrite(this->pinA, speed >= 0 ? HIGH : LOW);
digitalWrite(this->pinB, speed >= 0 ? LOW : HIGH);
// Set the motor speed using PWM
analogWrite(this->pinS, abs(speed));
}
// Turn the motor on with a specified speed, for a given time.
void DCMotor::on(int speed, int millisec) {
this->on(speed);
delay(millisec);
this->off();
}
// Turn the motor off.
void DCMotor::off() {
digitalWrite(this->pinA, LOW);
digitalWrite(this->pinB, LOW);
analogWrite(this->pinS, 0);
}