Search code examples
python-3.xraspberry-pigpio

button.when_pressed is activated before actually pressing the button


from twython import Twython
from time import sleep
from gpiozero import LED, Buzzer, InputDevice, Button
import RPi.GPIO as GPIO
import sys
import Adafruit_DHT
from signal import pause
import mysql.connector


GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(13,GPIO.OUT)
no_rain = InputDevice(18)

bz = Buzzer(19)

n = True

led = LED(23)
button = Button(13, pull_up=False)



def printstate():
 print("pressed")

n = True

if no_rain.is_active:
 bz.off()
 while n == True:
      if no_rain.is_active:
          print("It's raining, get your clothes out.")  
              #bz.off
          ledON()
          humidity, temperature = Adafruit_DHT.read_retry(11, 17)
          print('Temp: {:.1f} C'.format(temperature))
              print('Humidity: {:.1f}'.format(humidity))
          n = False

button.when_pressed = printstate()




pause()

button.when_pressed is registered as pressed even though i didn't actually press the button on my GPIO raspberry pi.

Tried both released and pressed, Is there anyway for me use to button to stop the buzzer from buzzing?

The buzzer is buzzing even though the program ended.


Solution

  • button.when_pressed expects a function, but you assign it the function response. I.e. the function is called when you assign it, instead of when the button is pressed.

    If you change the function to return something other than None you will probably get an exception when pressing the button also. Making the mistake a bit more noticable.

    Change it to:

    button.when_pressed = printstate  # without the parentheses