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
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)
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)
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')
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 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)
from gpiozero import Button, LED from signal import pause from time import sleep print("Starting the sensor") engageSensor = LED(21) pir = Button(20) engageSensor.on() while True: print(f'running ${pir.is_pressed}') sleep(1) # led = LED(26) # pir.wait_for_motion() # print("Motion detected!")
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()
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
from gpiozero import Button import time from signal import pause import picamera mygtukas = Button(2) with picamera.PiCamera() as camera: camera.resolution = (200, 200) time.sleep(2) mygtukas.when_pressed = camera.capture('image.jpg')
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()
#!/usr/bin/env python3 import sys import signal from pybleno import * from demo_service import * from gpiozero import Button, RGBLED from time import sleep led = RGBLED(17,27,22, active_high=False) button = Button(4) bleno = Bleno() name = 'Demo' demoService = DemoService(led, button) def onStateChange(state): if (state == 'poweredOn'): bleno.startAdvertising(name, [demoService.uuid], on_start_advertising) else: bleno.stopAdvertising(); bleno.on('stateChange', onStateChange) def on_start_advertising(err): if err: print(err) def on_advertising_start(error): if not error: print('advertising...')
import paho.mqtt.client as mqtt from gpiozero import Button from signal import pause button = Button(4) client = mqtt.Client() client.connect("broker.hivemq.com", 1883, 60) from geo import getLocation def button_press(): print("button clicked") client.publish("text/all", "ALERT !! Koforidua, Eastern Region, Ghana" + getLocation()) button.when_pressed = button_press pause()
setTextLCD('Ready to accept', 'commands') def setTextLCD(top=None, bottom=None): global lcd lcd.clear() if top: lcd.text(top, 1) if bottom: lcd.text(bottom, 2) lcd = LCD() setTextLCD('Loading...') mqttClient = getMQTTClient() record = None button = Button(button_pin, pull_up=False) button.when_pressed = buttonPressed button.when_released = buttonReleased ready() try: pause() except KeyboardInterrupt: lcd.clear()
#!/usr/bin/python3 # Script name: TrafficLight.py # Uses the red yellow and green LEDs to simulate a road traffic light # # MGB # 2019-10-10 from gpiozero import LED, Button #Using gpiozero library from time import sleep #Use sleep funtion for timing, time is in seconds grn_led=LED(17) # Assign pin 17 to the green led. yel_led=LED(18) # Assign pin 18 to the yellow led. red_led=LED(19) # Assign pin 19 to the red led. blu_led=LED(20) # Assign pin 20 to the blue led. pb1=Button(21) # Assign pin 21 to push button 1. print("Traffic Light simulation programme") while True: # Run util stopped by keyboard interrupt....Ctrl + C red.on() # Turn LED ON, set output pin to +3.3v sleep(4) # Wait 3 seconds yel_led.on() # Repeat for the other LEDs sleep(1) red_led.off() yel_led.off() grn_led.on() sleep(4) grn_led.off() yel_led.on() sleep(1.5)
# -*- coding: utf-8 -*- from gpiozero import Button import time, syslog import os syslog.openlog(facility=syslog.LOG_KERN) stopButton = Button(23) # defines the button as an object and chooses GPIO 23 while True: if stopButton.is_pressed: time.sleep(1) if stopButton.is_pressed: syslog.syslog(syslog.LOG_ALERT, "shutdown pressed") os.system("shutdown now -h") time.sleep(1)
from time import sleep from gpiozero import Button, LED from DCBLP import T t0 = T() t1 = T() t2 = T() tlacitko = Button(21) # v závorkách jsou čísla pinů led1 = LED(20) led2 = LED(16) led3 = LED(26) reset = 1 while True: Y0 = t0.runTr(tlacitko.value, reset)[0] # value vrací hodnotu tlačítka, pokud zmáčknuté tak je 1 Y1 = t1.runTr(Y0, reset)[0] Y2 = t2.runTr(Y1, reset)[0] led1.value = Y2 # value u LED svítí, když je 1 led2.value = Y1 led3.value = Y0 reset = not (not Y2 and Y1 and not Y0) print(reset) sleep(.05)
pin_B = LED(PIN_B) pin_C = LED(PIN_C) # Initialize the buzzer ready = [ 'C6q', 'G5q', 'E5q', 'C5q', ] player = aiy.toneplayer.TonePlayer(22) player.play(*ready) # Initialize the button (on the top of AIY Google Vision box) button = Button(BUTTON_GPIO_PIN) # Initialize LED (in the button on the top of AIY Google Vision box) leds = Leds() leds.update(Leds.rgb_off()) # Global variables input_img_width = 1640 input_img_height = 1232 output_img_size = 160 faces_buffer_size = 40 hand_gesture_buffer_size = 5 threshold = 0.6 # Length of long buffer (to make a decision to de/activate app) # and short buffer (to declare a specific hand gesture command)
from gpiozero import LED, Button from signal import pause led = LED(23) button = Button(2) button.when_pressed = led.on button.when_released = led.off pause()
Future Improvements: - To add a temperature and humidity sensor for better monitoring √ - To create software over a network for remote access to the system changing motor timing and light timing as well as send information on humdity and temperature. For more information please check the wiki. """ import time import RPi.GPIO as GPIO from gpiozero import LED, Button #GPIO pins motor = LED(4) lights = LED(23) ONOFF_Button = Button(21) motorTime_Button = Button(5) lightTime_Button = Button(25) start = False #when button is pressed to begin #light times hrs15 = 54000.00, hrs12 = 43200.00, hrs13 = 46800.00, , hr = 3600 #light time default is 13 hrs hrs = 46800.00 #motor times default is 1 min on and 4 minutes off tMotorOn = 60.00 tMotorOff = 240.00 #increments of 30 seconds motorTime = 0 currentTime = 0 LEDTime = 0 hrs24 = 86400.00
from gpiozero import Button from picamera import PiCamera from datetime import datetime from signal import pause button = Button(2) camera = PiCamera() def capture(): timestamp = datetime.now().isoformat() camera.capture('/home/pi/%s.jpg' % timestamp) button.when_pressed = capture pause()
# # Unpark script for INDI Dome Scripting Gateway # Based on github.com/fenriques/indi/blob/master/libindi/drivers/dome/dome_script.txt # # # The default folder is /usr/share/indi/scripts. # Exit code: 0 for success, 1 for failure # from gpiozero import Button import time import libioplus import sys # assign roof_open_switch to read on GPIO pin 13, other wire attached to ground roof_open_switch = Button(13) # assign roof_closed_switch to read on GPIO pin 21, other wire attached to ground roof_closed_switch = Button(21) # assign motor_relay to relay #4 on the Sequent Microsystems home automation 8 relay hat motor_relay = 4 # assign hat_stack to 0, which is the first relay hat (you can have multiple hats stacked up) hat_stack = 0 # assign relay on/off in english relay_on = 1 relay_off = 0 # pulse the motor relay on, then off again to start the Aleko AR900 motor cycle def pulse_motor(): libioplus.setRelayCh(hat_stack, motor_relay, relay_on) time.sleep(0.8)
def main(): global page global sd_image_version global r # Initialise some redis variables r.set("gsm:active", 0) r.set("wlan:active", 0) r.set("eth:active", 0) # First set up logging atexit.register(logging.shutdown) if not uselogfile: loghandler = logging.StreamHandler() else: logfile = "/var/log/emonpilcd/emonpilcd.log" print("emonPiLCD logging to:", logfile) loghandler = logging.handlers.RotatingFileHandler(logfile, mode='a', maxBytes=1000 * 1024, backupCount=1, ) loghandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger.addHandler(loghandler) logger.setLevel(logging.INFO) logger.info("Starting emonPiLCD V" + version) # Now check the LCD and initialise the object global lcd lcd = LCD(logger) lcd.backlight = 1 # ------------------------------------------------------------------------------------ # Discover & display emonPi SD card image version # ------------------------------------------------------------------------------------ sd_card_image = subprocess.call("ls /boot | grep emonSD", shell=True) if not sd_card_image: # if emonSD file exists sd_image_version = subprocess.check_output("ls /boot | grep emonSD", shell=True) else: sd_card_image = subprocess.call("ls /boot | grep emonpi", shell=True) if not sd_card_image: sd_image_version = subprocess.check_output("ls /boot | grep emonpi", shell=True) else: sd_image_version = "N/A " sd_image_version = sd_image_version.rstrip() lcd[0] = "emonPi Build:" lcd[1] = sd_image_version logger.info("SD card image build version: " + sd_image_version) # Set up the buttons and install handlers # emonPi LCD push button Pin 16 GPIO 23 # Uses gpiozero library to handle short and long press https://gpiozero.readthedocs.io/en/stable/api_input.html?highlight=button # push_btn = Button(23, pull_up=False, hold_time=5, bounce_time=0.1) # No bounce time increases response time but may result in switch bouncing... logger.info("Attaching push button interrupt...") try: push_btn = Button(23, pull_up=False, hold_time=5) push_btn.when_pressed = buttonPress push_btn.when_held = buttonPressLong except: logger.error("Failed to attach LCD push button interrupt...") logger.info("Attaching shutdown button interrupt...") try: shut_btn = Button(17, pull_up=False, hold_time=5) shut_btn.when_pressed = preShutdown shut_btn.when_held = shutdown except: logger.error("Failed to attach shutdown button interrupt...") logger.info("Connecting to redis server...") # We wait here until redis has successfully started up while True: try: r.client_list() break except redis.ConnectionError: logger.error("waiting for redis-server to start...") time.sleep(1.0) logger.info("Connected to redis") logger.info("Connecting to MQTT Server: " + mqtt_host + " on port: " + str(mqtt_port) + " with user: "******"feed1", msg.payload) if mqtt_feed2_topic in msg.topic: r.set("feed2", msg.payload) if mqtt_emonpi_topic in msg.topic: r.set("basedata", msg.payload) def on_connect(client, userdata, flags, rc): if rc == 0: mqttc.subscribe(mqtt_emonpi_topic) mqttc.subscribe(mqtt_feed1_topic) mqttc.subscribe(mqtt_feed2_topic) mqttc = mqtt.Client() mqttc.on_message = on_message mqttc.on_connect = on_connect try: mqttc.username_pw_set(mqtt_user, mqtt_passwd) mqttc.reconnect_delay_set(min_delay=1, max_delay=120) mqttc.connect_async(mqtt_host, mqtt_port, 60) # Run MQTT background thread which handles reconnects mqttc.loop_start() except Exception: logger.error("Could not connect to MQTT") else: logger.info("Connected to MQTT") # time to show Build version time.sleep(2) buttonPress_time = time.time() if not backlight_timeout: lcd.backlight = 1 page = default_page # Enter main loop while True: # turn backlight off after backlight_timeout seconds now = time.time() if backlight_timeout and now - buttonPress_time > backlight_timeout and lcd.backlight: lcd.backlight = 0 # Update LCD in case it is left at a screen where values can change (e.g uptime etc) updateLCD() time.sleep(lcd_update_sec)
from gpiozero import Button import math wind_speed_sensor = Button(5) wind_count = 0 def spin(): global wind_count wind_count = wind_count + 1 print("spin" + str(wind_count)) wind_speed_sensor.when_pressed = spin radius_cm = 9.0 wind_interval = 5 wind_count = 17 circumference_cm = (2 * math.pi) * radius_cm rotations = count / 2.0 dist_cm = circumference_cm * rotations speed = dist_cm / wind_interval print(speed) def reset_wind(): global wind_count wind_count = 0
# 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))
def shutdown(b): # find how long the button has been held p = b.pressed_time # blink rate will increase the longer we hold # the button down. E.g., at 2 seconds, use 1/2 second rate. leds.blink(on_time=0.5 / p, off_time=0.5 / p) if p > offtime: os.system("sudo shutdown -h now") def when_pressed(): # start blinking with 1/2 second rate leds.blink(on_time=0.5, off_time=0.5) def when_released(): # be sure to turn the LEDs off if we release early leds.off() with warnings.catch_warnings(): warnings.simplefilter("ignore") leds = LEDBoard(actledGPIO, powerledGPIO) btn = Button(offGPIO, hold_time=mintime, hold_repeat=True) btn.when_held = shutdown btn.when_pressed = when_pressed btn.when_released = when_released
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()
camera.video_stabilization = True filename = datetime.datetime.now().strftime('%d-%m-%Y-%H:%M:%S.h264') camera.annotate_text = datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S') print("look") camera.start_preview() print("cam start") camera.start_recording('/home/pi/Desktop/videos/'+filename) btn.wait_for_press() print("cam stop") camera.stop_recording() print("dont look") camera.stop_preview() camera.close() #init button = Button(17) print("button init") while True: button.wait_for_press() print("calling record fn") toggle_Record(button) sleep(3) print("end") #camera.start_preview() #button.wait_for_press() #camera.capture('/home/pi/Desktop/image.jpg') #camera.stop_preview()
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()
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)
class Interface: '''Creates interface to the raspi GPIO pins to control the buttons and leds of the UI''' def __init__(self, serial): self.engine = pyttsx3.init() self.voices = self.engine.getProperty('voices') self.engine.setProperty('rate', 130) self.engine.setProperty('voice', self.voices[11].id) self.error = LED(20) #checked self.ready = LED(16) #checked self.start_print = Button(26) #checked self.play = Button(13) #checked self.cancel = Button(6) #checked self.sound = Button(19) #checked self.ser = serial #checks if the buttons/switch change to an "on" state self.sound_triggered = False self.play_triggered = False self.print_triggered = False self.cancel_triggered = False #boolean to distinguish if press is for play or pause self.is_play_active = True self.is_cancel_active = False self.is_sound_active = False self.is_start_active = False # Debouncing boolean self.last_time = time.time() def debounced(self): if .1 + self.last_time < time.time(): self.last_time = time.time() debounced = True else: debounced = False return debounced def signal_error(self): self.error.on() if self.is_sound(): self.engine.say('There has been an error') self.engine.runAndWait() def resolve_error(self): self.error.off() if self.is_sound(): self.engine.say('The error has been resolved') self.engine.runAndWait() def signal_ready(self): if self.is_sound(): self.engine.say('The printer is ready to print') self.engine.runAndWait() self.ready.on() def resolve_ready(self): self.ready.off() def wait_for_play(self): self.play.wait_for_press() def wait_for_print(self): self.signal_ready() self.start_print.wait_for_press() def is_sound(self): if not self.sound.is_pressed and not self.is_sound_active: self.engine.say('Sound is on') self.engine.runAndWait() print('[interface.py] ', 'Sound switched on') self.is_sound_active = True if self.sound.is_pressed: self.is_sound_active = False return not self.sound.is_pressed def is_cancel(self): if self.cancel.is_pressed: self.is_cancel_active = True print('Process Cancelling') if self.is_sound(): self.engine.say('Process Canceled') self.engine.runAndWait() raise KeyboardInterrupt return self.is_cancel_active def check_buttons(self): '''Checks the status of the buttons and returns true if it should continue''' self.is_play() self.is_cancel() return True def sleep(self, amount_of_seconds): time_start = time.time() while time.time() < time_start + amount_of_seconds: self.is_play() self.is_cancel() def is_play(self): ''' Checks if the print should be played and holds if it should not''' if self.play.is_pressed and self.debounced(): self.is_play_active = not self.is_play_active if self.is_play_active: print('Playing') if self.is_sound(): self.engine.say('Playing') self.engine.runAndWait() if not self.is_play_active: print('Paused') if self.is_sound(): self.engine.say('Paused') self.engine.runAndWait() while not self.is_play_active: self.is_cancel() if self.play.is_pressed and self.debounced(): self.is_play_active = True print('Playing') if self.is_sound(): self.engine.say('Playing') self.engine.runAndWait() # print ("Play is " + str(self.is_play_active)) return self.is_play_active def is_start_print(self): if self.start_print.is_pressed and self.debounced(): self.is_start_active = not self.is_start_active if self.is_start_active: print('Starting Print') if self.is_sound(): self.engine.say('Printing') self.engine.runAndWait() self.resolve_ready() return self.is_start_active
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()
from time import sleep from turtle import Screen, Turtle from math import fabs, ceil from sqlite3 import connect from datetime import date from timeit import default_timer from random import choice from gpiozero import Button # buttons buttonA = Button(16) buttonB = Button(26) buttonC = Button(10) # TBD buttonD = Button(11) # TBD # database creation exec(open('system/database.py').read()) # executing database creation file # variable for the game count = 0 leftScore = 0 rightScore = 0 serve = [True, False] totalLeft = 0 totalRight = 0 totalThird = 0 player1 = False player2 = False player3 = None
# I check if ES is running here because if it *is* then any running game was launched from within ES # and we don't want to quit it when the button is pressed. But if the game was launched from a cart # then ES will not be running in the background and we *do* want to quit the emulator. ############################################################################################# # Set BCM 4 HIGH... the arduino reads this to determine if the Raspberry Pi is running led = LED(4) led.on() # If we do a manual shutdown from within ES then our program will be stopped and the pin # will return to a LOW state, the arduino can read this and cut the power when appropriate ############################################################################################# # Assign the NES 'power' button to the button functions onbtn = Button(3) offbtn = Button(2) onbtn.when_pressed = button_on offbtn.when_pressed = button_off ############################################################################################# # Assume the cart is not valid until we've checked it in the main loop cartok = False # Main Loop while True: try: line = ser.readline() if line != "": records = line[:-1].split(', ') # incoming data looks like: "$$$, $$$, $$$, \n"
from gpiozero import Button, TrafficLights, Buzzer from time import sleep buzzer = Buzzer(15) button = Button(21) lights = TrafficLights(25, 8, 7) while True: button.wait_for_press() buzzer.on() light.green.on() sleep(1) lights.amber.on() sleep(1) lights.red.on() sleep(1) lights.off() buzzer.off()
numbers = { 0: '/home/pi/Music/numbers/AUD-20190506-WA0012.mp3', 1: '/home/pi/Music/numbers/AUD-20190506-WA0002.mp3', 2: '/home/pi/Music/numbers/AUD-20190506-WA0003.mp3', 3: '/home/pi/Music/numbers/AUD-20190506-WA0004.mp3', 4: '/home/pi/Music/numbers/AUD-20190506-WA0005.mp3', 5: '/home/pi/Music/numbers/AUD-20190506-WA0006.mp3', 6: '/home/pi/Music/numbers/AUD-20190506-WA0007.mp3', 7: '/home/pi/Music/numbers/AUD-20190506-WA0008.mp3', 8: '/home/pi/Music/numbers/AUD-20190506-WA0009.mp3', 9: '/home/pi/Music/numbers/AUD-20190506-WA0010.mp3', 10: '/home/pi/Music/numbers/AUD-20190506-WA0011.mp3' } from gpiozero import LED, Button conter_btn = Button(16) # TODO Choose button import pygame pygame.mixer.init() player = pygame.mixer.music # start the luma led 32*8 led matrix from breadboard.luma_local_utils import set_serial, set_long_device serial = set_serial() cntr = 0 def activate(num): device = set_long_device() global cntr from luma.core.render import canvas
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..')
from gpiozero import LED, Button, LightSensor, MotionSensor, PWMLED from threading import Timer from time import sleep from requests import post timer = None ledPWM = PWMLED(21) led2 = LED(22) led3 = LED(23) but1 = Button(11) sensor_de_luz = LightSensor(8) sensor_de_movimento = MotionSensor(27) chave = "cB2Z3ma0b6FHUsDl0AVF_vm7mCMmg0ftj9ohwbwDsBH" evento = "Button1_pressed" endereco = "https://maker.ifttt.com/trigger/" + evento + "/with/key/" + chave def botao_pressionado(): dados = {"value1": sensor_de_luz.value} post(endereco, json=dados) def movimento_inerte(): led2.off() print("inerte") global timer timer = Timer(8.0, desliga_led_3) timer.start() def movimento_detectado():
from picamera import PiCamera from datetime import datetime from time import sleep from gpiozero import Button from random import choice import tweepy import json btn = Button(17) camera = PiCamera() with open('twitter_auth.json') as file: secrets = json.load(file) auth = tweepy.OAuthHandler(secrets['consumer_key'], secrets['consumer_secret']) auth.set_access_token(secrets['access_token'], secrets['access_token_secret']) twitter = tweepy.API(auth) status = ['Hey there peeps', 'Check out my photo', 'Babbage is coming at ya'] filename = '' def take_photo(): global filename now = datetime.now() filename = "{0:%Y}-{0:%m}-{0:%d}-{0:%H}-{0:%M}-{0:%S}.png".format(now) camera.start_preview(alpha=190) sleep(1)
from gpiozero import DistanceSensor, LED, Button from time import sleep from datetime import datetime from signal import pause from picamera import PiCamera dist_sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2) capture_button = Button(12) camera = PiCamera() led = LED(25) def capture(): print("capture") camera.capture('/home/pi/python_Pi/Project/image/%s.jpg' % datetime.now().isoformat()) def recording_on(): print("recording_on") led.on() camera.start_recording(output='/home/pi/python_Pi/Project/record/%s.h264' % datetime.now().isoformat()) def recording_off(): print("recording_off") led.off() camera.stop_recording()
#Green LED = pin 7 #Now it’s time for the code. Open Python 3, create a new file within the crackerjoke folder called ‘crackerjoke.py’ and type the following: ################################################################# import pygame.mixer from pygame.mixer import Sound from gpiozero import Button, LED from signal import pause from time import sleep pygame.mixer.init() good = Sound("/home/pi/crackerjoke/goodjoke.wav") bad = Sound("/home/pi/crackerjoke/badjoke.wav") goodbutton = Button(21) badbutton = Button(24) red = LED(8) green = LED(7) while True: red.on() green.on() goodbutton.when_pressed = good.play badbutton.when_pressed = bad.play pause() ################################################################# #If you’d like the code to run on reboot, allowing you to detach yourself from the monitor, keyboard, and mouse, open a terminal window and type:
# GET_GAME_URL_BASE = 'https://1bj8u6759k.execute-api.us-east-2.amazonaws.com/production/game/' # POST_GAME_SCORE_URL_BASE = 'https://1bj8u6759k.execute-api.us-east-2.amazonaws.com/production/game/' BUTTON1_GPIO = 5 BUTTON2_GPIO = 6 BUTTON3_GPIO = 12 BUTTON_HOLD_TIME = 3 SLEEP_TIMEOUT = 15 * 60 SLEEP_STATE = 'sleep' SETUP_STATE = 'setup' ONLINE_SETUP_STATE = 'online_setup' GAME_STATE = 'game' GAME_OVER_STATE = 'game_over' button1 = Button(BUTTON1_GPIO) button2 = Button(BUTTON2_GPIO) button3 = Button(BUTTON3_GPIO) button1.hold_time = BUTTON_HOLD_TIME button2.hold_time = BUTTON_HOLD_TIME button3.hold_time = BUTTON_HOLD_TIME scoreboard = Scoreboard('yellow', 'blue') time_of_last_interaction = time.time() game_id = None state = SLEEP_STATE play_to_score = 25 scores = [0, 0]
omx11 = udp_client.UDPClient("192.168.1.211", 9998) omx12 = udp_client.UDPClient("192.168.1.212", 9998) msg2 = osc_message_builder.OscMessageBuilder(address="/omxplayer") msg2.add_arg(1) msg2.add_arg(3) msg2 = msg2.build() omx1.send(msg2) omx2.send(msg2) omx3.send(msg2) omx4.send(msg2) omx5.send(msg2) omx6.send(msg2) omx7.send(msg2) omx8.send(msg2) omx9.send(msg2) omx10.send(msg2) omx11.send(msg2) omx12.send(msg2) check_call(['sudo', 'reboot']) def btn_pressed(): _thread.start_new_thread(reboot_process, (1, "")) reboot_btn = Button(27, hold_time=3) reboot_btn.when_held = poweroff reboot_btn.when_pressed = btn_pressed pause()
inProgress = False # Clear the In Progress flag return # Return nothing ################################################# # # # Initial Setup # # # ################################################# print("Begin Initial Setup") inProgress = False # Make sure we clear that we're currently processing an image camera = PiCamera() # Create an instance of the PiCamera startButton = Button( 17) # Initialise the Start button (Note, current button is push to break!) quitButton = Button( 25) # Initialise the Quit button (Note, current button is push to break!) displayBrightness = 0.1 # Set the Display Brightness clearScrollPhatHD() # Clear the Display scrollText = scrollTextClass() # Create the Scroll Text Class scrollTextForever = scrollTextForeverClass() # Create the Scroll Forever Class showBlinktAttract = showBlinkAttractClass( ) # Create the Show Blinkt Attract Class rootFilePath = os.path.dirname( os.path.realpath('__file__')) + '/' # Get the Root File Path print("Initial Setup Complete")
from gpiozero import Button, Robot from gpiozero.pins.pigpio import PiGPIOFactory from signal import pause factory = PiGPIOFactory(host='192.168.1.17') robot = Robot(left=(4, 14), right=(17, 18), pin_factory=factory) # remote pins # local buttons left = Button(26) right = Button(16) fw = Button(21) bw = Button(20) fw.when_pressed = robot.forward fw.when_released = robot.stop left.when_pressed = robot.left left.when_released = robot.stop right.when_pressed = robot.right right.when_released = robot.stop bw.when_pressed = robot.backward bw.when_released = robot.stop pause()
pnconfig.subscribe_key = "sub-c-1575c412-2116-11e8-a7d0-2e884fd949d2" pnconfig.publish_key = "pub-c-2d8f55f6-daa7-467b-923b-6a1e6570c9fc" pnconfig.ssl = False pubnub = PubNub(pnconfig) #--------------------------------------------# #------------Sensor Declarations-------------# #lamp is connected to GPIO4 as an LED lamp = LED(4) #door sensor is connected to GPIO3 as a Button door_sensor = Button(3) #light sensor is connected to GPIO14 as a Button light = Button(14) #--------------------------------------------# #door counter doorCount = 0 class MySubscribeCallback(SubscribeCallback): def status(self, pubnub, status): pass
from I2CDisplay import * from gpiozero import Button import time # File holding questions # 4 lines are the question and then the 5 is T for true or F for false # Repeat for Q 2 etc. quizfilename = "quiz.txt" start_button = Button(23) true_button = Button(22) false_button = Button(4) # Initialise display lcd_init() # Send some test lcd_string("Raspberry Pi",LCD_LINE_1) lcd_string("True or False quiz",LCD_LINE_2) lcd_string("",LCD_LINE_3) lcd_string("Press start",LCD_LINE_4) start_button.wait_for_press() # Note that there is no error handling of file not exist # Consider using a try except block # Open the file file = open(quizfilename) questions = 0 score = 0
from picamera import PiCamera from time import sleep from gpiozero import Button import datetime from signal import pause button = Button(17) camera = PiCamera() #i=0 ''' Create a Python program that will take a photo every time a button is pressed. The camera preview should be enabled for at least 2 seconds before the photo is taken. The photos should never be overwritten. You will need to come up with a naming convention that will ensure that the name of each photo will be unique. Add a timestamp to the actual photo that includes the precise date/time that the photo was taken. Hint: you will want to look at the datetime Python framework ''' #button.wait_for_press() #define function def take_photo(): camera.start_preview() now = datetime.datetime.now() date_time = now.strftime("%m-%d-%Y %H:%M:%S.%f")[:-3] camera.annotate_text = date_time #i += 1 #add a delay for at least 2 seconds before the photo is taken sleep(2) camera.capture('/home/pi/image' + str(i) + ' ' + date_time + '.jpg')
import pygame.mixer from pygame.mixer import Sound import time from gpiozero import MotionSensor from gpiozero import Button from signal import pause pygame.mixer.init() pir = MotionSensor(4) button = Button(2) drum = Sound("test/ka_ru_na_2.wav") while True: button.when_pressed = drum.play time.sleep(4) if pir.motion_detected: drum.play() print("Motion Detect!: !") time.sleep(4)
from gpiozero import Button button = Button(21) state = 1 def changestate(): global state print("state changed!") if state == 1: state = 0 else: state = 1 print("state is ", state) while True: button.when_pressed = changestate
import forecastio import datetime from gpiozero import RGBLED, Button from time import sleep from signal import pause from math import pow # https://developer.forecast.io/docs/v2#forecast_call led = RGBLED(red=4, green=26, blue=19) #led2 = RGBLED(red=13, green=6, blue=5) button = Button(18) button2 = Button(23) led.off() api_key = "9c09fe99666a61bbd85aa2743387cd31" lat = 47.3769 lng = 8.5417 def nextHours(hours): if led.is_lit: led.off() led2.off() return # till the forecast is loaded led.color = (0.2,0.2,0.2) led2.color = (0.2,0.2,0.2)
pnconfig = PNConfiguration() pnconfig.publish_key = 'pub-c-c823b87a-2007-4df2-88da-ad535587f882' pnconfig.subscribe_key = 'sub-c-4143a002-4a53-11e9-bc27-728c10c631fc' pnconfig.ssl = False pubnub = PubNub(pnconfig) # Pump is connected to GPIO4 as an LED pump = LED(4) # DHT Sensor is connected to GPIO17 sensor = 11 pin = 17 # Soil Moisture sensor is connected to GPIO14 as a button soil = Button(14) cmd = -1 TVal = -1 HVal = -1 pump.on() class MySubscribeCallback(SubscribeCallback): def status(self, pubnub, status): pass def presence(self, pubnub, presence): pass def message(self, pubnub, message):
from gpiozero import LED, Button from time import sleep from random import uniform import sys led = LED(4) right_button = Button(15) left_button = Button(14) left_name = input('left player name is ') right_name = input('right player name is ') led.on() sleep(uniform(1,2)) led.off() def pressed(button): if button.pin.number == 14: print(left_name + ' won the game') else: print(right_name + ' won the game') sys.exit() right_button.when_pressed=pressed left_button.when_pressed=pressed
if not config.testing: print("Starting in production mode") subprocess.call(["touch", settings_path]) subprocess.call(["touch", wpa_path]) subprocess.call(["touch", secrets_path]) subprocess.call(["chmod", "777", root_path]) subprocess.call(["chmod", "777", settings_path]) subprocess.call(["chmod", "777", secrets_path]) subprocess.call(["chmod", "777", wpa_path]) subprocess.call(["chmod", "777", settings_template_path]) process = subprocess.Popen(["python3", app_path]) else: print("Starting in testing mode") process = subprocess.Popen(["python3", app_path]) print("App started at pid {}".format(process.pid)) if not config.testing: button = Button(25, pull_up=False, hold_time=5) button.when_pressed = button_pressed button.when_released = button_released button.when_held = button_held signal.pause() else: while (True): line = input("L for long, S for short, D for double").rstrip() if line == "L": execute_long_press() elif line == "S": execute_short_press() elif line == "D": execute_double_press()
pin = '7' else: with open(file, 'w') as f: f.write('7') pin = '7' return int(pin) pinFile = "/boot/mintypi/pinfile.txt" pinDirectory = "/boot/mintypi/" pngviewPath = "/home/pi/MintyComboScript/Pngview/" iconPath = "/home/pi/MintyComboScript/icons" statePath = "/home/pi/MintyComboScript/combo.dat" comboStates = {'wifi': 1, 'bluetooth': 1, 'volume': 60, 'brightness': 1024, 'battery': 1} functionPin = grabPin(pinFile, pinDirectory) functionBtn = Button(functionPin) brightnessUpBtn = Button(4) brightnessDownBtn = Button(5) volumeUpBtn = Button(22) volumeDownBtn = Button(14) shutdownBtn = Button(26) monitorBtn = Button(21) wifiBtn = Button(20) bluetoothBtn = Button(16) cheatBtn = Button(6) led = 1 # Functions def brightnessUp(): if brightnessUpBtn.is_pressed:
from jam_picamera import JamPiCamera from auth import CON_KEY, CON_SEC, ACC_TOK, ACC_SEC from text import get_text from gpiozero import Button from twython import Twython from time import sleep import logging logger = logging.getLogger('photobooth') logging.basicConfig(level=logging.INFO) logger.info("starting") text = get_text(language='en') camera = JamPiCamera() button = Button(14, hold_time=5) if CON_KEY: twitter = Twython(CON_KEY, CON_SEC, ACC_TOK, ACC_SEC) else: twitter = None camera.resolution = (1024, 768) camera.start_preview() camera.vflip = True camera.annotate_text_size = 70 def quit(): logger.info("quitting") camera.close()
from gpiozero import Button from pygame import mixer from signal import pause mixer.init() # Glove Button Assignment thumb = Button(2) pointer = Button(3) middle = Button(4) ring = Button(17) pinky = Button(27) kick = mixer.Sound("dk1_kick.ogg") snare = mixer.Sound("dk1_snare.ogg") tom = mixer.Sound("dk1_tom.ogg") snap = mixer.Sound("dk1_snap.ogg") hat = mixer.Sound("dk1_hat.ogg") thumb.when_pressed = kick.play pointer.when_pressed = snare.play middle.when_pressed = tom.play ring.when_pressed = snap.play pinky.when_pressed = hat.play pause()
import state_machine from gpiozero import Button from gpiozero import DigitalOutputDevice from time import sleep pin_a = Button(22) pin_b = Button(23) pin_z = Button(24) device = DigitalOutputDevice(pin=17) a = pin_a.is_pressed b = pin_b.is_pressed z = pin_z.is_pressed counter = 0 # amount of increments for a full rotation of geared motor shaft with a gear ratio of ~26.85:1 # assuming increments for one rotation is 4000 # full_rotation = 107405 delay = .1 fsm = state_machine.Motor_State_Machine() fsm.update(state_machine.Motor_State.s0, a, b, z, start=True, stop=False, pause=False)
from gpiozero import LED, Button from signal import pause led = LED(17) button = Button(3) button.when_pressed = led.on button.when_released = led.off pause()
from gpiozero import Button, PWMLED from signal import pause import subprocess import time red = PWMLED(18) red.pulse() def popticket(): subprocess.run(["python3", "/home/pi/ticketbot/ticketsuccess.py"]) subprocess.run(["python3", "/home/pi/ticketbot/ticketgen.py"]) button = Button(7) button.when_pressed = popticket red.pulse() pause()