- // Struktura wyniku softstartu
- struct SoftUpdateResult {
- int value; // Zaktualizowana wartość
- uint8_t state; // 0 = osiągnięto, 1 = rośnie, 2 = maleje
- float progressPercent; // Procent pozostały do osiągnięcia celu
- };
- // Struktura stanu softstartu
- struct SoftUpdateState {
- unsigned long lastUpdate; // Czas ostatniej aktualizacji (ms)
- int currentValue; // Aktualna wartość
- bool active; // Czy softstart jest aktywny
- int initialDelta; // Początkowa różnica między wartościami
- };
- Pasztet::
- SoftUpdateResult softUpdate(SoftUpdateState &state, int targetValue, int stepSize, float totalTimeSec, bool debug) {
- SoftUpdateResult result = { state.currentValue, 0, 0.0 }; // Domyślnie: cel osiągnięty
- // Oblicz procent postępu
- int delta = abs(targetValue - state.currentValue);
- if (state.initialDelta == 0) {
- result.progressPercent = 0.0; // Brak różnicy początkowej
- } else {
- result.progressPercent = (float)delta / state.initialDelta * 100.0; // Procent pozostały
- }
- // Logowanie w trybie japierdole dlaczego to nie dziala ?!
- Serial.printf("Debug: delta=%d, initialDelta=%d, progressPercent=%.1f%%\n", delta, state.initialDelta, result.progressPercent);
- // Jeśli wartości są równe, nie ma potrzeby aktualizacji
- if (state.currentValue == targetValue) {
- state.active = false;
- result.state = 0;
- result.progressPercent = 0.0;
- return result;
- }
- // Oblicz liczbę kroków i interwał czasowy
- int totalSteps = (delta + stepSize - 1) / stepSize; // Zaokrąglenie w górę
- unsigned long intervalMs = max(50UL, (unsigned long)((totalTimeSec * 1000.0) / totalSteps)); // Min 50ms
- unsigned long now = millis();
- if (!state.active || now - state.lastUpdate >= intervalMs) {
- state.lastUpdate = now;
- state.active = true;
- if (state.currentValue < targetValue) {
- state.currentValue += stepSize;
- if (state.currentValue > targetValue) state.currentValue = targetValue;
- result.state = 1; // Rośnie
- } else if (state.currentValue > targetValue) {
- state.currentValue -= stepSize;
- if (state.currentValue < targetValue) state.currentValue = targetValue;
- result.state = 2; // Maleje
- }
- result.value = state.currentValue;
- if (state.currentValue == targetValue) {
- result.state = 0; // Osiągnięto
- state.active = false;
- result.progressPercent = 0.0; // Cel osiągnięty
- } else {
- // Zaktualizuj procent postępu
- delta = abs(targetValue - state.currentValue);
- if (state.initialDelta == 0) {
- result.progressPercent = 0.0; // Zabezpieczenie
- } else {
- result.progressPercent = (float)delta / state.initialDelta * 100.0;
- }
- }
- // Logowanie generalne...
- Serial.printf("SoftUpdate: Wartość=%d, Stan=%s, Pozostało=%.1f%%, Interwał=%lu ms\n",
- result.value,
- result.state == 0 ? "Osiągnięto" : (result.state == 1 ? "Rośnie" : "Maleje"),
- result.progressPercent,
- intervalMs);
- }
- return result;
- }