129 lines
2.9 KiB
C++
129 lines
2.9 KiB
C++
#ifndef L298N_ESP32_h
|
|
#define L298N_ESP32_h
|
|
|
|
#include <Arduino.h>
|
|
|
|
class L298N_ESP32 {
|
|
private:
|
|
uint8_t in1Pin;
|
|
uint8_t in2Pin;
|
|
uint8_t enPin;
|
|
uint8_t pwmChannel;
|
|
uint8_t _speed;
|
|
uint8_t _min_speed = 0;
|
|
uint8_t _max_speed = 255;
|
|
bool _invert = false;
|
|
|
|
void checkWrite(uint8_t value) {
|
|
if (_speed != value) {
|
|
_speed = value;
|
|
ledcWrite(enPin, _speed);
|
|
}
|
|
}
|
|
|
|
public:
|
|
L298N_ESP32(uint8_t in1, uint8_t in2, uint8_t en, uint8_t channel = 0) :
|
|
in1Pin(in1), in2Pin(in2), enPin(en), pwmChannel(channel), _speed(0) {}
|
|
|
|
void begin() {
|
|
pinMode(in1Pin, OUTPUT);
|
|
pinMode(in2Pin, OUTPUT);
|
|
ledcAttachChannel(enPin, 30000, 8, pwmChannel); // 30kHz frequency, 8-bit resolution
|
|
digitalWrite(in1Pin, LOW);
|
|
digitalWrite(in2Pin, LOW);
|
|
checkWrite(0);
|
|
}
|
|
|
|
void setMin(uint8_t value) {
|
|
_min_speed = value;
|
|
}
|
|
|
|
void setMax(uint8_t value) {
|
|
_max_speed = value;
|
|
}
|
|
|
|
void invert() {
|
|
_invert = !_invert;
|
|
}
|
|
|
|
void forward() {
|
|
if (!_invert) {
|
|
digitalWrite(in1Pin, LOW);
|
|
digitalWrite(in2Pin, HIGH);
|
|
} else {
|
|
digitalWrite(in1Pin, HIGH);
|
|
digitalWrite(in2Pin, LOW);
|
|
}
|
|
}
|
|
|
|
void backward() {
|
|
if (!_invert) {
|
|
digitalWrite(in1Pin, HIGH);
|
|
digitalWrite(in2Pin, LOW);
|
|
} else {
|
|
digitalWrite(in1Pin, LOW);
|
|
digitalWrite(in2Pin, HIGH);
|
|
}
|
|
}
|
|
|
|
void goMin() {
|
|
checkWrite(_min_speed);
|
|
}
|
|
|
|
void goMax() {
|
|
checkWrite(_max_speed);
|
|
}
|
|
|
|
void setSpeed(uint8_t speed) {
|
|
speed = constrain(speed, _min_speed, _max_speed);
|
|
checkWrite(speed);
|
|
}
|
|
|
|
void setPercentage(uint8_t percentage) {
|
|
if (percentage == 0) {
|
|
checkWrite(0);
|
|
} else {
|
|
uint8_t speed = map(percentage, 1, 100, _min_speed, _max_speed);
|
|
checkWrite(speed);
|
|
}
|
|
}
|
|
|
|
void override(uint8_t value) {
|
|
ledcWrite(enPin, value);
|
|
}
|
|
|
|
void stop() {
|
|
digitalWrite(in1Pin, LOW);
|
|
digitalWrite(in2Pin, LOW);
|
|
checkWrite(0);
|
|
}
|
|
|
|
unsigned int command(Stream &serial) {
|
|
unsigned int lastTriedValue = 0;
|
|
while (true) {
|
|
serial.print("Enter PWM value (0-255) or 'exit': ");
|
|
while (!serial.available()) {}
|
|
if (serial.available()) {
|
|
String input = serial.readStringUntil('\n');
|
|
serial.readString(); // Clear buffer
|
|
input.trim();
|
|
if (input.equalsIgnoreCase("exit")) {
|
|
serial.println("Exiting command function");
|
|
stop();
|
|
return lastTriedValue;
|
|
}
|
|
int value = input.toInt();
|
|
if (value >= 0 && value <= 255) {
|
|
lastTriedValue = value;
|
|
serial.println(lastTriedValue);
|
|
setSpeed(lastTriedValue);
|
|
} else {
|
|
serial.println("Invalid input. Please enter a value between 0 and 255.");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
#endif
|