Python gpiozero.Button() Examples

The following are 16 code examples of gpiozero.Button(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gpiozero , or try the search function .
Example #1
Source File: main.py    From satellite_tracker with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        self.led_queue = mp.Queue()
        self.demo_mode = mp.Lock()

        self.led_process = mp.Process(target=led_control, args=(self.led_queue, self.demo_mode,))

        self.shutting_down = False
        self.last_button_release = 0
        self.show_end_of_lines = False

        # The button has multiple functions:
        # Turn the device on when off, single press to show the end of long lines on the display,
        # double press to start demo mode, single press to stay at one animation in demo mode,
        # long press to shut down
        self.button = Button(3, hold_time=2, bounce_time=0.05)
        self.button.when_held = self.shutdown
        self.button.when_released = self.button_pressed

        self.tft = SattrackerTFT()

        self.tle_updated_time = None

        self.tracker = None  # load in start because it takes quite a long time

        self.led_array = led_array_from_constants() 
Example #2
Source File: binaryio.py    From bacpypes with MIT License 6 votes vote down vote up
def ReadProperty(self, obj, arrayIndex=None):
        if _debug:
            BIPresentValue._debug("ReadProperty %r arrayIndex=%r", obj, arrayIndex)

        # access an array
        if arrayIndex is not None:
            raise ExecutionError(
                errorClass="property", errorCode="propertyIsNotAnArray"
            )
        

        ###TODO: obj._button is the Button object
        
        if _debug:
            BIPresentValue._debug("    - read button: %r", obj._button)

        if obj._button.is_pressed:
            return "active"
        
        else:
            return "inactive" 
Example #3
Source File: ch_16_web_control.py    From raspberrypi_cookbook_ed3 with MIT License 6 votes vote down vote up
def index(led_number="n"):
    if led_number != "n":
        leds[int(led_number)].toggle()
    response = "<script>"
    response += "function changed(led)"
    response += "{"
    response += "  window.location.href='/' + led"
    response += "}"
    response += "</script>"
    
    response += '<h1>GPIO Control</h1>'
    response += '<h2>Button=' + switch_status() + '</h2>'
    response += '<h2>LEDs</h2>'
    response += html_for_led(0) 
    response += html_for_led(1) 
    response += html_for_led(2) 
    return response 
Example #4
Source File: watcher_button.py    From Pigrow with GNU General Public License v3.0 6 votes vote down vote up
def listen(gpio_num, log_path, *args):
    button = Button(gpio_num)

    def pressed():
         #print( " Button Pressed " )
         listen.press_start = time.time()

    def released():
        #print( " Button released " )
        listen.press_end = time.time()

    button.wait_for_press()
    pressed()
    button.wait_for_release()
    released()
    duration = listen.press_end - listen.press_start
    print(duration)
    log_button_presss(log_path, duration) 
Example #5
Source File: buttons.py    From scroll-phat-hd with MIT License 5 votes vote down vote up
def pressed(button):
    button_name = button_map[button.pin.number]
    print(f"Button {button_name} pressed!") 
Example #6
Source File: button-splash.py    From scroll-phat-hd with MIT License 5 votes vote down vote up
def pressed(button):
    global splash_origin, splash_time
    button_name, x, y = button_map[button.pin.number]
    splash_origin = (x, y)
    splash_time = time.time()
    print(f"Button {button_name} pressed!") 
Example #7
Source File: binaryio.py    From bacpypes with MIT License 5 votes vote down vote up
def __init__(self, button_id, **kwargs):
        if _debug:
            RPiBinaryInput._debug("__init__ %r %r", button_id, kwargs)
        BinaryInputObject.__init__(self, **kwargs)

        # create a button object
        self._button = Button(button_id)


#
#   BOPresentValue
# 
Example #8
Source File: binaryio.py    From bacpypes with MIT License 5 votes vote down vote up
def WriteProperty(self, obj, value, arrayIndex=None, priority=None, direct=False):
        if _debug:
            BOPresentValue._debug(
                "WriteProperty %r %r arrayIndex=%r priority=%r direct=%r",
                obj,
                value,
                arrayIndex,
                priority,
                direct,
            )

        # access an array
        if arrayIndex is not None:
            raise ExecutionError(
                errorClass="property", errorCode="propertyIsNotAnArray"
            )

        ###TODO: obj._button is the Button object
        if _debug:
            BOPresentValue._debug("    - write led: %r", obj._led)

        #raise ExecutionError(errorClass="property", errorCode="writeAccessDenied")

        if value == "active":
            obj._led.on()
        elif value == "inactive":
            obj._led.off()
        else:
            ### TODO: insert correct value error. Below is a placeholder.
            print("invalid value for led. Use 'active' to turn on or 'inactive' to turn off.")


#
#   RPiBinaryOutput
# 
Example #9
Source File: __init__.py    From photobooth with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self):

        super().__init__()

        import gpiozero
        self.LED = gpiozero.LED
        self.RGBLED = gpiozero.RGBLED
        self.Button = gpiozero.Button
        self.GPIOPinInUse = gpiozero.GPIOPinInUse

        self._buttons = []
        self._lamps = []
        self._rgb = [] 
