当前位置: 首页>>代码示例>>Python>>正文


Python gpiozero.Button类代码示例

本文整理汇总了Python中gpiozero.Button的典型用法代码示例。如果您正苦于以下问题:Python Button类的具体用法?Python Button怎么用?Python Button使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Button类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: HardwareController

class HardwareController(object):

    def __init__(self):

        self.button = Button(pin=BUTTON_PIN, hold_time=1, hold_repeat=True)
        self.status_led = LED(STATUS_LED_PIN)
        self.button_led = LED(BUTTON_LED_PIN)

        self.button.when_pressed = self.button_pressed
        self.button.when_released = self.button_released
        self.button.when_held = self.button_held
        self.hold_time = 0

        self.status_led.blink(on_time=0.1, off_time=0.1, n=5, background=False)
        self.status_led.on()

        return

    def close(self):

        self.button.close()
        self.button_led.close()
        self.status_led.close()

        return

    def button_held(self):

        logger.debug("button held")
        self.hold_time = self.button.active_time
        self.button_led.blink(on_time=0.25, off_time=0.1, n=1)

        return

    def button_pressed(self):

        logger.debug("button pressed")
        self.hold_time = 0

        return

    def button_released(self):

        increments = int(self.hold_time / BUTTON_HOLD_INCREMENTS)
        logger.debug("button released. Held for {0} increments".format(increments))

        if increments > 0:
            time.sleep(2)
            self.button_led.blink(on_time=0.5, off_time=0.5, n=increments, background=False)
            time.sleep(1)

            if increments == 1:
                logger.info("Shutdown called via button press")
                check_call(['sudo', 'poweroff'])
            elif increments == 2:
                logger.info("Reboot called via button press")
                check_call(['sudo', 'reboot'])

        return
开发者ID:nstoik,项目名称:farm_device,代码行数:59,代码来源:manager.py

示例2: shutdownButton

def shutdownButton():
    button_2 = Button(23, pull_up=True)
    button_2.wait_for_press()
    speak("Herrunterfahren...")
    time.sleep(3)
    quitThread()
    call("mpg123 -q snd/Robot_dying.mp3", shell=True)
    call("/sbin/poweroff &", shell=True)
开发者ID:buxit,项目名称:mot2bot,代码行数:8,代码来源:http-pi2kf.py

示例3: main

def main():
    """
    Main method.

    :return:
    """
    api = init_tweepy_api()
    photo_path = ""
    count = 1
    #while count > 0:
    
    button = Button(17)
    camera = PiCamera()
    camera.start_preview()
    while True:
	count -= 1
        try:
            #curtime, photo_name = click_camera_cli()
	    curtime = datetime.now()
            now = curtime.strftime('%Y%m%d-%H%M%S')
            photo_name = now + '.jpg'

            # Take a picture upon button press
	    print "Starting camera preview"
	    print "Is button pressed: " + str(button.is_pressed)
            button.wait_for_press()
	    print "Button pressed"
            photo_path = '/home/pi/' + photo_name
            camera.capture(photo_path)
	    print "Photo taken " + photo_path
            #camera.stop_preview()

            # Send the tweet with photo
	    print "Tweeting pic at : " + photo_path
            status = 'Photo auto-tweet from Smart Tree: ' + curtime.strftime('%Y/%m/%d %H:%M:%S')
            api.update_with_media(photo_path, status=status)
            sleep(10)
            # Delete pic after successful upload
            cleanup_pic(photo_path)
        except:
            # Catch all errors and continue looping
            print "Unexpected error:", sys.exc_info()
            cleanup_pic(photo_path)
开发者ID:shruti514,项目名称:SmartStreetUserApp-Commons,代码行数:43,代码来源:pressure_sensor_handler.py

示例4: main

def main():

    FLASH = flash.Flash(3)
    BUTTON = Button(14)

    while True:

        BUTTON.wait_for_press()

        print('Capturing...')

        fileName = 'image ' + datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') + '.png'

        FLASH.on()

        raspEYE.takePicture(fileName, sec=0, res=(1000, 750))

        FLASH.off()

        print('Finished')
