def run(self) -> None: self.was_held = False self.power_button = gpiozero.Button(self.POWER_PIN, pull_up=False, hold_time=0.03) self.power_button.when_released = self.__button_released self.power_button.when_held = self.__button_held
import chess import gpiozero import time import serial from collections import Counter import atexit import math #-----------------pin assignment------------------ #-------------------poll pins-------------- switch0 = gpiozero.Button(18, pull_up = False) switch1 = gpiozero.Button(4, pull_up = False) switch2 = gpiozero.Button(17, pull_up = False) switch3 = gpiozero.Button(27, pull_up = False) switch4 = gpiozero.Button(22, pull_up = False) switch5 = gpiozero.Button(6, pull_up = False) switch6 = gpiozero.Button(13, pull_up = False) switch7 = gpiozero.Button(19, pull_up = False) mux0 = gpiozero.LED(21) mux1 = gpiozero.LED(20) mux2 = gpiozero.LED(16) poll_select = [mux0, mux1, mux2] read_pins = [switch0, switch1, switch2, switch3, switch4, switch5, switch6, switch7] #poll_select = [gpiozero.LED(21), gpiozero.DigitalOutputDevice(20), gpiozero.DigitalOutputDevice(16)]
global cleared cleared = False points_new -= 10 counter = True def btn_reset(): global points_new global counter global cleared cleared = False points_new = 0 counter = False button1 = gpiozero.Button(btn1) button2 = gpiozero.Button(btn2) button3 = gpiozero.Button(btn3) button1.when_released = btn_plus button2.when_released = btn_minus button3.when_released = btn_reset class CardThread(threading.Thread): def __init__(self): super(CardThread, self).__init__() def run(self): while True: global id
Y_Constant = 500 Z_Constant = 500 X_Dir = zero.LED(10) X_Pulse = zero.LED(25) Y_Dir = zero.LED(9) Y_Pulse = zero.LED(8) Z_Dir = zero.LED(11) Z_Pulse = zero.LED(7) Planter_Dir = zero.LED(15) Planter_Pulse = zero.LED(18) Planter_Solenoid = zero.LED(23) Water_Solenoid = zero.LED(4) SDA = 2 SCL = 3 X_Stop_Low = zero.Button(6) X_Stop_High = zero.Button(13) Y_Stop_Low = zero.Button(19) Y_Stop_High = zero.Button(26) Z_Stop_Low = zero.Button(16) Z_Stop_High = zero.Button(20) def check_if_dry(): return 1 def water(): Water_Solenoid.on() print("watering plant") sleep(0.5)
# example of programming Raspberry Pi GPIO with gpiozero # refer to gpiozero.readthedocs.io import gpiozero as gpzero from time import sleep # set up pushbutton and bank of leds resetbutton = gpzero.Button(3) leds = gpzero.LEDBoard(26,16,20,21) # functions to control behavior def LightsOn (): while resetbutton.is_pressed: leds.on() def ResetCounter (): global counter leds.off() counter = 0 def binary2lights(showThis): leds.value = ( showThis & 0b1000, showThis & 0b0100, showThis & 0b0010, showThis & 0b0001) # setup button handlers resetbutton.when_pressed = LightsOn resetbutton.when_released = ResetCounter
def push1(): global lock print('push1') if lock.acquire(False): video() lock.release() lock = threading.Lock() led0 = aiy.leds.Leds() led1 = gpiozero.LED(aiy.pins.PIN_B) button0 = gpiozero.Button(23) button1 = gpiozero.Button(aiy.pins.PIN_A) button0.when_pressed = push0 button1.when_released = push1 camera = picamera.PiCamera(framerate=25) random.seed() led1.on() print('ready...') t0 = None
from neopixel import Adafruit_NeoPixel import gpiozero import time import RPi.GPIO as gpio # LEDs leftEye = gpiozero.LED(17) rightEye = gpiozero.LED(27) # Button button = gpiozero.Button(23) # LED strip configuration: LED_COUNT = 9 # Number of LED pixels. LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 5 # DMA channel to use for generating signal (try 5) LED_BRIGHTNESS = 128 # Set to 0 for darkest and 255 for brightest LED_CHANNEL = 0 # PWM channel LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) ws2812 = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) ws2812.begin() # LEDs def leftEyeOn(): leftEye.on()
import sys sys.path.append('..') from Tantallion import * import gpiozero as GPIO from signal import pause import time patch = Patch() room = patch.room('office') button1 = GPIO.Button(19, bounce_time=0.01) button2 = GPIO.Button(16, bounce_time=0.01) button3 = GPIO.Button(26, bounce_time=0.01) button4 = GPIO.Button(20, bounce_time=0.01) frankenstein = GPIO.Button(13) iterList = [0,0,0] naturalLooks = ['Copper', 'Burma', 'Snowy', 'Japanese', 'Sacred', 'Eternity'] saturatedLooks = ['Jelly', 'Vaporwave', 'Intersection', 'Eiffel', 'Valtari', 'Umbrella', 'Void'] contrastLooks = ['Toplight', 'Night', 'Cabinet'] naturalLooks = [scenes[x] for x in naturalLooks] saturatedLooks = [scenes[x] for x in saturatedLooks] contrastLooks = [scenes[x] for x in contrastLooks] def run1(): room.setArbitration('ButtonPress')
class Robot(): # back motors br = gpiozero.Motor(22, 27) # back right, connected to rpi BCM 27 and 22 bl = gpiozero.Motor(23, 24) # back left, connected to rpi BCM 23 and 24 # front motors fr = gpiozero.Motor(12, 16) # front right, connected to rpi BCM 12 and 16 fl = gpiozero.Motor(6, 5) # front left, connected to rpi BCM 6 and 5 opt = gpiozero.Button( 17 ) # opt is the optocoupler that is measuring encoder in back-left wheel, the encoder has 20 holes counter = 0 # variable needed to count up to the 20 holes in the step function print "created motors" def __init__(self): print "created class" def forward(self, speed=1): """ """ print "forward ", speed self.br.forward(speed) self.bl.forward(speed) self.fr.forward(speed) self.fl.forward(speed) def backward(self, speed=1): print "backward ", speed self.br.backward(speed) self.bl.backward(speed) self.fr.backward(speed) self.fl.backward(speed) def stop(self): print "stop" self.br.stop() self.bl.stop() self.fr.stop() self.fl.stop() def right(self, degrees=90): self.counter = 0 if degrees == 90: limit = 12 elif degrees == 180: limit = 24 elif degrees == 270: limit = 36 elif degrees == 360: limit = 48 else: limit = 12 def count_one(): self.counter = self.counter + 1 print " counter is ", self.counter if self.counter >= limit: # hardcoded number based on my current system self.stop() self.opt.when_pressed = count_one # Turning Right Movement self.fl.forward(1) self.bl.forward(1) self.fr.backward(1) self.br.backward(1) """ while self.counter < 10: sleep(1.0/1000000.0) self.stop() """ def left(self, degrees=90): self.counter = 0 if degrees == 90: limit = 12 elif degrees == 180: limit = 24 elif degrees == 270: limit = 36 elif degrees == 360: limit = 48 else: limit = 12 def count_one(): self.counter = self.counter + 1 print " counter is ", self.counter if self.counter >= limit: # hardcoded number based on my current system self.stop() self.opt.when_pressed = count_one self.fl.backward(1) self.bl.backward(1) self.fr.forward(1) self.br.forward(1) #sleep(1) #self.stop() def step(self, direction): self.counter = 0 def count_one(): self.counter = self.counter + 1 print " counter is ", self.counter, " - ", int(round(time() * 1000)) if self.counter >= 20: self.stop() self.opt.when_pressed = count_one if direction == "f": self.forward(1) elif direction == "b": self.backward(1) else: self.forward( 1 ) # for now the default is forward, this function may throw an error later """ while self.counter < 20: #sleep(1.0/1000000000.0) pass self.stop() """ def steps_forward(self, num_steps=1): for i in range(0, num_steps): self.step("f") def steps_backward(self, num_steps=1): for i in range(0, num_steps): self.step("b")
# encoding: utf-8 import gpiozero gumb = gpiozero.Button(22) zvok = gpiozero.Buzzer(4) while True: if gumb.is_pressed: zvok.on() if not gumb.is_pressed: zvok.off()
if not state["running"]: buzzer.off() enable_display(controls) logger.setLevel(logging.INFO) controls = initialise() set_brightness([0, 0, 0, 0, 0, 0, 0, 0], controls) enable_display(controls) state = { "motivation_mode": "normal", "running": False, } button1 = gpiozero.Button(2) button2 = gpiozero.Button(3) button3 = gpiozero.Button(4) button4 = gpiozero.Button(17) button5 = gpiozero.Button(27) buzzer = gpiozero.LED(24) button1.when_pressed = buzzer.on button1.when_released = buzzer.off button2.when_pressed = lambda: toggle_motivational_mode(controls, state) button3.when_pressed = lambda: set_target(state, controls, buzzer) button4.when_pressed = lambda: toggle_running(state, controls, buzzer)
def _setup_hardware(self): """ Create instances of all peripherals needed. """ self._button = gpiozero.Button(7,hold_time=2,hold_repeat=False,pull_up=True) self._button.when_pressed = self._on_button_press
def __init__(self, pin, callback): self.button = gpiozero.Button(pin) self.button.when_pressed = callback
import time from signal import pause import gpiozero def test(): print("hi") button = gpiozero.Button(4) button.when_activated = test pause()
def button_interrupts(): button = gz.Button(25) button.when_pressed = lambda: say_message("Press") button.when_released = lambda: say_message("Release") signal.pause()
#------------------------------------------ import time def timeNow(): return time.asctime()[11:19] #---------------------------------- bridge_to_D1 = blynk.bridge_widget( 40) # using our vpin 40 as our outgoing channel #------------------------------------ # our button -> their LED our_button4 = GPIO.Button(19) D1_blueled_gpio = 4 our_button4.when_pressed = lambda: bridge_to_D1.digital_write( D1_blueled_gpio, 1) our_button4.when_released = lambda: bridge_to_D1.digital_write( D1_blueled_gpio, 0) #----------------------------------- ourLed = GPIO.LED(20) # and D1 will send back a message to our vp65 on each D1 LED change (which we caused!). def xxx_h(value, pin, st): print("incoming: ", value[0]) ourLed.value = int(value[0][4]) # so we turn on OUR led too!
# set up GPIO hardware PIEZOPIN = 4 BUTTONPIN = 25 LEDPIN = 22 LED_RED_PIN = 23 buzzer = gpz.TonalBuzzer(PIEZOPIN) led = gpz.LED(LEDPIN) led_red = gpz.LED(LED_RED_PIN) rmotor = gpz.Motor(20, 16, 12, pwm=True) lmotor = gpz.Motor(26, 19, 5, pwm=True) lsensor = gpz.DistanceSensor(21, 24) # echo, trigger rsensor = gpz.DistanceSensor(13, 27) lsensor._queue.stop() # stop the auto-checking rsensor._queue.stop() # stop the auto-checking button = gpz.Button(BUTTONPIN, bounce_time=0.2) def beep(length=0.1, freq=500): buzzer.play(freq) time.sleep(length) buzzer.stop() def read_sensors(): # lsensor._read() # rsensor._read() return lsensor._read(), rsensor._read() def setspeed(motor, speed):
def __init__(self): self.cmdlin_params = sys.argv[1:] self.exitcode = 0 #self.videos_idle = ['/home/pi/Videos/Animationen_converted.mp4', # '/home/pi/Videos/Günter Grünwald - Saupreiß.mp4', # '/home/pi/Videos/Sprachprobleme im Biergarten.mp4', # '/home/pi/Videos/Der weiß-blaue Babystrampler.mp4', # ] #self.videos_idle = ['/home/pi/Videos/idle01.mp4', # '/home/pi/Videos/idle02.mp4', # '/home/pi/Videos/idle03.mp4', # '/home/pi/Videos/idle04.mp4', # '/home/pi/Videos/idle05.mp4', # '/home/pi/Videos/idle07.mp4', # '/home/pi/Videos/idle08.mp4', # '/home/pi/Videos/idle09.mp4'] # Test videos with durations from 0:03 to 0:22 # by www.studioschraut.de from vimeo: # Download them from https://vimeo.com/studioschraut self.videos_idle = [ '/home/pi/Videos/01_CD Promo on Vimeo.mp4', '/home/pi/Videos/02_WIDESCREEN SHOW Intro on Vimeo.mp4', #'/home/pi/Videos/03_Messe on Vimeo.mp4', '/home/pi/Videos/04_SFT SPOT TV Commercial on Vimeo.mp4', '/home/pi/Videos/05_Play Vanilla TV Spot on Vimeo.mp4' #, #'/home/pi/Videos/06_PCG PP Commercial on Vimeo.mp4' ] #self.videos_cntdn = ['/home/pi/Videos/Der weiß-blaue Babystrampler.mp4', # '/home/pi/Videos/Sprachprobleme im Biergarten.mp4'] self.videos_cntdn = [ '/home/pi/Videos/Disturbed_LandOfConfusion16s.mp4' ] self.videos_appl = ['/home/pi/Videos/AlanWalker_Spectre15s.mp4'] #self.videos_appl = ['/home/pi/Videos/applause00.mp4', # '/home/pi/Videos/applause01.mp4', # '/home/pi/Videos/applause02.mp4', # '/home/pi/Videos/applause03.mp4', # '/home/pi/Videos/applause04.mp4', # '/home/pi/Videos/applause05.mp4', # '/home/pi/Videos/applause06.mp4'] # Create three instances of omxplayer management: self.manage_instance = 0 self.pl = [None, None, None] self.pl[OMXINSTANCE_IDLE1] = VideoPlayer(OMXLAYER[OMXINSTANCE_IDLE1]) self.pl[OMXINSTANCE_IDLE2] = VideoPlayer(OMXLAYER[OMXINSTANCE_IDLE2]) self.pl[OMXINSTANCE_CNTDN] = VideoPlayer(OMXLAYER[OMXINSTANCE_CNTDN]) self.pl[OMXINSTANCE_IDLE1].fullscreen = '760,50,1720,590' # DEBUG! self.pl[OMXINSTANCE_IDLE2].fullscreen = '770,50,1730,590' # DEBUG! self.pl[OMXINSTANCE_CNTDN].fullscreen = '780,70,1740,610' # DEBUG! # GPIO access: self.gpio_buzzer = gpiozero.Button(17) # J8 pin 11 self.gpio_triggerpin = gpiozero.LED(7) # J8 pin 26 self.gpio_exitbtn = gpiozero.Button(23) # J8 pin 16 # Non-video properties: self.timeslot = 0.02 # todo: CMDLIN_PARAM self.randomindex_idle = 0 # -1 random selection 0 continuous selection self.randomindex_cntdn = 0 # -1 random selection 0 continuous selection self.randomindex_appl = 0 # -1 random selection 0 continuous selection # Initialisation of the state machine: self.errmsg = '' self.state = STATE_SELECT_IDLE_VIDEO self.buzzer_enabled = True
import gpiozero sys.path.append(CURRENT_DIR + 'libraries') if KeyboardActive: import keyboard ################################################################################ # ---------------------------------------------------------------------------- # ################################### MAIN ####################################### RootLockScreen = tk.Tk() LockImage = tk.PhotoImage(file=LockImagePath) setLockScreen(RootLockScreen, LockImage) RootLockScreen.withdraw() # Start hidden ## Lock screen triggers : keyboard + GPIO if KeyboardActive: keyboard.add_hotkey(LockKeys, toggleLockScreen, args=[RootLockScreen]) LockButton = gpiozero.Button(LockButtonNumber, pull_up=True, bounce_time=LockButtonBounceTime, hold_time=LockButtonHoldTime) LockButton.when_held = lambda: toggleLockScreen(RootLockScreen) RootLockScreen.mainloop()
stateFile = open(STATE_FILE_PATH, 'w') stateFile.write('Water Level Low!!') stateFile.close() notification("Water Level LOW!!") def water_level_hi(): print('water level hi') stateFile = open(STATE_FILE_PATH, 'w') stateFile.write('Water Level High :)') stateFile.close() notification("Water Level Hi :)") #main: level_input = gpiozero.Button(16, bounce_time=2.0) water_low = level_input.is_pressed if (water_low): water_level_low() else: water_level_hi() print('Initialized') debounce_count = 0 debounce_max = 3 while (True): new_input = level_input.is_pressed if water_low: #look for multiple consequtive new_input==False if new_input: #so we still see a water_low reading if (debounce_count > 0):
import rekognition import storage import database import draw import gpiozero import picamera import time ct = 50 image_file = '/tmp/image.jpg' button = gpiozero.Button(17) print("system ready...") while True: # speaker will emit a ready signal when the system is initialized # init celeb_result = None celeb_labels = [] # object is triggered by a mechanical action - button push if button.is_pressed: print("working...") # speaker emits a countdown # capture picture from camera camera = picamera.PiCamera() camera.capture(image_file) # upload picture to S3 s3 = storage.upload(image_file) # call rekognition apis # Step 1. Are there faces in the image? face_result = rekognition.detect_faces_api(s3) face_labels = rekognition.get_face_labels(face_result, ct)
import pygame import gpiozero import time pygame.mixer.init() channel = pygame.mixer.Channel(0) button_a = gpiozero.Button(2) track_a = pygame.mixer.Sound('samples/song.wav') channel.play(track_a, loops=-1) while True: if button_a.is_pressed: channel.set_volume(1) else: channel.set_volume(0)
def btn_listening(): """Listen to the button action all the time.""" btn = gpiozero.Button(21) btn.when_pressed = cb_btn_pressed signal.pause()
def predvajaj(i): led[i].on() zvok[i].play() time.sleep(1) led[i].off() led = [ gpiozero.LED(4), # modra gpiozero.LED(18), # rdeča gpiozero.LED(22), # oranžna gpiozero.LED(23) # zelena ] gumb = [ gpiozero.Button(13), # modra gpiozero.Button(16), # rdeča gpiozero.Button(19), # oranžna gpiozero.Button(20) # zelena ] zvok = [ pygame.mixer.Sound('blue.ogg'), # modra pygame.mixer.Sound('red.ogg'), # rdeča pygame.mixer.Sound('orange.ogg'), # oranžna pygame.mixer.Sound('green.ogg') # zelena ] while True: if gumb[0].is_pressed:
Y_Constant = 100 Z_Constant = 100 X_Dir = zero.LED(19) X_Pulse = zero.LED(22) Y_Dir = zero.LED(21) Y_Pulse = zero(24) Z_Dir = zero.LED(23) Z_Pulse = zero.LED(26) Planter_Dir = zero.LED(10) Planter_Pulse = zero.LED(12) Planter_Solenoid = zero.LED(16) Water_Solenoid = zero.LED(7) SDA = 3 SCL = 5 X_Stop_Low = zero.Button(31) X_Stop_High = zero.Button(33) Y_Stop_Low = zero.Button(35) Y_Stop_High = zero.Button(37) Z_Stop_Low = zero.Button(36) Z_Stop_High = zero.Button(38) def check_if_dry(): #Use I2C to get water sensor value. #Return value < Water_Constant. return 1 def water(): Water_Solenoid.on()
def move(self, step): self.current_index += step if self.current_index >= len(self.menu_items): self.current_index = 0 elif self.current_index < 0: self.current_index = len(self.menu_items) - 1 print "current index: %i" % self.current_index self.menu_items[self.current_index]() if __name__ == "__main__": rotary_btn = gpiozero.Button(6) rc = RotaryEncoder(19, 13) ui = Sensor_UI() rc.when_rotated = ui.rotary_changed while True: time.sleep(0.01) # ui.identify() # rotary_btn.wait_for_press() # ui.show_temp()
sekunden_leds = [0] sonstige_leds = [0] leer_leds = [0] rgbdict = self.rgb_farben_lesen() LOGGER.debug(f"stunden_leds: {stunden_leds}\n" f"minuten_leds: {minuten_leds}\n" f"sekunden_leds: {sekunden_leds}\n" f"leer_leds: {leer_leds}\n" f"sonstige_leds: {sonstige_leds}\n" f"rgbdict: {rgbdict}") led_setzen(stunden_leds, minuten_leds, sekunden_leds, leer_leds, sonstige_leds, rgbdict, self.pixels) # GPIO I_MODE_TASTER = gpiozero.Button(3) I_PLUS_TASTER = gpiozero.Button(4) I_MINUS_TASTER = gpiozero.Button(17) def config_schreiben(pfad=SKRIPTPFAD): configfile = os.path.join(pfad, "uhr_cfg.toml") with open(configfile, "w") as conffile: conffile.write(toml.dumps(CONFIG)) LOGGER.info(f"Schreibe Config: {CONFIG}") def alle_led(r, g, b, pixels): pixels.fill((r, g, b)) pixels.show()
##DOCUMENTATION: ###https://gpiozero.readthedocs.io/en/stable/api_input.html ##IMPORTS GO HERE import os #Gerenciamento de arquivos import gpiozero #GPIO nova, sensores import bluetooth #Bluetooth import subprocess #processamento paralelo, shell import json #output em json para servidor import time #time.sleep, time.time import threading #MultiThreading import Adafruit_DHT #DHT11 lib ##SETUP ###Input waterSensor = gpiozero.Button(pin=22, pull_up=False) ##WATER SENSOR AS BUTTON ldr=gpiozero.LightSensor(pin=21) ##LDR as LightSensor sensor=Adafruit_DHT.DHT11 ##DHT from Lib ###OUTPUT waterValve = gpiozero.OutputDevice(pin=23, active_high=True, initial_value=False) red=gpiozero.LED(4) ##RED MEANS STOP green=gpiozero.LED(17) ##GREEN MEANS GO blue=gpiozero.LED(24) ##BLUE MEANS CRY ###Variables #mac="10:3B:59:B1:B3:C8" #Endereço bluetooth android day, soil, ctrLogs = "Escuro", "Seco", 1#LDR, SoilSensor, LogCounter freq = 60 #Read Frequency lastdate, lasthour = "", "" #Last Irrigation data
import gpiozero # We are using GPIO pins import subprocess import os from time import sleep checkFile = "/dev/shm/no-openvpn" channel = 21 button = gpiozero.Button(channel) toggle = False togglerereaddelay = 1 cycledelay = .25 # Toggle False = Allow Openvpn (Remove /dev/shm/no-openvpn) # Toggle True = Stop Openvpn (Create /dev/shm/no-openvpn * kill openvpn --config processes) while True: if button.is_pressed: if lastButton == False: lastButton = True toggle = not toggle print("Flip Toggle to " + str(toggle)) if toggle: print("Disable OpenVPN") os.system("touch " + checkFile) os.system( "ps -ef | grep -v grep | grep \"openvpn --config\"| awk \'{print $2}\' | xargs kill >/dev/null 2>&1" ) sleep(togglerereaddelay) else: print("Enable OpenVPN") os.system("rm -f " + checkFile) sleep(togglerereaddelay)
import gpiozero as gp import tkinter as tk import time from tkinter import ttk S4 = gp.Button(24) #Binding Sensor Ldr3 = gp.LightSensor(19) #Case Feeder Buzzer = gp.PWMOutputDevice(18, frequency=6000) Relay2 = gp.OutputDevice(6, initial_value=False, active_high=True) Relay2.source = Ldr3 while True: pulsetime = 0 Ldr3.wait_for_light() time.sleep(0.1) while Ldr3.light_detected == True: time.sleep(0.2) pulsetime += 1 print(pulsetime) if pulsetime >= 15: Buzzer.pulse(n=1) if Ldr3.light_detected == False: Buzzer.off()