Pi GPIO Binary Sesnsor

I’m having the same problem. Quite often HA is not correctly showing the port input state. It detects the on state perfectly but misses the edge for return to the off state and does not update until there is a further trigger (often misses the return on that too).

There are quite a few reports of this and people (myself included) have tried messing with the debounce time and external pull-up resistors to no avail. Disabling the debounce timer by giving it a value of 1 is not a solution as multiple events are then generated.

This is quite disappointing as I have numerous hard wired PIR sensors already in place from an existing alarm system I wanted to replace with HA. Until the GPIO binary sensor is reliable HA is just not an option for me.

There’s already an open ticket about this but it has seen no activity since October last year.

@tom_l

Success!!

Spent two days testing gpio state for use with alarm sensors. I replace old Ademco, etc. alarm panels with Raspberry Pi. Couldn’t gpio to consistently detect ON/OFF state.(poor edge detection) It would turn ON OK but OFF was inconsistent or not at all.

Finally gave up and just installed and wired the alarm sensors. I had successfully set this up previously and took SD card from that pi and still had failures and figured something was up. It worked when wired in circuit to alarm door and motion sensors.

Problem for me was voltage it seems. Out of circuit gpio pin received 3.29vdc. In circuit it received 3.17vdc.
I use resistors but extra wire resistance from 10’+ wire runs made a big difference. GPIO is set as normally low. I thought 3.29 would be within limit but maybe it must be lower, 3vdc - 3.2vdc.

I’m not following what you are saying. First you say “success” then you say the voltage is too low (it isn’t btw, 3.17v is plenty for logic 1). What did you do to get HA to see the ports to reliably return to the inactive state?

There’s no actual electrical specification for the gpio but some investigation has revealed that an input logic 1 will be detected reliably above 2.15v. A logic 0 must be below 1.15v. Apparently the gpio port can only source 16mA TOTAL (all pins combined) but it can sink 16mA at EACH port. More here: http://www.mosaic-industries.com/embedded-systems/microcontroller-projects/raspberry-pi/gpio-pin-electrical-specifications#input-and-output-pin-electrical-specifications.

I have all my inputs (and outputs) isolated with optocouplers. So at the gpio pin I have 0.1v as logic 0 and 3.3v as logic 1 no matter what the length of cable is. This also reduces the input capacitance to pF levels. Long runs of cable may have excessive capacitance which can cause switching transients on the input.

The problem is edge detection when the input returns to the inactive state (inverted logic enabled or not). This is a timing issue with HA. Using a python routine to read the ports does not have this problem. It is only HA.

If your sensors are active for 2 seconds or more (most PIRs will be ok) it seems to be reliable but less than this and the input may not register a change on return to the inactive state. A doorbell switch for example is going to be problematic.

1 Like

Thank’s to everyone on this thread, I created a hopefully simple example of how to read/write gio. Switch drives a LED.

And, per previous comments, I was having alot of issues with triggering working sometimes. Here is gpio port output with no decoupling capacitor https://imgur.com/iD3xGTb

After I added decoupling capacitor to the gpio swith port, the bounce went away. https://imgur.com/yaVrKs3

Thanks again for all of the comments in this thread.

Try pressing your switch for less than a second and see what happens.

Like this?

What is this in your binary_sensor definition?:

scan_interval: 10

I haven’t seen that documented anywhere.

Edit/ also I suspect you have very little else tying up the availability of the HA bus. In my system with the full GPIO bus wired to inputs and output plus countless other automations and scripts this becomes a problem,

Sorry for late reply but I wanted to test some things. Also, sorry I am busy and did not have time to check by Oscope but I think my result may be helpful to some. I will try to make clear what happened for me while setting up Binary Sensor as input for my home alarm sensors (only 2 doors so far)

GOAL
My goal was to take existing alarm contacts (door sensor and motions) and use with RasPi and HA Binary Sensor. I previously succeed with this without any problem and expected task to be simple but it was a little complicated

TEST#1 (Fail)
I started by testing on bench(kitchen table) just to verify I could remember the pinout and make sure HA didnt have some error that came along since I last used for this purpose. This had issue where hi/low was not consistently detected (edge detect error).

