class RoPiBuzzer: # initialize 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!") # activate buzz def on(self, time=0): log.debug("Activate buzz") if _conf['quiet'] is False: self.buzzer.on() if time is not 0: sleep(time) self.off() # deactivate buzz def off(self): log.debug("Deativate buzz") self.buzzer.off() # terminate def terminate(self): log.debug("Buzzer termination...") self.buzzer.close()
class Chime(Thread): """ Makes the doorbell chime rings. - Front door: Default (once) - Back door: Configurable in `*Config` classes. See `BACK_DOORBELL_RINGS_NUMBER` """ PAUSE_BETWEEN_STATES = 0.4 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): try: logger.debug('Ring bell, ring bell...') for i in range(0, self.__times): self.__buzzer.on() sleep(self.PAUSE_BETWEEN_STATES) self.__buzzer.off() sleep(self.PAUSE_BETWEEN_STATES) except Exception as e: logger.error(e) return # Close thread
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()
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 test_buzzer(): print('Testing buzzer...') bz = Buzzer(BUZZER_PIN) bz.on() sleep(1) bz.off() ans = input('Heard a buzz? y/n: ') return ans == 'y'
def dit(x, y, rate): led = LED(x) buzz = Buzzer(y) led.on() buzz.on() sleep(rate) led.off() buzz.off() sleep(rate)
def dash(): buzzer = Buzzer(22) led.on() buzzer.on() sleep(0.5) led.off() buzzer.off() buzzer.close() return render_template('json.html')
def car_stop(dist_gpios, buz_gpio): x, y = dist_gpios dist_sensor = DistanceSensor(x, y) buz = Buzzer(buz_gpio) while True: if dist_sensor.distance <= 1.5: buz.on() else: buz.off()
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 buzzerCorto(): buzzer = Buzzer(16) cont=0 while cont<2: buzzer.on() sleep(0.1) buzzer.off() sleep(0.1) cont+=1
def alarm_sequence(task_name): # This is the job the schedulers in scheduler.py executes # Sounds the alarm bz = Buzzer(26) synthesize_text(task_name) bz.on() print("Buzzer off in 3 seconds") sleep(3) bz.off() print("Buzzer off")
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 buzzerOnOne(): i = 0 bz = Buzzer(17) while i < 1: bz.on() sleep(1) bz.off() sleep(1.4) i = i + 1 print("Sound One")
def checkDoor(): buzzer = Buzzer(17) GPIO.setup(27, GPIO.IN) input = GPIO.input(27) while True: if (GPIO.input(27)): print("Door Opened") buzzer.on() sleep(1) buzzer.off() sleep(1)
class Tilter: 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 update(self): now = datetime.datetime.now() if (now - self.last_sample) > datetime.timedelta( 0, self.sample_period, 0): axes = self.accel.getAxes(True) self.last_sample = now if (axes['x'] > self.upper / 100) or (axes['x'] < self.lower / 100): self.alarm = True else: self.alarm = False if self.alarm: if (now - self.beep_change) > datetime.timedelta( 0, self.beep_dur, 0): if self.beeping: self.bz.off() self.beeping = False else: self.bz.on() self.beeping = True self.beep_change = now else: self.bz.off() def loop(self): t = threading.currentThread() while getattr(t, "do_run", True): try: self.update() time.sleep(0.01) except Exception: # grovepi.digitalWrite(buzzer,0) self.bz.off() raise return
def buzzerOnZero(): i = 0 bz = Buzzer(17) while i < 1: bz.on() sleep(1) bz.off() sleep(1.4) bz.on() sleep(0.5) i = i + 1 print("Sound Zero")
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()
def triggerAlarm(): global triggeredMinute global alarmTime if not (triggeredMinute == alarmTime): triggeredMinute = alarmTime alarmActive = True buzzer = Buzzer(17) button = Button(26) while (alarmActive): if (button.is_pressed): alarmActive = False for i in range(5): buzzer.on() time.sleep(.25) buzzer.off() time.sleep(.25) time.sleep(.75)
class BuzzerResource(resource.Resource): def get_link_description(self): # Publish additional data in .well-known/core return dict(**super().get_link_description(), title=f"Buzzer Resource - pin: {self.pin}") 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) async def render_get(self, request): payload = f"{self.resource.value}" print(f'BUZZER {self.pin}: GET') return Message(payload=payload.encode(), code=Code.CONTENT) async def render_post(self, request): payload = request.payload.decode() print(f'BUZZER {self.pin}: POST {payload}') if payload in ['0', 'off']: self.resource.off() elif payload in ['1', 'on']: self.resource.on() elif payload in ['-1', 'toggle']: self.resource.toggle() elif 'beep' in payload: p = payload.split(" ") if p[0] != 'beep': return Message(code=Code.BAD_REQUEST) on_time, off_time, n = 1, 1, None if len(p) > 1 and p[1].isdigit(): on_time = int(p[1]) if len(p) > 2 and p[2].isdigit(): off_time = int(p[2]) if len(p) > 3 and p[3].isdigit(): n = int(p[3]) self.resource.beep(on_time, off_time, n) else: return Message(code=Code.BAD_REQUEST) return Message(code=Code.CHANGED)
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 buzzer(): print "MAKE SOME NOISE!!!" bz = Buzzer(5) # buzzer at gpio 5 redled = LED(19) t_end = time.time() + 30 while time.time() < t_end: try: print "on buzzer and led" bz.on() redled.on() sleep(0.25) print "off buzzer and led" bz.off() redled.off() sleep(0.25) except Exception: bz.off() redled.off()
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 total_output(temp): GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.OUT) GPIO.setup(14, GPIO.OUT) buzzer = Buzzer(3) if (temp >= 26): GPIO.output(4, GPIO.HIGH) buzzer.on() time.sleep(4) GPIO.output(4, GPIO.LOW) buzzer.off() time.sleep(4) elif (temp < 26 and temp > 22): GPIO.output(14, GPIO.HIGH) buzzer.on() time.sleep(1) GPIO.output(14, GPIO.LOW) buzzer.off() time.sleep(1)
def beep(duration=1): """ Issue a single "beep" sound :param duration: Time to sustain beep for, in seconds :return: None """ app.logger.info("Starting beep") app.logger.debug(f"Beep duration: {duration}") try: buzzer = Buzzer(pin=24) buzzer.on() time.sleep(duration) buzzer.off() except exc.BadPinFactory as e: app.logger.warning( f"Unable to issue beep in this environment: {e}") except Exception as e: app.logger.error(f"Unknown problem with beep: {e}") app.logger.info("Finished beep")
class BuzzLevel: def __init__(self): self.buzzer = Buzzer(4) self.onTime = .01 self.offTime = .19 self.level = 0 self.active = False self.run() def beep(self, on): if on: self.buzzer.on() time.sleep(self.onTime) self.buzzer.off() time.sleep(self.offTime) else: time.sleep(self.onTime + self.offTime) def beepLevel(self): for i in range(self.level): self.beep(True) for i in range(5 - self.level): self.beep(False) def run(self): thread1 = threading.Thread(target = self._run, args = []) thread1.start() def _run(self): self.active = True while self.active: self.beepLevel() def setLevel(self, level): self.level = level def stop(self): self.active = False
class MyPanel(Panel): def __init__(self): Panel.__init__(self, 12, 9) self._point = Point(0, 0, 20, 20) self._buz = Buzzer(26) def render(self, canvas, delta): canvas.off_all() # canvas.draw_text(self.x, 1, 'SHAHAB') # self.x += -10 * delta # if self.x < -35: # self.x = 13 # # canvas.draw_char(0, 1, 'A') # canvas.draw_char(6, 1, 'B') canvas.on(self._point.x, self._point.y) self._point.x += self._point.vx * delta self._point.y += self._point.vy * delta if self._point.x <= 0: self._collision() self._point.vx = abs(self._point.vx) if self._point.x >= self.width - 1: self._collision() self._point.vx = -abs(self._point.vx) if self._point.y <= 0: self._collision() self._point.vy = abs(self._point.vy) if self._point.y >= self.height - 1: self._collision() self._point.vy = -abs(self._point.vy) def _collision(self): thread = Thread(target=self._play_sound) thread.start() def _play_sound(self): self._buz.on() sleep(.05) self._buz.off()
from gpiozero import Buzzer from time import sleep bz = Buzzer(23) while True: bz.on() sleep(0.2) bz.off() sleep(0.2)
import sys from gpiozero import Button, Buzzer import time button = Button(int(sys.argv[1])) buzzer = Buzzer(int(sys.argv[2])) begin = 0 end = 0 while True: if button.is_pressed: buzzer.on() if begin == end: begin = time.time() else: end = time.time() else: buzzer.off() if end != begin: print(end - begin) begin = end
while True: lcd.text('Please Enter \nPasscode!', 1) btn1.when_pressed = buttonOne btn2.when_pressed = buttonTwo if len(userpass) == len(password): lcd.clear() lcd.text('Authenticating...', 1) sleep(1) result = checkPass(userpass, password) if result is True: lcd.text('Passcode', 1) lcd.text('Correct!', 2) buzz.on() greenled.on() sleep(2) greenled.off() buzz.off() lcd.text('Initializing', 1) lcd.text('Face Scan...', 2) break else: lcd.text('Passcode', 1) lcd.text('Incorrect!', 2) buzz.on() redled.on() sleep(2) redled.off() buzz.off()
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: #get the players position now p = mc.player.getTilePos()
def temp_light(temperature): scale = set_temp - 20 if temperature < 20: return [0,0,255] else: temp_difference = set_temp - temperature backlight_colour = int((scale - temp_difference)*(255/scale)) return [(0 + backlight_colour), 0 , (255 - backlight_colour)] @joystick.on(joystick.UP) def handle_up(pin): global set_temp set_temp += 1 @joystick.on(joystick.DOWN) def handle_down(pin): global set_temp set_temp -= 1 while True: temperature = read_temp() lcd_text = "Water temp: " + str(round(temperature, 1)) + "Set temp: " + str(set_temp) lcd.clear() lcd.write(lcd_text) rgb_colours = temp_light(temperature) backlight.rgb(rgb_colours[0], rgb_colours[1], rgb_colours[2]) if temperature >= set_temp: bz.on() time.sleep(0.5)
elif lives == 1: life1.on() life2.off() life3.off() elif lives == 0: life1.off() life2.off() life3.off() lives = 3 life_counter(lives) while True: time.sleep(0.01) for i in range(2): buzzer.on() time.sleep(0.5) buzzer.off() time.sleep(0.5) while lives > 0: time.sleep(0.01) tool.wait_for_press() for i in range(3): buzzer.on() time.sleep(0.2) buzzer.off() time.sleep(0.2) time.sleep(0.1) print("You lost a life") lives = lives - 1 life_counter(lives)