The sensor is noisy. The data may suddenly bounce. Humans are also very analog. Even if you think you are holding your finger, the data will fluctuate.
If this is used digitally as it is, it will result in a very unstable system. Therefore, it is important to have a filter that prepares the raw data.
Use the Exponential Moving Average (EMA) filter. [(Reference)](https://en.wikipedia.org/wiki/%E7%A7%BB%E5%8B%95%E5%B9%B3%E5%9D%87#%E6%8C%87% E6% 95% B0% E7% A7% BB% E5% 8B% 95% E5% B9% B3% E5% 9D% 87)
S_t = α \times Y_{t-1} + (1-α) \times S_{t-1}
The larger the value of α, the smaller the weight of the old value. And vice versa.
Attenuates momentary fluctuations. You can get data that suppresses buzzing.
var lastVal: CGFloat = 0.0
var alpha: CGFloat = 0.4
func lowpass(val: CGFloat) -> CGFloat {
lastVal = alpha * val + lastVal * (1 - alpha)
return lastVal
}
Only the momentary fluctuation component is used. You can get the data when it changes suddenly.
var lastVal: CGFloat = 0.0
var alpha: CGFloat = 0.4
func highpass(val: CGFloat) -> CGFloat {
lastVal = alpha * val + lastVal * (1 - alpha)
return val - lastVal
}
Recommended Posts