Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal
|--------------------------------------------------------------------|----------------------------------------------------------------------|
| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions |
| [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus |
| [Controllers](doc/controllers/README.md) | PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation |
| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation |
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA |
| [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker (offline), Recursive Least Squares (online) |
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR, Moving Average |
Expand Down
7 changes: 0 additions & 7 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ Difficulty legend:
| # | Component | Target module | Difficulty |
|----|------------------------------------------------------|---------------------------|------------|
| 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ |
| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ |
| 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ |
| 6 | Median filter | `filters/passive` | ★★☆☆☆ |
| 7 | Feedforward / 2-DOF controller | `controllers` | ★★☆☆☆ |
Expand Down Expand Up @@ -94,12 +93,6 @@ Difficulty legend:
- **Algorithm / paper:** K. J. Åström, R. M. Murray, *Feedback Systems* (2008), actuator saturation & windup.
- **Reuses:** Scalar/`Vector` templates.

### 4. Bang-bang / hysteresis (relay) controller
- **What:** Two-state relay output with a Schmitt-trigger dead-band to prevent chatter.
- **Embedded value:** The standard control law for thermostats, level control, and power-stage on/off regulation.
- **Algorithm / paper:** Åström & Murray, *Feedback Systems*, relay feedback; Ya. Z. Tsypkin, *Relay Control Systems* (1984).
- **Reuses:** `controllers` interfaces.

### 5. Peak / zero-crossing / RMS-envelope detectors
- **What:** Lightweight feature extractors: rising/falling peak hold, sign-change (zero-crossing) counter, and RMS envelope via one-pole on `x²`.
- **Embedded value:** Cheap building blocks for frequency estimation, VU metering, activity detection, and event triggers.
Expand Down
103 changes: 103 additions & 0 deletions doc/controllers/BangBangHysteresis.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Bang-Bang / Hysteresis (Relay) Controller

## Overview & Motivation

The bang-bang controller is the simplest closed-loop regulator: its output switches between two discrete levels depending on whether the controlled variable is above or below a threshold. Without hysteresis, a plain threshold comparator chatters — switching at high frequency whenever noise nudges the signal across the boundary.

Adding a **dead-band (Schmitt trigger)** eliminates chatter by giving the relay memory: once the output goes High it stays High until the measurement falls all the way to a *lower* threshold, and vice versa. This makes the relay a practical actuator-safe control primitive for thermostats, fridge compressors, tank level switches, and power-stage on/off regulation.

## Mathematical Theory

### State Transition

The relay holds a binary state $s \in \{\text{Low}, \text{High}\}$ with the following transition rules:

$$
s[k] = \begin{cases}
\text{High} & \text{if } s[k-1] = \text{Low} \text{ and } x[k] \geq \theta_H \\
\text{Low} & \text{if } s[k-1] = \text{High} \text{ and } x[k] \leq \theta_L \\
s[k-1] & \text{otherwise}
\end{cases}
$$

where $\theta_L < \theta_H$ are the lower and upper switching thresholds (the hysteresis band).

### Output Map

$$
u[k] = \begin{cases}
u_H & \text{if } s[k] = \text{High} \\
u_L & \text{if } s[k] = \text{Low}
\end{cases}
$$

The output levels $u_L$ and $u_H$ are arbitrary; common choices are $\{0, 1\}$ or $\{-1, +1\}$.

### Hysteresis Band Width

The band width $\Delta = \theta_H - \theta_L$ is the key design parameter. It bounds the switching frequency $f_s$ given a signal slope $\dot{x}$:

$$
f_s \leq \frac{|\dot{x}|}{2\Delta}
$$

A wider band reduces $f_s$ (protecting relays and power stages) at the cost of a larger steady-state limit cycle amplitude.

## Complexity Analysis

| Case | Time | Space | Notes |
|------|--------|--------|--------------------------------------------|
| All | $O(1)$ | $O(1)$ | Two comparisons, one state bit, one select |

No arithmetic on the signal path — only comparisons — so the relay introduces no numerical error and is exactly representable in any floating-point format.

## Step-by-Step Walkthrough

**Setup:** band $[\theta_L, \theta_H] = [-0.2, 0.2]$, outputs $u_L = 0$, $u_H = 1$, initial state Low.

| Step | $x[k]$ | Condition | $s[k]$ | $u[k]$ |
|------|--------|------------------------------|--------|--------|
| 1 | 0.0 | Low, $x < 0.2$ | Low | 0 |
| 2 | 0.3 | Low, $x \geq 0.2$ → switch | High | 1 |
| 3 | 0.1 | High, $x > -0.2$ → hold | High | 1 |
| 4 | −0.3 | High, $x \leq -0.2$ → switch | Low | 0 |
| 5 | 0.0 | Low, $x < 0.2$ → hold | Low | 0 |

## Pitfalls & Edge Cases

- **Inverted band.** $\theta_H \leq \theta_L$ latches the output in an undefined state; reject this at construction time via a precondition assertion.
- **Exactly on threshold.** Transitions are inclusive: $x = \theta_H$ triggers Low→High and $x = \theta_L$ triggers High→Low. This avoids a dead-zone at the switching points.
- **Zero-width band.** $\theta_H = \theta_L$ collapses the relay to a pure comparator (no hysteresis). The logic is still correct but offers no chatter suppression.
- **Noise sizing.** The band width must exceed the peak-to-peak noise amplitude; otherwise noise alone drives state transitions at the sampling rate.
- **Actuator minimum on-time.** Size $\Delta$ so that the minimum on-time (derived from $\Delta / |\dot{x}|_\text{max}$) is above the actuator's rated minimum switching period.

## Variants & Generalizations

| Variant | Key Difference |
|-------------------------------------------|-----------------------------------------------------------------------------------------------------------|
| **Plain comparator** | $\Delta = 0$; no memory, chatters on noise |
| **Asymmetric band** | $\theta_H$ and $\theta_L$ not symmetric around the set-point; biases the duty cycle |
| **Three-state relay** | Adds a dead-band output level $u_0$; used in motor direction control |
| **Adaptive hysteresis** | Band width tracks signal variance online to maintain a target switching rate |
| **Relay feedback test (Åström–Hägglund)** | Deliberate oscillation under relay feedback to identify the ultimate gain/period for automatic PID tuning |

## Applications

- **Thermostats and HVAC** — heating/cooling switched on/off around a temperature set-point.
- **Tank and vessel level control** — pump on/off between high- and low-level floats.
- **Power-stage converters** — hysteretic current-mode control in DC-DC converters and class-D amplifiers.
- **Motor drive enable/disable** — protecting power stages with a current-band relay.
- **Åström–Hägglund auto-tuning** — the relay feedback experiment that drives limit-cycle oscillation for PID parameter identification.

## Connections to Other Algorithms

| Algorithm | Relationship |
|-------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------|
| [PID Controller](Pid.md) | The relay's limit cycle can be used to identify PID tuning parameters via the Åström–Hägglund relay-feedback test |
| [Saturation / Rate Limiter](SaturationRateLimiter.md) | Continuous-output counterpart for actuator constraint; often combined with a relay in cascaded loops |

## References & Further Reading

- K. J. Åström, R. M. Murray, *Feedback Systems: An Introduction for Scientists and Engineers*, Princeton University Press, 2008 — relay feedback, Chapter 10.
- Ya. Z. Tsypkin, *Relay Control Systems*, Cambridge University Press, 1984.
- K. J. Åström, T. Hägglund, "Automatic Tuning of Simple Regulators with Specifications on Phase and Amplitude Margins," *Automatica*, 20(5), 1984.
1 change: 1 addition & 0 deletions doc/controllers/README.md
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Feedback control algorithms for regulating dynamic systems in real time.

| Algorithm | Description |
|--------------------------|-----------------------------------------------------------------------------------------|
| [Bang-Bang / Hysteresis Controller](BangBangHysteresis.md) | Two-state relay controller with Schmitt-trigger dead-band to prevent chatter |
| [PID Controller](Pid.md) | Proportional-Integral-Derivative controller using a discrete recursive formulation |
| [LQR Controller](Lqr.md) | Linear Quadratic Regulator — optimal state-feedback control minimizing a quadratic cost |
| [LQG Controller](Lqg.md) | Linear Quadratic Gaussian — output-feedback optimal control via LQR + Kalman Filter |
Expand Down
6 changes: 6 additions & 0 deletions numerical/controllers/implementations/BangBangHysteresis.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#include "numerical/controllers/implementations/BangBangHysteresis.hpp"

namespace controllers
{
template class BangBangHysteresis<float>;
}
75 changes: 75 additions & 0 deletions numerical/controllers/implementations/BangBangHysteresis.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#pragma once

#if defined(__GNUC__) || defined(__clang__)
#pragma GCC optimize("O3", "fast-math")
#endif

#include "infra/util/ReallyAssert.hpp"
#include "numerical/math/CompilerOptimizations.hpp"
#include <type_traits>

namespace controllers
{
enum class RelayState
{
Low,
High
};

template<typename T>
class BangBangHysteresis
{
public:
static_assert(std::is_floating_point_v<T>, "BangBangHysteresis supports floating-point types");

BangBangHysteresis(T lowThreshold, T highThreshold, T outputLow, T outputHigh);

OPTIMIZE_FOR_SPEED T Update(T measurement);
void Reset(RelayState initial = RelayState::Low);
RelayState State() const;

private:
T lowThreshold;
T highThreshold;
T outputLow;
T outputHigh;
RelayState state{ RelayState::Low };
};

template<typename T>
BangBangHysteresis<T>::BangBangHysteresis(T lowThreshold, T highThreshold, T outputLow, T outputHigh)
: lowThreshold{ lowThreshold }
, highThreshold{ highThreshold }
, outputLow{ outputLow }
, outputHigh{ outputHigh }
{
really_assert(highThreshold > lowThreshold);
}

template<typename T>
OPTIMIZE_FOR_SPEED T BangBangHysteresis<T>::Update(T measurement)
{

Check warning on line 51 in numerical/controllers/implementations/BangBangHysteresis.hpp

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Reduce verbosity with "using enum" for "controllers::RelayState".

See more on https://sonarcloud.io/project/issues?id=embedded-pro_embedded-dsp-control&issues=AZ-fcqfmVdZmdBFKEInJ&open=AZ-fcqfmVdZmdBFKEInJ&pullRequest=167
if (state == RelayState::Low && measurement >= highThreshold)
state = RelayState::High;
else if (state == RelayState::High && measurement <= lowThreshold)
state = RelayState::Low;

return (state == RelayState::High) ? outputHigh : outputLow;
}

template<typename T>
void BangBangHysteresis<T>::Reset(RelayState initial)
{
state = initial;
}

template<typename T>
RelayState BangBangHysteresis<T>::State() const
{
return state;
}

#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
extern template class BangBangHysteresis<float>;
#endif
}
2 changes: 2 additions & 0 deletions numerical/controllers/implementations/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ target_link_libraries(numerical.controllers.implementations ${NUMERICAL_VISIBILI
)

target_sources(numerical.controllers.implementations PRIVATE
BangBangHysteresis.hpp
Lqg.hpp
Lqr.hpp
Mpc.hpp
Expand All @@ -20,6 +21,7 @@ target_sources(numerical.controllers.implementations PRIVATE
)

numerical_add_coverage_sources(numerical.controllers.implementations
BangBangHysteresis.cpp
Lqg.cpp
Lqr.cpp
Mpc.cpp
Expand Down
1 change: 1 addition & 0 deletions numerical/controllers/implementations/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ target_link_libraries(numerical.controllers_test PUBLIC
)

target_sources(numerical.controllers_test PRIVATE
TestBangBangHysteresis.cpp
TestLqg.cpp
TestLqr.cpp
TestMpc.cpp
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
#include "numerical/controllers/implementations/BangBangHysteresis.hpp"
#include "gtest/gtest.h"
#include <array>

namespace
{
class TestBangBangHysteresis
: public ::testing::Test
{
public:
controllers::BangBangHysteresis<float> relay{ -0.2f, 0.2f, 0.0f, 1.0f };
};
}

TEST_F(TestBangBangHysteresis, starts_in_low_state)
{
EXPECT_EQ(relay.State(), controllers::RelayState::Low);
EXPECT_FLOAT_EQ(relay.Update(0.0f), 0.0f);
}

TEST_F(TestBangBangHysteresis, switches_high_at_upper_threshold)
{
float output = relay.Update(0.2f);

EXPECT_EQ(relay.State(), controllers::RelayState::High);
EXPECT_FLOAT_EQ(output, 1.0f);
}

TEST_F(TestBangBangHysteresis, stays_high_inside_band)
{
relay.Update(0.2f);

float output = relay.Update(0.0f);

EXPECT_EQ(relay.State(), controllers::RelayState::High);
EXPECT_FLOAT_EQ(output, 1.0f);
}

TEST_F(TestBangBangHysteresis, switches_low_at_lower_threshold)
{
relay.Update(0.2f);

float output = relay.Update(-0.2f);

EXPECT_EQ(relay.State(), controllers::RelayState::Low);
EXPECT_FLOAT_EQ(output, 0.0f);
}

TEST_F(TestBangBangHysteresis, hysteresis_prevents_chatter)
{
std::array<float, 5> inputs{ 0.1f, -0.1f, 0.15f, -0.15f, 0.05f };

for (float x : inputs)
relay.Update(x);

EXPECT_EQ(relay.State(), controllers::RelayState::Low);
}

TEST_F(TestBangBangHysteresis, full_cycle_sequence)
{
std::array<float, 5> inputs{ 0.0f, 0.3f, 0.1f, -0.3f, 0.0f };
std::array<controllers::RelayState, 5> expectedStates{
controllers::RelayState::Low,
controllers::RelayState::High,
controllers::RelayState::High,
controllers::RelayState::Low,
controllers::RelayState::Low
};

for (std::size_t i = 0; i < inputs.size(); ++i)
{
relay.Update(inputs[i]);
EXPECT_EQ(relay.State(), expectedStates[i]);
}
}

TEST_F(TestBangBangHysteresis, reset_restores_initial_state)
{
relay.Update(0.2f);
EXPECT_EQ(relay.State(), controllers::RelayState::High);

relay.Reset(controllers::RelayState::Low);

EXPECT_EQ(relay.State(), controllers::RelayState::Low);
}

TEST_F(TestBangBangHysteresis, custom_output_levels)
{
controllers::BangBangHysteresis<float> customRelay{ -0.2f, 0.2f, -1.0f, 1.0f };

EXPECT_FLOAT_EQ(customRelay.Update(0.0f), -1.0f);
EXPECT_FLOAT_EQ(customRelay.Update(0.2f), 1.0f);
}
30 changes: 0 additions & 30 deletions roadmap/controllers/BangBangHysteresis/explanation.md

This file was deleted.

Loading
Loading