开发者ID:oodeagleoo,项目名称:raspEYE,代码行数:20,代码来源:buttonCamera.py

示例5: __init__

    def __init__(self):

        self.button = Button(pin=BUTTON_PIN, hold_time=1, hold_repeat=True)
        self.status_led = LED(STATUS_LED_PIN)
        self.button_led = LED(BUTTON_LED_PIN)

        self.button.when_pressed = self.button_pressed
        self.button.when_released = self.button_released
        self.button.when_held = self.button_held
        self.hold_time = 0

        self.status_led.blink(on_time=0.1, off_time=0.1, n=5, background=False)
        self.status_led.on()

        return
开发者ID:nstoik,项目名称:farm_device,代码行数:15,代码来源:manager.py

示例6: main

def main():
    button = Button(5)

    red=LED(2)
    amber=LED(17)
    green=LED(11)

    button.wait_for_press()

    red.on()
    amber.on()
    green.on()

    with PiCamera() as camera:  
        timestamp = datetime.now().isoformat()
        photo_path = '/home/pi/push-button-photo/photos/%s.jpg' % timestamp
        camera.start_preview()
        sleep(1)
        red.off()
        amber.on()
        green.on()
        sleep(1)
        red.off()
        amber.off()
        green.on()
        sleep(1)
        red.off()
        amber.off()
        green.off()
        camera.capture(photo_path)
        camera.stop_preview()

    message = "I have been taking photos with code..."
    with open(photo_path, 'rb') as photo:
        twitter.update_status_with_media(status=message, media=photo)
    print("Tweeted: %s" % message)
开发者ID:LornaLynch,项目名称:Push-Button-Photo,代码行数:36,代码来源:push-button-photo.py

示例7: Button

import os
from gpiozero import Button
from signal import pause
button = Button(4,pull_up=False)

def pressed(button):
    print("Pin %s pressed. The system is going to try shutdown now!" % button.pin)
    os.system("shutdown now -h")

button.when_pressed = pressed
pause()
开发者ID:lsa-pucrs,项目名称:donnie-assistive-robot-sw,代码行数:11,代码来源:softshutdown.py

示例8: LED

import time
import os
import subprocess
import Adafruit_Nokia_LCD as LCD
import Adafruit_GPIO.SPI as SPI
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from gpiozero import LED,Button
from picamera import PiCamera

yellow = LED(16)
button = Button(15)
dropbox = Button(21)
led_drop = LED(20)
stop = Button(26)
# Raspberry Pi hardware SPI config:
DC = 23
RST = 24
SPI_PORT = 0
SPI_DEVICE = 0


# Hardware SPI usage:
disp = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000))

# Software SPI usage (defaults to bit-bang SPI interface):
#disp = LCD.PCD8544(DC, RST, SCLK, DIN, CS)

