When the contact sensor circuit is open, i.e. the magnet is in distance, the binary sensor returns a firm ON, but when the the magnet touches the sensor, it returns a constant ON/OFF/ON/OFF… I had to add a delay to OFF to get some stable output but sometimes, it is not enough.
My first guess would be faulty wiring (or a faulty reed switch), especially since it’s only giving you issues when in the closed state. I’d double-check your connections and also swap out the sensor.
We don’t know if it’s the most common normally open or a normally closed reed switch. I use both. Sometimes get tied up in the logic. I’ve found leaving it floating is an interesting experience.
When sensor is either closed or opened (can’t remember now which one is OK), it is fine, but in opposite state, it is flapping. I suspect this is due to bad cable (thin or interference or both, length is ~12m). Would hardware resistor help in this case? What value should I try with? Do I disable internal then? If I disable it now with long cable connected, it does not flap, but it also does not change state at all.
Unshielded cable of that length is huge antenna for interferences.
Like I wrote above, if you don’t know your reed sensor circuit, you can try with internal pulldown first: pulldown: true (in case of esp32)
For hardware resistor correct value depends on many things, you could start with 1k - 4k7
In case you have bare reed switch (not some sensor circuit), which is just a magnetic switch, you wire it between GPIO and GND and set internal pullup or use hardware pullup resistor.
It is just normal magnetic. When magnets are near each other, circuit is closed and GPIO and GND are connected.
I can try with hw resistor. Do I wire it just between GPIO and GND? Do i need to disable internal then? (Remove pullup: true) part?
With code above, when I just connect sensor to GPIO and GND (20cm cable), and move magnets, it behaves as expected.