December 9, 2025, 7:12 pm by: cuagfe
Unknown
GPS location

// ESP32 + BTS7960 – smooth acceleration and braking 20→100→20%
// Direction: first LEFT, then RIGHT, in a loop
#define RPWM_PIN 4 // right
#define LPWM_PIN 16 // left
#define LED_PIN 2 // LED – lights up when the motor is running
const int pwmFreq = 20000;
const int pwmResolution = 8; // 0–255
const int stepTime = 2000; // 2 seconds for each 10% step
void setup() {
Serial.begin(115200);
ledcAttach(RPWM_PIN, pwmFreq, pwmResolution);
ledcAttach(LPWM_PIN, pwmFreq, pwmResolution);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
Serial.println("Start: smooth LEFT → RIGHT → LEFT...");
delay(1000);
}
void loop() {
// ==================== LEFT: 20% → 100% → 20% ====================
runDirectionSmooth(LPWM_PIN, RPWM_PIN, "LEFT");
// Short pause after the full left cycle
stopMotor();
delay(1000);
// ==================== RIGHT: 20% → 100% → 20% ====================
runDirectionSmooth(RPWM_PIN, LPWM_PIN, "RIGHT");
// Short pause after the full right cycle
stopMotor();
delay(1000);
}
// =====================================================
// Function: smooth acceleration and braking in one direction
// =====================================================
void runDirectionSmooth(int forwardPin, int reversePin, String dirName) {
// Acceleration: 20% → 100%
for (int duty = 51; duty <= 255; duty += 25) { // 51≈20%, 255=100%, step ≈10%
int percent = (duty * 100) / 255;
Serial.printf("→ %s: %d%% (duty=%d)n", dirName.c_str(), percent, duty);
digitalWrite(LED_PIN, HIGH);
ledcWrite(forwardPin, duty);