# Moving average
Computes a running average of incoming numeric values using a selectable algorithm (EMA or CA)
Moving average
V
R
AVG
# Inputs
| ID | Abbrev | Name | Type | Default | Description |
|---|---|---|---|---|---|
value | V | Value | NUMBER | 0 | Numeric input value to include in the average |
reset | R | Reset | BOOLEAN | false | Rising edge resets the average to the current input value |
# Outputs
| ID | Abbrev | Name | Type | Default | Description |
|---|---|---|---|---|---|
average | AVG | Average | NUMBER | 0 | The computed moving average |
# Configuration
| ID | Name | Type | Default | Unit | Description |
|---|---|---|---|---|---|
algorithm | Algorithm | ENUM | 0 | Averaging algorithm: EMA (Exponential Moving Average) or CA (Cumulative Average) Details: Values: EMA, CA | |
alpha | Alpha (smoothing factor) | NUMBER | 0.2 | EMA smoothing factor (0-1). Higher values give more weight to recent values Details: Visible when algorithm = EMA> 0 ≤ 1 |
# State
| ID | Name | Type | Default | Unit | Description |
|---|---|---|---|---|---|
count | Count | NUMBER | 0 | Number of values received | |
prev_reset | Previous reset state | BOOLEAN | false | Previous state of the reset input for edge detection |
# Source Code
View Volang source
channel = input::channel()
value = input::value()
if (channel == "reset") {
prev_reset = state::get("prev_reset")
if (value and !prev_reset) {
current = input::get("value")
state::set("count", 1)
output::set("average", current)
}
state::set("prev_reset", value)
return
}
if (channel == "value") {
count = state::get("count")
avg = output::get("average")
if (count == 0) {
state::set("count", 1)
output::set("average", value)
return
}
algorithm = config::get("algorithm")
if (algorithm == 0) {
alpha = config::get("alpha")
new_avg = alpha * value + (1 - alpha) * avg
output::set("average", new_avg)
} else {
count = count + 1
state::set("count", count)
new_avg = avg + (value - avg) / count
output::set("average", new_avg)
}
}
