C语言_用于ADC数据的均值滤波算法

C语言_用于ADC数据的均值滤波算法

说明:
在采集ADC值的时候一般都是多次采集然后,然后取平均值,改进型做法就是去掉最大最小值剩下的再取平均值

unsigned short average(unsigned short arr[], unsigned char size)
{
	unsigned int sum = 0;

	for (unsigned int i = 0; i < size - 1; i++) {
		for (unsigned int j = 0; j < size - i - 1; j++) {
			if (arr[j] > arr[j + 1]) {
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
	for(unsigned int i = 1; i < size - 1; i++)
	{
		sum += arr[i];
		//SENSOR_printf("%d ",arr[i]);
	}
	//SENSOR_printf("\r\n");

	//SENSOR_debug("sum:%d,count:%d,average:%d\r\n",sum,size-2,sum /(size-2));
	return sum /(size-2);
}

应用实例:

#include 

unsigned short average(unsigned short arr[], unsigned char size)
{
	unsigned int sum = 0;

	for (unsigned int i = 0; i < size - 1; i++) {
		for (unsigned int j = 0; j < size - i - 1; j++) {
			if (arr[j] > arr[j + 1]) {
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
	for(unsigned int i = 1; i < size - 1; i++)
	{
		sum += arr[i];
		printf("%d ",arr[i]);
	}
	printf("sum:%d,count:%d,average:%d\r\n",sum,size-2,sum /(size-2));
	return sum /(size-2);
}
 
int main()
{
    unsigned short data[10] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09};
    printf("Hello, World\r\n");
    printf("average:%d",average(data, 10));
    return(0);
}

输出:
C语言_用于ADC数据的均值滤波算法_第1张图片

你可能感兴趣的:(STM32开发经验,算法,c语言,均值算法)