Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Simple C code for 50 point moving average filter using Buffer

Status
Not open for further replies.

dipk11

Junior Member level 2
Joined
Jul 27, 2017
Messages
23
Helped
0
Reputation
0
Reaction score
0
Trophy points
1
Activity points
245
Hi all,
Anybody has a code written for a N point moving average filter in C?
I am basically stuck with the implementation when it comes to the averaging part.
It would be great if someone can help me kickstart with sample code.

Regards.
 

Hi,

A forum is not meant that others do your job.
--> Show what you have done so far.

There are explanations as well as code in the internet...

Klaus
 

code for 50 point moving average filter using Buffer

Another useful concept you'll need to know during code implementation is the circular buffer, which can be used to add/remove samples, one per time, keeping the last 49 ones.
 

Code:
void add_value(double *buf, uint16_t size, double value)
{
	uint16_t i;

	for (i = 1; i != size; i++)
		buf[i] = buf[i + 1];

	buf[size - 1] = value;
}

double get_average(double *buf, uint16_t size, uint16_t average)
{
	double sum = 0;
	uint16_t i;

	for (i = size - average; i != size; i++)
		sum += buf[i];

	return sum / average;
}
Usage:
Code:
double buf[100];

int main(void)
{
	uint16_t i;

	for (i = 0; i != 100; i++)
		buf[i] = 0.0;

	for (i = 0; i != 100; i++) {
		add_value(buf, 100, i / 10);
	}

	printf("Average 5: %f\n", get_average(buf, 100, 5));
	printf("Average 10: %f\n", get_average(buf, 100, 10));
	printf("Average 50: %f\n", get_average(buf, 100, 50));
}
 
Last edited:

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top