Help, I want to turn relay constantly on until a difference is detected, but triggered only one instead
As far as I can see, the relay will stay on when val is less or equal than 500, and stay off when val is higher than 500.

However, there might be a problem when val keeps fastly moving around 500; it will switch on and off quite fast.

To prevent this, you should make two 'triggers', e.g. turn it on when the value &lt;= 480, and turn it off when the value >= 520. When it is in between 480 and 520 it will not change. This will cause less fast changes of the relay. Of course if the initial value is already between 480 and 520 you have to make a choice yourself.