4.4.4 Update Average Filters

These filters are used to average out the noise in the PIR sensor measurement. This will reduce the chance of false detections when the noise is high. The short_term_average filter is the average of the four most recent ADC measurements and can be adjusted in the define PIR_SHORT_TERM_FILTER_RANGE. For each new ADC measurement, 1/(size of filter) is subtracted, and the new ADC measurement is added. This way, the filter is constantly updated and will be able to track rapid changes in the ADC measurements, such as movement. The long_term_average filter swap out 1/(size of filter) for each new ADC measurement. The long_term_average filter is slower but will track and average the noise in the measurement in addition to the slower drift in the system. When there is no movement, the filters will converge around the same value, and the filter_delta will stay low. When movement happens, the signal from the PIR will change, and the filter_delta will increase since the short_term_average will follow the changing signal faster than the long_term_average.

void update_average_filters()
{
	accumulated_long_term_average
	-= accumulated_long_term_average / PIR_LONG_TERM_FILTER_RANGE; /* Subtract 1/x from accumulated filter value */
	accumulated_short_term_average
	-= accumulated_short_term_average / PIR_SHORT_TERM_FILTER_RANGE; /* Subtract 1/y from accumulated filter value */

	accumulated_long_term_average += adc_result;  /* Add new ADC measurement (1/x) to accumulated filter value */
	accumulated_short_term_average += adc_result; /* Add new ADC measurement (1/y) to accumulated filter value */

	long_term_average = accumulated_long_term_average / PIR_LONG_TERM_FILTER_RANGE; /* Divide the accumulated_long_term_average on X to create long_term_average */
	short_term_average = accumulated_short_term_average	/ PIR_SHORT_TERM_FILTER_RANGE; /* Divide the accumulated_long_term_average on Y to create long_term_average */

	filter_delta = long_term_average - short_term_average; /* Find delta between filters */
}