def __init__(self): self.buzzer = Buzzer(4) self.onTime = .01 self.offTime = .19 self.level = 0 self.active = False self.run()
class PhoneControls: def __init__(self, callbPush, callbHang, ledPins=(17, 27, 22), buzzerPin=13, pttPin=18, canPin=19): # define properties self.led = RGBLED(ledPins[0], ledPins[1], ledPins[2]) self.buzzer = Buzzer(buzzerPin, active_high=True) self.pttButton = Device.pin_factory.pin(pttPin) self.canButton: Pin = Device.pin_factory.pin(canPin) # configure hardware self.__configPinHandler__(self.pttButton, self.__pttCallback__) self.__configPinHandler__(self.canButton, self.__canCallback__) self.cbCan = callbHang self.cbPtt = callbPush def __configPinHandler__(self, button: Pin, cb): button.edges = "both" button.input_with_pull("up") button.bounce = .250 button.when_changed = cb def __canCallback__(self, ticks, state): sleep(0.2) state = self.canButton.state log.debug("Can button state=%d", state) if state == 0: self.cbCan(CanState.HUNGUP) else: self.cbCan(CanState.LIFTED) def __pttCallback__(self, ticks, state): sleep(0.2) state = self.pttButton.state log.debug("PTT button state=%d", state) if state == 1: self.cbPtt(PttState.RELEASED) else: self.cbPtt(PttState.PRESSED) def ledOff(self): self.led.off() def ledOn(self, rgb=(1, 1, 1)): self.led.value = rgb def startBlinking(self, rgb=(1, 1, 1), off_time=0.5, on_time=0.5): self.led.blink(on_time=on_time, off_time=off_time, on_color=rgb, background=True) def beep(self): self.buzzer.beep(on_time=1, off_time=0.25, background=True) def stopBeep(self): self.buzzer.off()
def __init__(self, pin, active_high=True, initial_value=False): super().__init__() self.pin = pin self.resource = Buzzer(pin, active_high=active_high, initial_value=initial_value)
def __init__(self): Thread.__init__(self) Thread.daemon = True self.statusled = LED(gpioled) self.arm = Button(gpioarm) self.disarm = Button(gpiodisarm) self.buzzer = Buzzer(gpiobuzzer)
def __init__(self, port_name, name="buzzer"): self._pma_port = port_name self.name = name Stateful.__init__(self) Recreatable.__init__(self, {"port_name": port_name, "name": self.name}) gpiozero_Buzzer.__init__(self, get_pin_for_port(self._pma_port))
def __init__(self, BasePath, TelgramId, room): print("Initializing Camera") self.camera = PiCamera() self.camera.resolution = (640, 480) print("Initializing AWS") self.s3 = AwsS3() print("Initializing MotionSensor") self.pir = MotionSensor(26, sample_rate=1000, queue_len=1, threshold=0.9) self.pir.when_motion = self.OnMotion self.pir.when_no_motion = self.OnStopMotion self.bz = Buzzer(21) self.DisarmDetector = False self.has_detected_motion = False self.BasePath = BasePath self.room = room self.MotionCallback = None if not os.path.isdir(BasePath): os.makedirs(BasePath) self.update_time = time.time() self.snapshot_file_path = str(room.Id) + '.png'
def Read(self): self.Values.clear() for pin in self.Pins: bz=Buzzer(pin) #beep(on_time=1,off_time=1,n=None,background=Ture) bz.beep(1,0.1,1,False) self.Values.append(1)
def __init__(self, times=1): """ Makes the bell chimes :param times: number of times the bell must chime """ self.__times = int(times) self.__buzzer = Buzzer(config.get('CHIME_GPIO_BCM')) super().__init__()
class BistrobotBell: def __init__(self, buzzer_pin): self.buzzer = Buzzer(buzzer_pin) def buzz(self, duration=5): for i in range(0, duration): self.buzzer.on() sleep(0.01) self.buzzer.off()
def __init__(self, remote_address): # set PINs on BOARD log.debug("Initializing Buzzer...") log.debug("> buzzer pin: " + str(_conf['buzzer_pin'])) # using Buzzer rem_pi = PiGPIOFactory(host=remote_address) self.buzzer = Buzzer(_conf['buzzer_pin'], pin_factory=rem_pi) log.debug("...init done!")
def piezo_output(temp): buzzer = Buzzer(3) if (temp > 25): buzzer.on() time.sleep(4) buzzer.off() time.sleep(1) elif (temp < 26 and temp > 24): buzzer.on() time.sleep(1) buzzer.off() time.sleep(1)
class Detection: def __init__(self): self.alarm = Buzzer(22) def findAnomalies(self, newData, mu, std, sigma): if (newData > (mu + sigma * std) | newData < (mu - sigma * std)): print("Anomaly detected") self.alarm.on() time.sleep(3) self.alarm.off() else: print("Normal")
def __init__(self): self.bz = Buzzer(18) self.accel = adxl345.ADXL345() self.tick = datetime.datetime.now() self.beep_dur = 0.1 self.sample_period = 0.2 self.upper = 20 self.lower = -20 self.beeping = False self.alarm = False self.beep_change = datetime.datetime.now() self.last_sample = datetime.datetime.now() self.run = False
def active_seismometer(callback, callback_interval): buzzer = Buzzer(3) status_led = LED(26) scale_led = LEDBoard(a=18, b=23, c=12, d=19, e=6, f=22, g=17, xdp=16) seismometer = Seismometer() seismometer.start_calculation(callback, callback_interval) while True: try: seismic_scale = seismometer.seismic_scale scale_led.value = SCALE_LED_CHARSETS[ seismometer.get_user_friendly_formatted_seismic_scale()] if seismometer.ready: if not status_led.is_lit: status_led.on() if seismic_scale >= 3.5: if not buzzer.is_active: buzzer.on() else: buzzer.off() except KeyboardInterrupt: break seismometer.stop_calculation() scale_led.off() status_led.off() buzzer.off()
def distancemain(): # setup pins for ultrasonic sensor and buzzer TRIG = 17 ECHO = 27 GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG,GPIO.OUT) GPIO.setup(ECHO,GPIO.IN) bz = Buzzer(22) # connect to aws my_rpi = utils.setupAWS("MyStudyRoom-RPI-distance") my_rpi.connect() update = True while update: try: # subscribe to topic to check whether the start or stop monitoring button is pressed my_rpi.subscribe("operation/distance", 1, customCallback) global start_distance_program # if start monitoring button is pressed, start program if start_distance_program == True: # get the values needed (current distance value and datetime) GPIO.output(TRIG, True) sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO)==0: pulse_start = time() while GPIO.input(ECHO)==1: pulse_end = time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 distance = round(distance, 2) # type: float n = datetime.now() date_time = n.strftime("%Y-%m-%d %H:%M:%S") # type:string # publish message to sensors/distance topic and save to dynamodb message = {} message["deviceid"] = 1 message["datetime"] = date_time message["distance_cm"] = distance my_rpi.publish("sensors/distance", json.dumps(message), 1) print(message) # check whether the distance is lower than 25 cm # if distance lower than 25 if distance <= 25: # on buzzer bz.on() sleep(1) bz.off() # else off buzzer else: bz.off() except KeyboardInterrupt: start_distance_program = False utils.cleanGPIO()
class BuzzerSensor(object): def __init__(self, numberPin): self.buzzer = Buzzer(numberPin) def getBuzzer(self): return self.buzzer def value(self): return self.buzzer.is_active def buzzerOff(self): self.buzzer.off() def buzzerOn(self): self.buzzer.on()
class DoorbellAlarm: led = RGBLED(red=17, green=22, blue=27) buzzer = Buzzer(26) num_of_times = 0 def __init__(self, num_of_times): self.num_of_times = num_of_times def play_sequence(self): num = 0 while num < self.num_of_times: self.buzzer.on() self.light_show() sleep(0.5) self.buzzer.off() sleep(0.5) num += 1 def light_show(self): self.led.color = (1, 0, 0) sleep(0.1) self.led.color = (0, 1, 0) sleep(0.1) self.led.color = (0, 0, 1) sleep(0.1) self.led.off()
def getExample04(root, r, c): def RuidoBuzzer(): #Metodo para iniciar y detener el ruido del buzzer global bz global ruido if ruido: bz.off() #Apaga el ruido else: bz.on() #enciende el ruido ruido = not ruido def IniciarPines(): GPIO.setmode(GPIO.BCM) # Ponemos la Raspberry en modo BCM GPIO.setup( gpiobuzzer, GPIO.OUT) # Ponemos el pin GPIO nº16 como salida para el LED #1 gpiobuzzer = 16 #Variable que especifica el pin que se utilizara IniciarPines() #Iniciamos los pines a utilizar bz = Buzzer(gpiobuzzer) #Creamos el buzzer ruido = False #Variable boolena que permitira el encendido y apagado de buzzer frame = tkinter.Frame(root) frame.grid(row=r, column=c) #Creamos la interfaz grafica btn_Buz16 = tkinter.Button( frame, text="RuidoBuzzer", command=RuidoBuzzer) # Creamos un boton para la interfaz grafica btn_Buz16.pack() #Agregamos el boton a la interfaz
def main(): # now just write the code you would use on a real Raspberry Pi from gpiozero import LED, Button from time import sleep from gpiozero import Buzzer buzzer = Buzzer(16) led1 = LED(21) led1.blink() def button1_pressed(): print("button 1 pressed!") led2.toggle() def button2_pressed(): print("button 2 pressed!") buzzer.on() def button2_released(): print("button 2 released!") buzzer.off() led2 = LED(22) button1 = Button(11) button1.when_pressed = button1_pressed button2 = Button(12) button2.when_pressed = button2_pressed button2.when_released = button2_released while True: sleep(0.1)
def main(): # now just write the code you would use on a real Raspberry Pi from gpiozero import LED, Button from time import sleep from gpiozero import Buzzer buzzer = Buzzer(16) led1 = LED(21) # id 1 devices = [led1] def button1_pressed(): print("button 1 pressed!") led1.toggle() def button2_pressed(): print("button 1 pressed!") udp_controller("f0;living_room;c1;1;change") button1 = Button(11) button1.when_pressed = button1_pressed button2 = Button(12) button2.when_pressed = button2_pressed sock = udp_reciver_init() while True: command = udp_reciver_check_messages(sock) print(command) if (is_for_me(command, who_i_am)): do_my_job(command[3], command[4], devices) sleep(0.1)
def defineElectronics(): global led global flashlight global buzzer global temperatureSensorInput global humiditySensorInput global gasSensorInput global pi global INA global INB global INC global IND pi = pigpio.pi() led = LED(22) flashlight = LED(23) buzzer = Buzzer(24) temperatureSensorInput = MCP3008(channel=0) humiditySensorInput = MCP3008(channel=1) gasSensorInput = MCP3008(channel=2) INA = 13 INB = 19 INC = 26 IND = 12 for i in [INA, INB, INC, IND]: pi.set_mode(i, pigpio.OUTPUT)
def dash(): buzzer = Buzzer(22) led.on() buzzer.on() sleep(0.5) led.off() buzzer.off() buzzer.close() return render_template('json.html')
def __init__(self,pin_buzzer): self.pin_buzzer = pin_buzzer # buzzers are keyed by name self.buzzer = {} for name,pin in self.pin_buzzer.items(): self.buzzer[name]=Buzzer(pin)
def __init__(self, callbPush, callbHang, ledPins=(17, 27, 22), buzzerPin=13, pttPin=18, canPin=19): # define properties self.led = RGBLED(ledPins[0], ledPins[1], ledPins[2]) self.buzzer = Buzzer(buzzerPin, active_high=True) self.pttButton = Device.pin_factory.pin(pttPin) self.canButton: Pin = Device.pin_factory.pin(canPin) # configure hardware self.__configPinHandler__(self.pttButton, self.__pttCallback__) self.__configPinHandler__(self.canButton, self.__canCallback__) self.cbCan = callbHang self.cbPtt = callbPush
def play_buzzer(pin, stream, high_time): """ Initialize Buzzer """ buzzer = Buzzer(pin) """ Turn the buzzer On on receiving a 1 """" """ Turn the buzzer Off on receiving a 0 """ stream_methods = { '1': buzzer.on, '0': buzzer.off } """ Iterate through the stream """ for item in stream: stream_methods[item]() # Execute Required Function sleep(high_time) # sleep for required time buzzer.off() # Turn off the Buzzer
def __init__(self, host, port): GPIO.setmode(GPIO.BCM) self.buzzer = Buzzer(17) self.host = host self.port = port self.topic = 'iot/control/key' self.msg = 'direct_on' self.client = mqtt.Client() self.client.connect(self.host, self.port) self.fname = 'doorlock.json' self.keyPressed = '' self.tempPeriod = True
class BuzzerController: def __init__(self, gpio: int): self.__bz__ = Buzzer(gpio) self.__bz__.off() def short_beep(self, times: int): x = 0 while x < times: self.__bz__.on() time.sleep(0.05) self.__bz__.off() time.sleep(0.09) x += 1 def long_beep(self): self.__bz__.on() time.sleep(0.3) self.__bz__.off()
def __init__(self, pwm=False, initial_value=False, pin_factory=None): super(FishDish, self).__init__( red=9, yellow=22, green=4, pwm=pwm, initial_value=initial_value, _order=('red','yellow','green'), pin_factory=pin_factory ) self.button=Button(7) self.buzzer=Buzzer(8)
class MockChime: def __init__(self, times=1): """ Makes the bell chimes :param times: number of times the bell must chime """ self.__times = int(times) self.__buzzer = Buzzer(config.get('CHIME_GPIO_BCM')) super().__init__() def __del__(self): if self.__buzzer: self.__buzzer.close() def run(self): for i in range(0, self.__times): self.__buzzer.on() self.__cpt += 1
def main(): try: # logging configuration logging.basicConfig( filename='/opt/rpi-button-box/button-box.log', level=logging.INFO, format= '%(asctime)s.%(msecs)03d %(levelname)s %(module)s : %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logging.info('Started the button box controller') buttons = config_buttons() # wait for a button labelled 'power' to be turned ON before continuing logging.info('Trying to find a power switch...') for button in buttons: if button.label == 'power': logging.info('Power switch found at {}'.format(button.pin)) if not button.is_active: print( 'Waiting for the power button ({}) to be turned ON...'. format(button.pin)) button.wait_for_active() logging.info('Power switch was turned ON by user'.format( button.pin)) sleep(button.hold_time ) # wait for the power button to enter is_held state break # when_* properties will pass the device that activated it to a function that takes a single parameter # use the device's attributes (e.g., pin, type, label) to determine what to do push_buttons, switches = [], [] for button in buttons: if button.type == 'switch': switches.append(button) button.when_held, button.when_released = event_held, event_released logging.info( 'Configured the switch button ({0}) at {1}'.format( button.label, button.pin)) else: # assumes only 'push' and 'switch' types push_buttons.append(button) button.when_pressed, button.when_released = event_pressed, event_released logging.info('Configured the push button ({0}) at {1}'.format( button.label, button.pin)) if args['buzzer']: # buzzer is activated by any push button buzzer, buzzer.source = Buzzer( args['buzzer']), any_values(*push_buttons) logging.info('Configured a buzzer at {}'.format(buzzer.pin)) print( 'The button box is now turned ON. To close it, release the power button or press Ctrl+C.' ) logging.info('The button box is ON and waiting for user input') pause() except KeyboardInterrupt: end(msg='Received a signal to stop.', status=1) except GPIOZeroError as err: end(msg='GPIOZero error: {}'.format(err), status=1)
from twython import Twython file = open("/home/pi/retropicam/auths/CONSUMER_KEY.txt","r") CONSUMER_KEY = file.read() file = open("/home/pi/retropicam/auths/CONSUMER_SECRET.txt","r") CONSUMER_SECRET = file.read() file = open("/home/pi/retropicam/auths/ACCESS_KEY.txt","r") ACCESS_KEY = file.read() file = open("/home/pi/retropicam/auths/ACCESS_SECRET.txt","r") ACCESS_SECRET = file.read() api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) #setup ins and outs btn = Button(23) led = LED(17) bz = Buzzer(2) #Setect button while True: if btn.is_pressed: #User feedback led.blink(0.05,0.05) bz.beep(on_time=0.1,off_time=0.1) print("Button pressed, taking photos...") #Take photos filename = "/home/pi/retropicam/photos/photo" #Take gif photos for num in range (length): date = time.strftime("%d-%m-%Y-%H-%M%S")
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)
#!/usr/bin/env python import os import time import dot3k.lcd as lcd import dot3k.joystick as joystick import dot3k.backlight as backlight from gpiozero import Buzzer import RPi.GPIO as GPIO set_temp = 85 bz = Buzzer(21) GPIO.setup(12,GPIO.OUT) GPIO.output(12,GPIO.HIGH) os.system('modprobe w1-gpio') os.system('modprobe w1-therm') temp_sensor = '/sys/bus/w1/devices/28-000006d85491/w1_slave' def temp_raw(): f = open(temp_sensor, 'r') lines = f.readlines() f.close() return lines def read_temp(): lines = temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = temp_raw()
from gpiozero import MotionSensor, Buzzer import time pir = MotionSensor(4) bz = Buzzer(3) print("Waiting for PIR to settle") pir.wait_for_no_motion() while True: print("Ready") pir.wait_for_motion() print("Motion detected!") bz.beep(0.5, 0.25, 8) time.sleep(3)
p = mc.player.getTilePos() #hide a gold block near the player #create a random position x = p.x + randint(-20, 20) y = p.y + randint(-5, 5) z = p.z + randint(-20, 20) #create the gold block mc.setBlock(x, y, z, block.GOLD_BLOCK.id) #create LED led = LED(4) #create the buzzer buzz = Buzzer(17) #flash all the LED and buzz on led.on() buzz.on() sleep(1) led.off() buzz.off() dist = 0 gameover = False while gameover == False: