Version 0 of Filtering measurement values with a 1D Kalman filter

Updated 2017-07-09 11:54:46 by JMeh

The Kalman algorithm can eliminate noise from a group of measurement values (see wikipedia article https://en.wikipedia.org/wiki/Kalman_filter ) and is therefore a complicated mathematical algorithm full of matrix operations. But when we reduce the problem to only one variable (which contains the noise), this algorithm can be simplified. I found a nice implementation (http://interactive-matter.eu/blog/2009/12/18/filtering-sensor-data-with-a-kalman-filter/ ) with only 4 lines of important code. There is also an implementation for Arduino (https://github.com/bachagas/Kalman ).

Here is a little Tcl code which helps me freeing my measurements (weights from a scale during a steel remelting process) from noise:

#
# Kalman - Filter
#
# https://de.wikipedia.org/wiki/Kalman-Filter
# https://github.com/bachagas/Kalman
# http://interactive-matter.eu/blog/2009/12/18/filtering-sensor-data-with-a-kalman-filter/
#

namespace eval ::kalman {
  variable state
}


proc ::kalman::init {id q r p initial_value} {
  variable state

  set state($id,q) $q
  set state($id,r) $r
  set state($id,p) $p
  set state($id,x) $initial_value

  return $id
}


proc ::kalman::update {id measurement} {
  variable state

  # prediction update
  set state($id,p) [expr {$state($id,p) + $state($id,q)}]

  # measurement update
  set state($id,k) [expr {$state($id,p) / ($state($id,p) + $state($id,r))}]
  set state($id,x) [expr {$state($id,x) + $state($id,k) * ($measurement - $state($id,x))}]
  set state($id,p) [expr {(1.0 - $state($id,k)) * $state($id,p)}]

  return $state($id,x)
}


proc ::kalman::get {id} {
  variable state

  return $state($id,x)
}


proc ::kalman::destroy {id} {
  variable state

  array unset state $id,*
}


package provide kalman 1.0