State change detection with analog input?

    unsigned int x;
    unsigned int samples = 1000;
    unsigned long int accumulator = 0; // initialize accumulator
    for (x = 0; x < samples; x++) {
        accumulator += analogRead(channel);
    }
    return accumulator / samples;

It is faster to use a power of 2 e.g. 512 or 1024 iso 1000 as the compiler can optimize this to a shift instruction which is faster.

In my experience 16/32/64 samples are often enough to have a stable read. More reads will take more time which can cause the
signal to drift as time goes by.