# Initialize library.
disp.begin(contrast=40
开发者ID:uktechreviews,项目名称:motion_cam,代码行数:31,代码来源:drop_cam2.py

示例9: Bridge

from phue import Bridge
import logging

import thread

logging.basicConfig()

lightrunning = {1:False, 2:False, 3:False}

b = Bridge('192.168.1.178', 'YxPYRWNawywC-sKHkjuRho7iOwMMSrn3di2ETF74')  # Enter bridge IP here.

lights = b.get_light_objects()

led = LED(27)
button1 = Button(17, pull_up=False)
button2 = Button(18, pull_up=False)


class light_status():

    def __init__(self):

        self.light1_status = 0
        self.light2_status = 0
        self.light3_status = 0
        self.light4_status = 0
        self.light5_status = 0
        self.light6_status = 0

ls = light_status()
开发者ID:wrxavex,项目名称:Omron_D6T,代码行数:30,代码来源:new_pir_fly.py

示例10: shutdown

from gpiozero import Button
from subprocess import check_call
from signal import pause

def shutdown():
    check_call(['sudo', 'poweroff'])

shutdown_btn = Button(17, hold_time=2)
shutdown_btn.when_held = shutdown

pause()
开发者ID:DirkUK,项目名称:python-gpiozero,代码行数:11,代码来源:button_shutdown.py

示例11: RGBLED

            # wait for two triggers again
            self.waitForOtherSensor = True
        else:
            # Now we have detected one trigger lets just wait for one more
            self.waitForOtherSensor = False


if __name__ == "__main__":
    try:
        # Initialize RGB_LED
        rgbLed = RGBLED(RGB_RED_PIN, RGB_GREEN_PIN, RGB_BLUE_PIN, False)

        # Initialize the Pitch Button - this is used to start the timer. If a
        # ball or strike is not detected in time x after the button press the
        # pitch is considered a ball.
        pitchButton = Button(PITCH_BUTTON_PIN)

        # Create instance of StrikeZone
        detectZone = StrikeZone()

        #Now initialize sensors
        for index, horizPin in enumerate(HORIZ_GPIO_PINS):
            horizSensors.append(LightSensor(horizPin, 
                                            queue_len = QUEUE_LEN,
                                            charge_time_limit = CHARGE_TIME))
            horizSensors[index].when_dark = detectZone.horizDark 
            horizSensors[index].when_light = detectZone.horizLight 
        for index, vertPin in enumerate(VERT_GPIO_PINS):
            vertSensors.append(LightSensor(vertPin, 
                                           queue_len = QUEUE_LEN,
                                           charge_time_limit = CHARGE_TIME))
开发者ID:Lennster,项目名称:baseball-strikezone-detector,代码行数:31,代码来源:XxY_LDR_strikezone.py

示例12: int

import pygame.mixer
from pygame.mixer import Sound
from gpiozero import Button
from signal import pause
from time import sleep

pin = int(input("pin:\t"))
pygame.mixer.init()

button = Button(pin)
drum = Sound("samples/drum_tom_mid_hard.wav")
while True:
    button.wait_for_press()
    print("button pressed")
    drum.play()
    sleep(0.1)
    button.wait_for_release()	
开发者ID:giosoft,项目名称:Pi_Python,代码行数:17,代码来源:musicbox.py

示例13: LED

from gpiozero import Button, LED
from time import sleep

led = LED(17)
button = Button(3)

delay = 1.0

def blink_fast():
    global delay
    delay = 0.1

def blink_slow():
    global delay
    delay = 1.0
    
button.when_pressed = blink_fast
button.when_released = blink_slow

while True:
    sleep(delay)
    led.on()
    sleep(delay)
    led.off()
开发者ID:VectorSpaceHQ,项目名称:Raspberry-Pi-Workshop,代码行数:24,代码来源:button_blink_rate.py

示例14: water_high

from gpiozero import Button
from signal import pause
import arrow

def water_high():
    print("Water High!")
    utc = arrow.utcnow()
    utc_local = utc.to('local')
    print("UTC time  - Water lever changed HIGH - at: {}".format(utc))
    print("Local time - Water level changed HIGH - at: {}".format(utc_local))



def water_low():
    print("Water Low!")
    utc = arrow.utcnow()
    utc_local = utc.to('local')
    print("UTC time  - Water lever changed LOW - at: {}".format(utc))
    print("Local time - Water level changed LOW - at: {}".format(utc_local))


button = Button(2)
button.when_pressed = water_high
button.when_released = water_low
print('*** Water Level Sensor Started ***')

pause()
print('..Running..')


开发者ID:TizenTeam,项目名称:WaterMonitor_IoT_PWA,代码行数:28,代码来源:water_callback.py

示例15: LED

from gpiozero import LED
from gpiozero import Button
from gpiozero import Buzzer
import time

life1 = LED(17)
life2 = LED(27)
life3 = LED(22)
buzzer = Buzzer(10)
tool = Button(9)

def life_counter(lives):
    if lives == 3:
        life1.on()
        life2.on()
        life3.on()
    elif lives == 2:
        life1.on()
        life2.on()
        life3.off()
    elif lives == 1:
        life1.on()
        life2.off()
        life3.off()
    elif lives == 0:
        life1.off()
        life2.off()
        life3.off()

lives = 3
life_counter(lives)
开发者ID:lesp,项目名称:LV24-Dr-Robot,代码行数:31,代码来源:Dr-Robot-GPIO-Zero.py


注:本文中的gpiozero.Button类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。