TEST#2(Fail)
I wanted to test with know good install. I pulled SD Card from the RasPi running my gate using Cover component. This has x1 magnetic sensor and is connected to relay controlling gate Open. When I use this HA Install in my test configured for Binary Sensor my result was same, hi/low not properly detected.

INSTALL#1 (Success)
As stated in previous post, I have done this same setup 5 time previously without problem so I decided to ignore test result and install. I use a RasPi HAT that has screw down terminals for GPIO and standard 5VDC micro USB power supply. Sensor are the standard door reed switch with magnets connected from 3VDC to GPIO input with 1K ohm resistor. This worked without issue. Open/Close resulted in high/low change. I try opening just enough to change state and immediate close (assume <1sec change) and function was OK. I considered this success and post my information. I notice there was lower voltage 3.17vdc when I have success so I thought this useful and put this information.

INSTALL#2 POWER SUPPLY UPGRADE (Fail)
I wanted single supply for Motion Detectors(12vdc) and RasPi(5vdc) so I install power supply that supply both voltage (MEAN WELL RD-65A). Immediately after install this supply I have edge detect problems again.

RESISTOR CHANGE (Success)
I remember for my other Alarm Box changeovers I use 2.2K ohm resistors and decide to change from the current 1K to 3.2k resistance. This worked but I did notice if I try quick open/close (approx 750ms) it did not detect always. I increase resistance to 5.4k and even quick open/close(less than 500ms) is properly detected. After this was working OK I decide to also lower “bouncetime” from 300 to 50

FINAL RESULT (success)
Circuit: 3vdc>>5.4K ohm>>gpio input

binary_sensor:

  • platform: rpi_gpio
    ports:
    17: Garage Great Rm Door
    26: Garage Kitchen Dr
    pull_mode: DOWN
    bouncetime: 50
    scan_interval: 10

NOTE
I use HA for Doorbell previously. Basically directly wired button into HA with 2.2K resistor just like an alarm contact. Upon thought I did have some issue for presses less than 1 second, but this is like result I receive before my change from 3.2k to 5.4k. honestly I’ve used GPIO for 4 separate installs/implementations of GPIO with HA and function was always stable enough for production use.
My previous HA Alarm install consisted of 2doors, 4motions and 1 doorbell connected to GPIO.

https://www.amazon.com/gp/product/B005T7EZM8/ref=oh_aui_detailpage_o04_s00?ie=UTF8&psc=1

https://www.amazon.com/gp/product/B01M27459S/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1

1 Like

Wow. That sounds far from stable.
I’ve given up on HA’s GPIO inputs. I was running out of pins anyway. I’m moving all my inputs to another Pi that runs a python script to monitor the gpio pins and reports the states via mqtt. A user on Reddit was kind enough to share the script.

My outputs and temperature DHT22 sensors are still connected to the “master’ Pi running Hassio.

4 Likes

Hi,

Something to keep in mind when using GPIO input/ outputs on raspberry PIs

1.Consider the default state of a RP on powerup or reboot, some pins are configured as input or outputs and can have internal pull ups enabled.
refer to this link: https://raspberrypi.stackexchange.com/questions/51479/gpio-pin-states-on-powerup
Study the pin you intend to use as a input or output on power up and find one that works to your default power on state.
2. Random input readings, most likely due to the pin is floating. Add a pull up resistor to your 3.3V line or pull down to ground. (You can avoid using an external pull up resistor by using the internal week pullup of the GPIO.)
or
All mechanical switches bounce. HA could be reading mutliple states on the one key press, plenty of circuits/solutions on google as to how to debounce a button.
3. Missing trigger inputs, Hassbian isn’t a real time operating systems, hence HA it could be busy doing something else and can miss a putton presst, you can use a latch circuit between the buttons with something like 74FCT2573T or http://www.play-hookey.com/digital/sequential/rs_nand_latch.html
Once you’ve read the state chance, simply reset the latch with a free GPIO pin.

If you’re still having issues please feel free to contact me, happy to assist here!!

Rob.

  1. Noted and all is well. Start up values are correct.

  2. I don’t get random inputs. Pins are not floating. HA GPOIs have a debounce routine. I have tried ridiculously long debounce times. No change in behaviour. I have also tried an electronic pulse with no bounce. The problem remains.

  3. It doesn’t have to be real time it. HA just needs to respond to all state changes. If the pulse was 1 second long I dont care if it is stretched to 2 or 3 seconds by HA. I just want the state changes - in order.