Example #10
Source File: __init__.py    From photobooth with GNU Affero General Public License v3.0 5 votes vote down vote up
def setButton(self, bcm_pin, handler):

        try:
            self._buttons.append(self.Button(bcm_pin))
            self._buttons[-1].when_pressed = handler
        except self.GPIOPinInUse:
            logging.error('Pin {} already in use!'.format(bcm_pin)) 
Example #11
Source File: ch_12_switch_2.py    From raspberrypi_cookbook_ed3 with MIT License 5 votes vote down vote up
def do_stuff():
    print("Button Pressed") 
Example #12
Source File: button_utils.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def accept_button_callback():
	global button_input_received

	accept_button_callback_logger = logging.getLogger('button_utils.accept_button_callback')

	accept_button_callback_logger.info("$$$$$$$$$$$$$$ Accept Button was pushed! $$$$$$$$$$$$$$")
	button_input_received = config.__ACCEPT_INPUT__
	accept_button_callback_logger.info("All done with the button callback!")

	return 
Example #13
Source File: button_utils.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def choice_button_callback():
	global button_input_received

	choice_button_callback_logger = logging.getLogger('button_utils.choice_button_callback')

	choice_button_callback_logger.info("############### Choice Button was pushed! #################")
	button_input_received = config.__CHOOSE_AGAIN__

	choice_button_callback_logger.info("All done with the button callback!")

	return 
Example #14
Source File: binaryio.py    From bacpypes with MIT License 4 votes vote down vote up
def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

    if _debug:
        _log.debug("initialization")
    if _debug:
        _log.debug("    - args: %r", args)

    # make a device object
    this_device = LocalDeviceObject(
        objectName=args.ini.objectname,
        objectIdentifier=("device", int(args.ini.objectidentifier)),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
    )

    # make a sample application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # make the buttons
    for button_id, bio_id in button_list:
        bio = RPiBinaryInput(
            button_id,
            objectIdentifier=("binaryInput", bio_id),
            objectName="Button-%d" % (button_id,),
        )
        _log.debug("    - bio: %r", bio)
        this_application.add_object(bio)

    # make the LEDs
    for led_id, boo_id in led_list:
        boo = RPiBinaryOutput(
            led_id,
            objectIdentifier=("binaryOutput", boo_id),
            objectName="LED-%d" % (led_id,),
        )
        _log.debug("    - boo: %r", boo)
        this_application.add_object(boo)

    _log.debug("running")

    run()

    _log.debug("fini") 
Example #15
Source File: 7-TrafficLights.py    From EduKit1 with MIT License 4 votes vote down vote up
def startgreen():
    # Remember all code in the function is indented

# Turn the green off and the amber on for 3 seconds
# ('Pedestrian' red LED stays lit)
def steadyamber():
    # Remember all code in the function is indented

# Turn the amber off, and then the red on for 1 second
def steadyred():
    # Remember all code in the function is indented

# Sound the buzzer for 4 seconds
# (If you have the 'pedestrian' LEDs, turn the red off and green on)
def startwalking():
    # Make the buzzer buzz on and off, half a second of
    # sound followed by half a second of silence

# Turn the buzzer off and wait for 2 seconds
# (If you have a second green 'pedestrian' LED, make it flash on and
# off for the two seconds)
def dontwalk():
    # Remember all code in the function is indented

# Flash the amber on and off for 6 seconds
# (And the green 'pedestrian' LED too)
def flashingambergreen():
    # Remember all code in the function is indented

# Flash the amber for one more second
# (Turn the green 'pedestrian' LED off and the red on)
def flashingamber():
    # Remember all code in the function is indented

# Go through the traffic light sequence by calling each function
# one after the other.
def trafficlightqequence():
    # Remember all code in the function is indented

os.system('clear')  # Clears the terminal
print("Traffic Lights")
# Initialise the traffic lights
startgreen()

# Here is the loop that waits at lease 20 seconds before
# stopping the cars if the button has been pressed
while True:  # Loop around forever
    buttonnotpressed = True  # Button has not been pressed
    start = time.time()  # Records the current time
    while buttonnotpressed:  # While the button has not been pressed
        time.sleep(0.1)  # Wait for 0.1s
        if button.ispressed:  # If the button is pressed
            now = time.time()
            buttonnotpressed = False  # Button has been pressed
            if (now - start) <= 20:  # If under 20 seconds
                time.sleep(20 - (now - start))  # Wait until 20s is up
                trafficlightqequence()  # Run the traffic light sequence 
Example #16
Source File: button_utils.py    From aws-builders-fair-projects with Apache License 2.0 4 votes vote down vote up
def button_handler(wait_delay=60, accept_led=None, choice_led=None, green_button_text="for Accept", yellow_button_text="for more choice"):

	global button_input_received

	button_utils_logger = logging.getLogger('button_.button_handler')
	button_input_received = False

	if not test_environment:
		accept_button = Button(config.__GREEN_BUTTON__)
		accept_button.when_pressed = accept_button_callback
		choice_button = Button(config.__YELLOW_BUTTON__)
		choice_button.when_pressed = choice_button_callback

	button_utils_logger.info("Go ahead and press the appropriate button. ")

	profile_prompt = "Push Green button %s or Yellow button %s." % (green_button_text, yellow_button_text)
	if (green_button_text =="for Accept") and (yellow_button_text=="for more choice"):
		speech_file_name = "push_green_accept_yellow_choice.mp3"
	else:
		fname = profile_prompt.replace(" ", "_")
		fname = fname.replace(".", "")
		speech_file_name = "%s.mp3" % fname

	speech_file_path = generate_audio(speech_text=profile_prompt, filename=speech_file_name)
	button_utils_logger.info("Generated Audio now. Playing audio next: ")
	play_audio(file_path=speech_file_path)
	button_utils_logger.info("Audio played. Done!")

	while (wait_delay and (not button_input_received)):
		button_utils_logger.info("In button thread: waiting for button input")
		sleep(10)
		wait_delay -= 10

	if button_input_received:
		button_utils_logger.info("Button input was received successfully: %d" % button_input_received)
	else:
		button_utils_logger.info("No button press detected!")

		profile_prompt = "No button press was detected. Defaulting to an accept now."
		speech_file_path = generate_audio(speech_text=profile_prompt, filename="no_button_press_was_detected.mp3")
		play_audio(file_path=speech_file_path)

		button_input_received = 1

	if not test_environment:
		if button_input_received == 1:
			if accept_led:
				accept_led.on()
				choice_led.off()
		elif button_input_received == 2:
			if choice_led:
				choice_led.on()
				accept_led.off()

	if not test_environment:
		accept_button.close()
		choice_button.close()

	button_utils_logger.info("Done with button_handler.")

	return button_input_received