Created
June 6, 2023 22:32
-
-
Save dzid26/86bbd4899cd94a10aa9276f1433b2838 to your computer and use it in GitHub Desktop.
32bit movingAverage with 16bit buffer + offsets - for slowly moving signals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define AVG_WINDOW 16U | |
static int32_t errMovingAverage(int32_t val) { | |
const uint8_t window_n = AVG_WINDOW; | |
static int16_t ringbuffer[AVG_WINDOW-1U]; | |
static int32_t offset = 0; | |
static int32_t old_offset = 0; | |
static uint8_t ringbuffer_idx = window_n-1U; | |
static int32_t avg=0; | |
static int32_t accu=0; | |
if (ringbuffer_idx==(window_n-1U)){ | |
old_offset = offset; | |
offset = val; | |
}else{ | |
int16_t delta = (int16_t)(val - offset); | |
accu += (int32_t)(delta - (ringbuffer[ringbuffer_idx])); | |
ringbuffer[ringbuffer_idx] = delta; | |
} | |
avg = offset + (accu - ((offset - old_offset)*(int8_t)(uint8_t)(window_n-ringbuffer_idx-1U)))/(int32_t)window_n; | |
ringbuffer_idx = (ringbuffer_idx + 1U) % window_n; | |
return avg; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment