Endlessly repeating...

A low pass filter in Processing

14 January 2010

In trying to further humanise my wobbly camera project I needed some of the parameters to change in a way that was linked but with one of the parameters responding at a slower rate. To do this, you need a low pass filter which will be familiar to anyone that's spent any time making electronic music (anyone else should follow the link). There are a few ways to implement such a filter but for my purposes a quick moving average version was good enough. This works by buffering it's inputs into a FIFO and output the mean value of the contents of the buffer (I wouldn't do a good job of explaining the maths behind this so I'm not even going to try). The degree of filtering can be changed by increasing or decreasing the length of the FIFO queue. Code for the filter class and a little example are below.

float vPrev, lPrev, v;
LowPass lp;

void setup() {
    size(600, 200, P2D);
    lp = new LowPass(10);  //The argument is the FIFO queue length

void draw() {
    v = noise((float)frameCount / 10) * 100;

    line(3 * (frameCount - 1), vPrev, 3 * frameCount, v);
    vPrev = v;

    line(3 * (frameCount - 1), lPrev + 100, 3 * frameCount, lp.output + 100);
    lPrev = lp.output;

class LowPass {
    ArrayList buffer;
    int len;
    float output;

    LowPass(int len) {
        this.len = len;
        buffer = new ArrayList(len);
        for(int i = 0; i < len; i++) {
            buffer.add(new Float(0.0));

    void input(float v) {
        buffer.add(new Float(v));

        float sum = 0;
        for(int i=0; i<buffer.size(); i++) {
                Float fv = (Float)buffer.get(i);
                sum += fv.floatValue();
        output = sum / buffer.size();