# Moving average

Process

Computes a running average of incoming numeric values using a selectable algorithm (EMA or CA)

Moving average
V
R
AVG

# Inputs

IDAbbrevNameTypeDefaultDescription
valueVValueNUMBER0Numeric input value to include in the average
resetRResetBOOLEANfalseRising edge resets the average to the current input value

# Outputs

IDAbbrevNameTypeDefaultDescription
averageAVGAverageNUMBER0The computed moving average

# Configuration

IDNameTypeDefaultUnitDescription
algorithmAlgorithmENUM0Averaging algorithm: EMA (Exponential Moving Average) or CA (Cumulative Average)

Details:

Values: EMA, CA
alphaAlpha (smoothing factor)NUMBER0.2EMA smoothing factor (0-1). Higher values give more weight to recent values

Details:

Visible whenalgorithm = EMA
> 0
≤ 1

# State

IDNameTypeDefaultUnitDescription
countCountNUMBER0Number of values received
prev_resetPrevious reset stateBOOLEANfalsePrevious 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)
    }
}
Computes a running average of incoming numeric values using a selectable algorithm (EMA or CA)