HA will detect the initial state change to active but more often than not it will not detect the return to the inactive state if the pulse is less than 1.5 seconds. HA needs some sort of FIFO buffer or message queue.

I’ve been noticing the same thing here. HA seems pretty reliable at detecting the initial trigger, but often misses the return to normal. This seems to be most often when the initial trigger is short acting rather than long acting (e.g. Motion sensors which always trigger for at least 2 seconds are fine, but doorbells that you quickly press and let go often aren’t)

If anyone comes up with an actual solution, I’m all ears, but so far all combinations of pull-ups, pull-downs, and debounce times have been ineffective (which is to be expected given the suspected nature of the issue).

1 Like

Yep. That’s exactly the issue. Unfortunately the developers have shown zero interest in fixing it. The only reliable solution I’ve found is not to use HA for GPIO inputs. See my mqtt post above.

Barring a developer expressing interest in fixing it, maybe I’ll have to come up with some form of external circuit that debounces and widens the pulse width to avoid those short trigger situations.

Beyond that I’ve had some success triggering on the leading edge of things instead of the trailing edge, of course if you want to use the same input again before HA finally notices the state change you’re still screwed.

I tried a 555 timer ic configured as a 2 second monostable to stretch input pulses. This did work. Search for the circuit. Note however this inverts the signal and it is a 5V chip so needs a resistor divider on the output the protect the 3.3v raspi GPIO input.

Having the same issue with particular magnetic switches.

The external solutions people are developing are polling which is always reading the current state. Hass calls GPIO.add_event_detect in the external RPi.GPIO library which is relying on getting edge events from the kernel via epoll. I’m curious if the issue is intertwined with the number of pins your are watching as the library code is watching all the pins through a single epoll interface.

I’m using Raspbian Stretch (kernel = 4.14.34-v7+). I’ve tried RPi.GPIO 0.6.3 and the latest code from https://sourceforge.net/p/raspberry-gpio-python/code/ci/default/tree/ but it still has the same issue. Until the upstream library/kernel works, hass will not work.

The fix for my setup is a 1ms bounce time. This is just an alarm trigger so the bounce is not an issue. This won’t work for people expecting user button presses.

Are you able to tell if the problem is in the underlying RPi GPIO library, or in Home Assistant’s interface to it?

It seems unlikely to me that an issue this substantial would be in the underlying library and not have attracted a fair amount of attention.

I used the code at the bottom which sums up what hass actually does. I don’t think you can get much more basic. This is only for a single pin. The results show that the callback doesn’t get called for the final return to 0.

A key point to note is that this ONLY affects those using add_event_detect and only for certain types of input. Some of my switches work perfectly but the old magentic sensors used in some of our windows produce this incorrect behavior. I only briefly looked at the GPIO library code and I didn’t see anything out of the ordinary so I’m wondering if there is a epoll or driver bug in the recent kernels.

RESULTS

1525319681.3509254: port starts at 0

1525319684.8207247: port is now 1
1525319684.9523368: port is now 1
1525319685.0304863: port is now 1
1525319689.348844:  port is now 0
1525319689.4491622: port is now 1  <== this is the last thing HASS sees

1525319693.4145496: port ends at 0

CODE

#!/usr/bin/env python3

import RPi.GPIO as GPIO
import time

def read_gpio(port):
    print("{}: port is now {}".format(time.time(), GPIO.input(port)))

port      = 12
pull_mode = 'UP'
bounce    = 50

GPIO.setmode(GPIO.BCM)
GPIO.setup(port, GPIO.IN, GPIO.PUD_DOWN if pull_mode == 'DOWN' else GPIO.PUD_UP)
print("{}: port starts at {}".format(time.time(), GPIO.input(port)))
GPIO.add_event_detect(port, GPIO.BOTH, callback=read_gpio, bouncetime=bounce)
while True:
    try: time.sleep(1)
    except: break
print("{}: port ends at {}".format(time.time(), GPIO.input(port)))
GPIO.cleanup()
1 Like

It seems similar to an open ticket: https://sourceforge.net/p/raspberry-gpio-python/tickets/143/

Great detective work.

So who is responsible for actioning that ticket? It has been open since 2016.