You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1013 B
65 lines
1013 B
9 years ago
|
#include <stdint.h>
|
||
|
#include <malloc.h>
|
||
|
|
||
|
#include "meanbuf.h"
|
||
|
|
||
|
|
||
9 years ago
|
struct meanbuf_struct {
|
||
|
float * buf; // buffer (allocated at init)
|
||
|
size_t cap; // capacity
|
||
|
size_t nw; // next write index
|
||
|
float mean; // updated on write
|
||
|
};
|
||
|
|
||
|
|
||
9 years ago
|
/** Init a buffer */
|
||
9 years ago
|
MeanBuf *meanbuf_create(size_t size)
|
||
9 years ago
|
{
|
||
9 years ago
|
MeanBuf *mb = malloc(sizeof(MeanBuf));
|
||
|
|
||
9 years ago
|
if (size < 1) size = 1;
|
||
|
|
||
|
mb->buf = calloc(size, sizeof(float)); // calloc, so it starts with zeros.
|
||
|
mb->cap = size;
|
||
|
mb->nw = 0;
|
||
|
mb->mean = 0;
|
||
|
|
||
|
// clean buffer
|
||
|
for (uint16_t i = 0; i < size; i++) {
|
||
|
mb->buf[i] = 0;
|
||
|
}
|
||
9 years ago
|
|
||
|
return mb;
|
||
9 years ago
|
}
|
||
|
|
||
|
|
||
9 years ago
|
void meanbuf_destroy(MeanBuf *mb)
|
||
9 years ago
|
{
|
||
9 years ago
|
if (mb == NULL) return;
|
||
|
|
||
9 years ago
|
if (mb->buf != NULL) {
|
||
|
free(mb->buf);
|
||
|
}
|
||
9 years ago
|
|
||
|
free(mb);
|
||
9 years ago
|
}
|
||
|
|
||
|
|
||
|
/** Add a value to the buffer. Returns current mean. */
|
||
9 years ago
|
float meanbuf_add(MeanBuf *mb, float f)
|
||
9 years ago
|
{
|
||
|
// add sample
|
||
|
mb->buf[mb->nw++] = f;
|
||
|
if (mb->nw == mb->cap) mb->nw = 0;
|
||
|
|
||
|
// calculate average
|
||
|
float acc = 0;
|
||
|
for (size_t i = 0; i < mb->cap; i++) {
|
||
|
acc += mb->buf[i];
|
||
|
}
|
||
|
|
||
|
acc /= mb->cap;
|
||
|
|
||
|
return mb->mean = acc;
|
||
|
}
|