MBaker
Posts: 1
Joined: Wed May 30, 2018 12:35 pm

How to stop multiple detection of button press?

Fri Jun 15, 2018 10:05 am

OK this is my 1st project. I have to take a contact closure and make it send an email. I have wired up a button using a pull down resistor. to protect the PI. My code is below but basically the email sends automatically and repeatedly without the contact closing. So some of this code is wrong and I know I also have to add event detection but when I do that the code doesn't run at all. Help please!!!

Code: Select all

import smtplib
from email.mime.text import MIMEText
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN)
print "close to send email"

while True:
        input = GPIO.input(23)
        if input == True:
            print "email sent"

            message = """Fault detected"""
            msg = MIMEText(message)
            msg['subject'] = 'Test'
            msg['from']='[email protected]'
            msg['to']='[email protected]'

            s = smtplib.SMTP('smtp.gmail.com' , '587')

            s.ehlo()
            s.starttls()
            s.ehlo()

            s.login('[email protected]' , 'toacttest-123')
            s.sendmail(msg['from'], msg['to'], msg.as_string())
            s.quit()

scotty101
Posts: 3597
Joined: Fri Jun 08, 2012 6:03 pm

Re: How to stop multiple detection?

Fri Jun 15, 2018 10:53 am

The first thing to try is a simple time.sleep(5) to delay the while loop for a few seconds after a single button press. This might be enough for your program.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

PiGraham
Posts: 3548
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How to stop multiple detection?

Fri Jun 15, 2018 11:04 am

If you record the time when a keypress occurs you can check how long it has been when the next keypress occurs. If it's too soon just ignore itelse just update the time

Paul_Di
Posts: 1
Joined: Fri Jun 15, 2018 11:01 am

Re: How to stop multiple detection?

Fri Jun 15, 2018 11:14 am

Use a variable to keep track if you have sent an email already... see code below. This will correct the issue.

Code: Select all

emailSent = false;
while True:
	input = GPIO.input(23)
	if input == True && emailSent == false:       

		message = """Fault detected"""
		msg = MIMEText(message)
		msg['subject'] = 'Test'
		msg['from']='[email protected]'
		msg['to']='[email protected]'
	
		s = smtplib.SMTP('smtp.gmail.com' , '587')
		s.ehlo()
		s.starttls()
		s.ehlo()
		s.login('[email protected]' , 'toacttest-123')
		s.sendmail(msg['from'], msg['to'], msg.as_string())
		s.quit()
		emailSent = true
		print "email sent"
		
	elif input == false:
		emailSent = false;

pksato
Posts: 295
Joined: Fri Aug 03, 2012 5:25 pm
Location: Brazil

Re: How to stop multiple detection?

Fri Jun 15, 2018 11:39 am

Hi,
You need to use debouncing to prevent multiple trigger.
A simple debouncing is to add a little delay after action (email sent).

Also have hardware debouncing methods, like a capacitor in parallel with switch.

A long wiring can act as electric field antenna and trigger the input, a capacitor from input to ground (or VCC) can used to prevent false trigger.

PiGraham
Posts: 3548
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How to stop multiple detection of button press?

Fri Jun 15, 2018 1:44 pm

Your code is only testing the current state. If you want one action when the button is presed to need to detect when the input changes state.

Code: Select all

        input = GPIO.input(23)
        if input == True:
            print "email sent"
The above will kep printing "email sent" over and over as long as the button is pressed.
You can track the previous state with a variable and do something only when the new state is True and the old state is False.
You can use the GPIOZero library button class which has some useful features.

Code: Select all

from gpiozero import Button

button = Button(2)

button.wait_for_press()
print("Button was pressed")
or using events:

Code: Select all

from gpiozero import Button
from signal import pause

def say_hello():
    print("Hello!")

button = Button(2)

button.when_pressed = say_hello

pause()
http://gpiozero.readthedocs.io/en/stabl ... tml#button

pcmanbob
Posts: 6191
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: How to stop multiple detection of button press?

Fri Jun 15, 2018 2:52 pm

Just be way of another example of how you can do this

Code: Select all

import smtplib
from email.mime.text import MIMEText
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN)
print "close to send email"

while True:
        # this while loop waits for input to = 1
        while GPIO.input(23) == 0:
            time.sleep (0.5)
            
        print "email sent"

        message = """Fault detected"""
        msg = MIMEText(message)
        msg['subject'] = 'Test'
        msg['from']='[email protected]'
        msg['to']='[email protected]'

        s = smtplib.SMTP('smtp.gmail.com' , '587')

        s.ehlo()
        s.starttls()
        s.ehlo()

        s.login('[email protected]' , 'toacttest-123')
        s.sendmail(msg['from'], msg['to'], msg.as_string())
        s.quit()

        # this while loop waits for input to = 0
        while GPIO.input(23) == 1:
            time.sleep (0.5)    
            
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

drgeoff
Posts: 9346
Joined: Wed Jan 25, 2012 6:39 pm

Re: How to stop multiple detection of button press?

Fri Jun 15, 2018 3:43 pm

MBaker wrote:
Fri Jun 15, 2018 10:05 am
I have wired up a button using a pull down resistor. to protect the PI.
The purpose of a pull-down (or pull-up) resistor is not to protect the RPi. It is to provide a defined voltage to the GPIO input when the switch is open.

pcmanbob
Posts: 6191
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: How to stop multiple detection of button press?

Fri Jun 15, 2018 3:57 pm

This has a good explanation as to why you need a pull up or pull down resistor .

https://github.com/raspberrypilearning/ ... up_down.md

it also shows you how to protect your pi gpio in the event you set the gpio pin to output and high while it is shorted to ground, using a 1K resistor.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

Return to “Beginners”