#!/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)
from signal import pause from gpiozero import Button import requests ip_addr = "" port = 5000 button_map = {"GPIO6": "1", "GPIO13": "2", "GPIO19": "3", "GPIO26": "4"} def tx(button): angle = button_map[str(button.pin)] requests.post("http://%s:%s/hate5grip?angle=%s" % (ip_addr, port, angle)) button1 = Button(6) button2 = Button(13) button3 = Button(19) button4 = Button(26) try: button1.when_pressed = tx button2.when_pressed = tx button3.when_pressed = tx button4.when_pressed = tx pause() finally: pass
from gpiozero import Button import pygame.mixer from pygame.mixer import Sound from signal import pause pygame.mixer.init() sound_pins = { 2: Sound("samples/drum_tom_mid_hard.wav"), 3: Sound("samples/drum_cymbal_open.wav"), } buttons = [Button(pin) for pin in sound_pins] for button in buttons: sound = sound_pins[button.pin.number] button.when_pressed = sound.play pause()
from gpiozero import LED, Button led = LED(17) button = Button(2) button.when_pressed = led.on button.when_released = led.off
## 2 player game - Player 1 will press a sequence of buttons ## and set in action a sequence of lights. ## Player 2 observes the light sequence then attempts ## to copy the sequence by pressing buttons ## If correct a celebratory sequnce of lights plays ## otherwise the buzzer sounds. ## To set up PlayHAT, please visit https://github.com/4tronix/PlayHAT import time from neopixel import * from gpiozero import Button, Buzzer from signal import pause btnG = Button(17) btnR = Button(4) btnB = Button(22) btnY = Button(27) beeper = Buzzer(23) MyList = [] MyCheckList = [] # 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)
def set_up_button(): for button_nr in BTN_PIN: button_list.append(Button(button_nr))
pygame.mixer.music.load( "/home/pi/Sounds/Normal.mp3") pygame.mixer.music.play() else: if (emotions == "Sad"): pygame.mixer.music.load( "/home/pi/Sounds/Sad.mp3") pygame.mixer.music.play() else: if (emotions == "Surprise"): pygame.mixer.music.load( "/home/pi/Sounds/Surprise.mp3") pygame.mixer.music.play() if (emotions == "Neutral"): CODE("Normal") CODE(emotions) # morse code for the emotions else: print("Face is not detected clearly :( ") GPIO.output(buzzer, GPIO.HIGH) sleep(1) GPIO.output(buzzer, GPIO.LOW) # Play NoFace pygame.mixer.music.load("/home/pi/Sounds/NoFace.mp3") pygame.mixer.music.play() CODE("No Face") #os.execv('/home/pi/button.py', sys.argv) button = Button(4) button.when_pressed = take_picture_with_camera
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()
# 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]
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 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 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
# # 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)
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
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)
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")
def btn_setup(): for k in range(AMOUNT_BUTTONS): btn.append(Button(BTN_PIN[k], pin_factory=IP_ADRESS))
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
#imports from gpiozero import Servo from gpiozero import Button import time """ Team 37 Servo Control """ servoPin1 = 17 servoPin2 = 18 button1_pin = 4 button2_pin = 21 button1 = Button(button1_pin) button2 = Button(button2_pin) motor1 = Servo(servoPin1, max_pulse_width = 2.7e-3, min_pulse_width = 5e-4) motor2 = Servo(servoPin2, max_pulse_width = 2.7e-3, min_pulse_width = 5e-4) init_val = -1 #resetting motor motor1.value = init_val motor2.value = init_val try: while True: # if button1.is_pressed and motor1.value != 1: motor1.value += 0.1 motor2.value += 0.1 time.sleep(0.05) print("Button 1 is Pressed") if motor1.value and motor2.value == 1:
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')
def exit_flow(): sys.exit() def cb(name): pass if __name__=='__main__': manager = Manager() engine = pyttsx3.init() engine.setProperty('rate', 145) engine.setProperty('volume', 1) engine.setProperty('voice', 'english+f1') camera = PiCamera() button_green = Button(17) button_red = Button(15) button_yellow = Button(18) button_red.hold_time = 3 engine.connect('started-utterance', cb) pressed = False while True: end_result = manager.dict() end_result['description'] = '' end_result['text'] = '' end_result['emotion'] = '' main() while(engine.isBusy()): pass
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
s3 = session.resource('s3') curr_meds = [] curr_times = {'slot1': '', 'slot2': '', 'slot3': ''} old_times = {} meds_for_each_time = [[],[],[]] disp_jobs = [] disp_jobs_order = [] disp_jobs_status = {'slot1': '', 'slot2': '', 'slot3': ''} disp_fails = [] email = '' #Declaring GPIO limit_switch = Button(14) limit_bool = True dispense_button = Button(15) reset_button = Button(16) servo = Servo(17) servo.value = None green_led = LED(27) red_led = LED(22) system_on_led = LED(26) cam = picamera.PiCamera() cam.vflip = True cam.resolution = (480,640) buzzer1 = Buzzer(18) buzzer2 = Buzzer(23) # Servo pos file init read
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 Button from time import sleep button = Button(17, pull_up=False) #17: detection sensor #22: mechanical switch while True: if button.is_pressed: print("Pressed") else: print("Released") sleep(1)
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()
def execute(self): ##################################### # # # REFERENCE IMPLEMENTATION # # # ##################################### specificConfig = self.config.get('SpecificConfig') if not specificConfig: self.return_queue.put( Record(None, message='Trigger: {:04d}'.format( self.config['Identifier']))) return gpioName = None mainMode = None cmd = None self.gpio = None self.initFlag = False for attrs in specificConfig: if attrs['Name'] == 'GPIO': gpioName = attrs['Data'] if attrs['Name'] == 'MainMode': mainMode = attrs['Data'] self.gpio = Button(gpioName) if mainMode == 'Fire when released': self.gpio.when_released = self.onReleased elif mainMode == 'Fire when pressed': self.gpio.when_pressed = self.onPressed ##################################### # # # Start of the infinite loop # # # ##################################### while (True): # Example code: Do something try: # Block for 1 second and wait for incoming commands cmd = None cmd = self.cmd_queue.get(block=True, timeout=1) except queue.Empty: pass if isinstance(cmd, ProcCMD): if cmd.bStop: # Stop command received, exit self.return_queue.put( Record(None, 'GPIO{} closed'.format(self.gpio.pin.number))) self.gpio.close() return
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 signal import pause from subprocess import check_call held_for = 0.0 def rls(): global held_for if (held_for > 5.0): check_call(['/sbin/poweroff']) elif (held_for > 2.0): check_call(['/sbin/reboot']) else: held_for = 0.0 def hld(): # callback for when button is held # is called every hold_time seconds global held_for # need to use max() as held_time resets to zero on last callback held_for = max(held_for, button.held_time + button.hold_time) button = Button(use_button, hold_time=1.0, hold_repeat=True) button.when_held = hld button.when_released = rls pause() # wait forever
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()