Example #1
0
def set_alarm(timeout=5, n=5):
    bz = Buzzer(buzzer_pin)
    # bz.on()
    # time.sleep(timeout)
    # bz.off()
    bz.beep(on_time=0.5, off_time=0.5, n=n, background=False)
    bz.off()
Example #2
0
 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)
Example #3
0
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()
Example #4
0
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 Beeper:
    def __init__(self):
        self.bz = Buzzer(3)  # GPIO 3 for beep

    def lock(self):
        self.bz.beep(on_time=0.1, n=1, background=True)

    def unlock(self):
        self.bz.beep(on_time=0.05, off_time=0.15, n=2, background=True)

    def unAuth(self):
        self.bz.beep(on_time=0.5, off_time=0.3, n=3, background=True)
Example #6
0
while True:
    dados = {'offset': ultimo_id + 1}
    updates = get(endereco_updates, json=dados).json()
    
    if updates['ok']:
        result = updates['result']
        
        for r in result:
            mensagem = r["message"]
            if ("text" in mensagem):
                texto = mensagem['text']
                if texto == 'Abrir':
                    led1.on()
                elif texto == 'Soar alarme':
                    buzzer.beep(n=5, on_time=0.05, off_time=0.1)
                elif texto == 'Ignorar':
                    pass
                else:
                    buzzer.beep(n=2, on_time=0.5, off_time=0.5)
                    lcd.clear()
                    lcd.message("Mensagem\nrecebida!")
                    sleep(0.4)
                    lcd.clear()
                    sleep(0.4)
                    lcd.message("Mensagem\nrecebida!")
                    sleep(0.4)
                    lcd.clear()
                    sleep(0.4)
                    
                    texto = tirar_acentos(texto)
#-----------------------------------------------------------
# File name   : 03_activeBuzzer_1.py
# Description : Modify the buzzer to sound when button is pressed.
#
# Wiring      : See the Adeept Wiring PNG 02_activeBuzzer.png
#
# Pretty boring, but get introduced to a transistor.
#-----------------------------------------------------------

# Import Buzzer  and pause functions only... not the entire libraries
from gpiozero import Buzzer
from signal import pause

# Set pins for Buzzer control
myBuzz = Buzzer(18)  # GPIO18 / pin 12

# Use included function 'beep' to play the sound
# parameters are beep(on_time, off_time, repeat), with time in seconds
myBuzz.beep(1, 1, 40)

# ... to keep script running. That's it.
pause()
Example #8
0
        if bbox is not None:
            for i in range(len(bbox)):
                cv2.line(img,
                         tuple(bbox[i][0]),
                         tuple(bbox[(i + 1) % len(bbox)][0]),
                         color=(255, 0, 0),
                         thickness=2)

            cv2.putText(img, data,
                        (int(bbox[0][0][0]), int(bbox[0][0][1]), 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

            if data:
                sw1Press = False
                buzzer.beep(0.1, 0.1, 1)
                print("Data found: " + data)
                led.off()
                data = ""
                z = open('codigo_hexQR.txt', 'w')
                z.writelines(data)
                z.close()

                shutil.move(r".\codigo_hexQR.txt", r".\Hexcode")

        cv2.imshow("code detector", img)

    else:
        cap.read()
        cv2.destroyAllWindows()
but3.when_pressed = gravaAudio
but3.when_released = pararAudio

while True:
    endereco = endereco_base + "/getUpdates"
    dados = {"offset": proximo_id_de_update}
    resposta = get(endereco, json=dados)
    dic_da_resposta = resposta.json()

    for resultado in dic_da_resposta["result"]:
        mensagem = resultado["message"]
        if "text" in mensagem:
            texto = mensagem["text"]
            if (texto == "Abrir"):
                led1.on()
            elif (texto == "Alarme"):
                buzzer.beep(n=5, on_time=0.1, off_time=0.1)
        elif "voice" in mensagem:
            id_do_arquivo = mensagem["voice"]["file_id"]
            endereco = endereco_base + "/getFile"
            dados = {"file_id": id_do_arquivo}
            result = get(endereco, json=dados)
            dicionario = result.json()
            caminho = dicionario["result"]["file_path"]
            endereco_do_arquivo = "https://api.telegram.org/file/bot" + chave + "/" + caminho
            arquivo_de_destino = "meu_arquivo.ogg"
            urlretrieve(endereco_do_arquivo, arquivo_de_destino)
            player.loadfile(arquivo_de_destino)

        proximo_id_de_update = int(resultado["update_id"]) + 1
Example #10
0
def cam():
    os.system('fswebcam --no-banner imagetest')  #For clicking Pic


def action():
    cam()
    message = "Someone's at the door !!!"
    telegram_bot.sendMessage(761084539, message)  # Add Chat ID
    telegram_bot.sendPhoto(761084539, photo=open("imagetest"))


if __name__ == '__main__':
    while True:
        dist = distance()
        print(dist)
        if dist < 20:
            GPIO.output(24, True)
            time.sleep(0.5)
            GPIO.output(24, False)
            print("Motion Detected...")
            telegram_bot = telepot.Bot(
                '850662582:AAFZYs11fR_II-m7OAj2oGyhsiSqnz-PgwI')  # Token ID
            buzzer.beep()  #Buzzer turns on
            action()

            MessageLoop(telegram_bot, action)
            print('Running Perfectly fine !!!')
            buzzer.off()  #Buzzer turns off
            sleep(1)
        time.sleep(1)
Example #11
0
from gpiozero import MotionSensor, Buzzer
import time

pir = MotionSensor(4)
bz = Buzzer(3)

print("{} Waiting for PIR to stabilize".format(
    time.strftime("%B %d, %H:%M:%S")))
pir.wait_for_inactive()

while True:
    print("Ready")
    pir.wait_for_active()
    print("{0} Motion detected".format(time.strftime("%B %d, %H:%M:%S")))
    bz.beep(0.25, 0.5, 4)
    time.sleep(1)
Example #12
0
#-----------------------------------------------------------
# File name   : 03_buzzer_0.py
# Description : Wire up a simple on/off buzzer to play when
#               the script runs.
# Wiring      : Run a connection from the GPIO18 pin into the
#               positive end of the buzzer, then close the circuit
#               by tieing the negative end into ground.
#
# Pretty boring, but make buzzer sound programatically.
#-----------------------------------------------------------

# Import Buzzer  and pause functions only... not the entire libraries
from gpiozero import Buzzer
from signal import pause

# Set pins for Buzzer control
myBuzz = Buzzer(18)  # GPIO18 / pin 12

# Use included function 'beep' to play the sound
# parameters are beep(on_time, off_time, repeat), with time in seconds
myBuzz.beep(0.5, 1,
            3)  # buzz for 1/2 second, off for 1 second, repeat 3 timesz

# ... to keep script running. That's it.
pause()
Example #13
0
# make the bell ring

from gpiozero import Buzzer

ringer = Buzzer(23)

ringer.beep(on_time = .04, off_time = .04, n = 20)


Example #14
0
import time                                                                                                                         
from gpiozero import LightSensor, Buzzer #import LDR and Buzzer from GPIO pin zero
from time import sleep
from time import strftime
import datetime #Imports the date and time in to file
import paho.mqtt.publish as publish

ldr = LightSensor(4)
buzzer = Buzzer(17)
timestamp = datetime.datetime.now().strftime("%Y%m%d %H:%M:%S")
while True: #continuously checks the light level on LDR
    time.sleep(2) 
    if ldr is not None:
        f=open("lslog.csv", "a") #Creates log file for analytics
        if ldr.value < 0.8: #if LDR value falls below 0.5 buzzer will
            buzzer.beep(4) #how long the buzzer beeps for
            f.write(timestamp+","), #inserts time stamp in to analytics
            f.write("1"+","),       #Insertsmqttproject a one in to the analytics to show buzzer had sounded
            f.write(str(ldr)+"\n"),
            
            publish.single("mqtt-events", ldr.value, hostname="test.mosquitto.org")
        else:
            buzzer.off()
            f.write(timestamp +","),
            f.write("0"+","),     #Inserts 0 to show buzzer has not sounded at specified time
            f.write(str(ldr)+"\n"),
            

        f.close()
        time.sleep(2) 
    else:
Example #15
0
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")
          takephoto = "fswebcam -r "+resolution+" --no-banner"+" "+filename+"-"+date+".jpg"
          os.system(takephoto)
     	#User feedback
        print("Photos Taken")
        led.off()
        bz.off()
        #makegif
Example #16
0
from gpiozero import DistanceSensor, Buzzer
import picamera
import time

sensor = DistanceSensor(echo=24, trigger=23)
buzzer = Buzzer(3)
time.sleep(5)
print('Waiting for sensor to settle')

while True:
    d = sensor.distance
    print('Sensing...')

    if d <1:
        print('WARNING! Object detected {} meter away'.format(d))
        buzzer.beep(0.08, 0.08, 1)

    time.sleep(2)
import time
from gpiozero import LED, MotionSensor, Buzzer

motion_sensor = MotionSensor(4)
led = LED(2)
buzzer = Buzzer(17)

try:
    while True:
        motion_sensor.wait_for_active()
        print("Motion detected")
        buzzer.beep(n=2)
        led.blink(n=2)
        time.sleep(2)
finally:
    buzzer.off()
    led.off()
Example #18
0
from gpiozero import Buzzer

bz = Buzzer(17)
bz.on()
bz.beep(on_time=1, off_time=1, n=None, background=True)
Example #19
0
    stdout.write("\33[2K\r" + str(beat))
    stdout.flush()
    leds[led_num].on()
    buzzer.on()
    sleep(bpm)
    leds[led_num].off()
    buzzer.off()
    stdout.write("\33[2K\r")


while True:
    try:
        if beat == 1:
            stdout.write("\33[2K\r" + str(beat))
            leds[0].on()
            buzzer.beep(0.009, 0.009, 1)
            sleep(bpm)
            leds[0].off()
            beat = beat + 1
            stdout.write("\33[2k\r")
        elif beat == 2:
            flashBeep(1)
            beat = beat + 1
        elif beat == 3:
            flashBeep(2)
            beat = beat + 1
        elif beat == 4:
            flashBeep(3)
            beat = beat + 1
        elif beat == 5:
            measure_count = measure_count + 1
Example #20
0
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)

Example #21
0
from gpiozero import LED, Button, Buzzer
from time import sleep, time
from os import system
from signal import pause
import Adafruit_SSD1306
from PIL import Image

RST = 24
xshutter = Button(16)
xhalt = Button(21, hold_time=4)
xled = LED(5)
bz = Buzzer(10)
bz.beep(0.01, 0.01, 4)

# Flash LED on startup to indicate ready state
for i in range(0, 5):
    xled.on()
    sleep(0.2)
    xled.off()
    sleep(0.2)

disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
disp.begin()
tname = "xx"
t = 0


def takapik():
    global tname
    global t
    t = round(time())
botao = Button(11)

# loop infinito
init("aula", blocking=False)
botao.when_pressed = administrador

#print(coletar_digitos("Digite senha:"))
while True:
    if(sensor.distance <= 0.2):
        apt = coletar_digitos("Digite apto")
        #print("inicio")
        verifica = validar_apartamento(apt)
        if verifica == True:
            senha = coletar_digitos("Digite senha:")
            morador = retornar_nome_do_morador(apt,senha)
            if morador != None:
                lcd.clear()
                lcd.message("Bem vindo\n" + morador)
                colecao2.insert({"apartamento":apt, "data/hora": datetime.now(),"morador": morador})
            else:
                lcd.clear()
                lcd.message("Acesso\ninvalido")
                buzzer.beep(n=3, on_time=0.125, off_time=0.125)
                colecao2.insert({"apartamento":apt, "data/hora": datetime.now()})
        else:
            lcd.clear()
            lcd.message("Apartamento\ninvalido")
            buzzer.beep(n=2, on_time=0.25, off_time=0.25)
    sleep(1.5)

Example #23
0
from gpiozero import MotionSensor, Buzzer, LED
import time

pir = MotionSensor(23)
bz = Buzzer(24)
led = LED(18)
print("Waiting for PIR to settle")
pir.wait_for_no_motion()

while True:
    led.off()
    print("Ready")
    pir.wait_for_motion()
    led.on()
    print("Motion detected!")
    bz.beep(0.5, 0.25, 8)
    time.sleep(3)
Example #24
0
    class __impl:
        def __init__(self, logger):
            self.logger = logger
            self.state = State()
            self.serial = serial.Serial(
                port='/dev/serial0',
                baudrate=9600,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                bytesize=serial.EIGHTBITS,
                timeout=0)
            self.buzzer = Buzzer(4)
            self.led = LED(26)
            self.button = Button(12, True)
            self.button.when_pressed = lambda: self.toggleHypertrain()

            self.buffer = ''
            self.jsonParsePattern = regex.compile(r'\{(?:[^{}]|(?R))*\}')

            self.thread = threading.Thread(target=self.readThread)
            self.threadStop = False

        def toggleHypertrain(self):
            self.state.Stopped = not self.state.Stopped
            # self.state.Loaded = not self.state.Loaded
            self.logger.info(
                "Button pressed, new state Stopped: " + str(self.state.Stopped))
            self.led.blink(1, 1, 1)
            if (self.state.Stopped):
                self.sendStartStop('stop')
                self.state.reset()
            else:
                self.sendStartStop('start')

        def sendStartStop(self, action):
            data = {}
            data['sender'] = 'raspberry'
            data['action'] = action
            self.write(json.dumps(data))

        def sendApproachStop(self):
            data = {}
            data['sender'] = 'raspberry'
            data['action'] = 'approachstop'
            self.write(json.dumps(data))

        def sendSpeedPercent(self, acceleration):
            if (acceleration != self.state.LastAccelerationPercent):
                self.state.LastAccelerationPercent = acceleration
                data = {}
                data['sender'] = 'raspberry'
                data['action'] = 'accelerate'
                data['payload'] = acceleration
                self.write(json.dumps(data))

        def buzzSignalNumber(self, num):
            self.buzzer.beep(0.3, 0.3, num)

        def readThreadStart(self):
            self.thread.start()

        def readThreadStop(self):
            self.threadStop = True

        def readThread(self):
            while (not self.threadStop):
                self.read()
                time.sleep(self.state.ThreadSleepingThreshold)

        def read(self):
            if (self.serial.in_waiting > 0):
                while self.serial.inWaiting():
                    asciiBytes = self.serial.read(self.serial.inWaiting())
                    if (asciiBytes):
                        self.buffer += asciiBytes.decode('ascii')

                for incoming in self.extractJSONObjects(self.buffer):
                    self.parse(str(incoming).replace("'", '"'))

        def write(self, message):
            if (message):
                self.logger.info("Sending: " + message)
                self.serial.write(message.encode())

        def parse(self, message):
            jsonObj = None
            try:
                jsonObj = json.loads(message)
                if (jsonObj["sender"] == "arduino"):
                    if (jsonObj["action"] == "loaded"):
                        self.led.blink(1, 1, 1)
                        self.buzzSignalNumber(1)
                        if (not self.state.Loaded):
                            self.state.Loaded = True
                    if (jsonObj["action"] == "speed"):
                        return
                    if (jsonObj["action"] == "way" and jsonObj["payload"]):
                        self.logger.debug("Way: " + message)
                        self.state.CoveredDistance = int(
                            jsonObj["payload"])
                        return

                self.logger.debug("Receiving: " + message)

            except AttributeError as e:
                self.logger.error(
                    "AttributeError in JSON: " + str(e))
            except Exception as e:
                self.logger.error("Unknown message: " + str(e))
                self.logger.error(message)

        def extractJSONObjects(self, text, decoder=JSONDecoder()):
            pos = 0
            while True:
                match = text.find('{', pos)
                if match == -1:
                    break
                try:
                    result, index = decoder.raw_decode(text[match:])
                    yield result
                    pos = match + index
                    # now strip the match from our buffer
                    self.buffer = self.buffer[pos:]
                except ValueError:
                    pos = match + 1
Example #25
0
from gpiozero import Buzzer
from time import sleep

buz = Buzzer(2)
while 1:
    buz.beep(0.5, 0.5, 1)
Example #26
0
from gpiozero import Button, Buzzer

button = Button(4)
buzzer = Buzzer(23)

while (True):
    button.wait_for_release()
    print("Door opened")
    buzzer.beep(1, 0, 1)

    button.wait_for_press()
    print("Door closed")
Example #27
0
from gpiozero import Button, TrafficLights, Buzzer
from time import sleep
lights = TrafficLights(25, 8, 7)

button = Button(21)
buzzer= Buzzer(15)


while True:
      button.wait_for_press()
      lights.green.on()
      sleep(1)
      lights.amber.on()
      sleep(1)
      lights.red.on()
      sleep(1)
      lights.off()
      buzzer.beep()
Example #28
0
 
SensorPrevSec = 0
SensorInterval = 2 # 2 seconds
ThingSpeakPrevSec = 0
ThingSpeakInterval = 20 # 20 seconds
 
try:
 while True:
 
 if time() – SensorPrevSec > SensorInterval:
 SensorPrevSec = time()
 
 humidity, temperature = Adafruit_DHT.read_retry(SENSOR_TYPE, SENSOR_PIN)
 print("Humidity = {:.2f}%\tTemperature = {:.2f}C".format(humidity, temperature))
 
 if time() – ThingSpeakPrevSec > ThingSpeakInterval:
 ThingSpeakPrevSec = time()
 
 thingspeakHttp = BASE_URL + "&field1={:.2f}&field2={:.2f}".format(temperature, humidity)
 print(thingspeakHttp)
 
 conn = urlopen(thingspeakHttp)
 print("Response: {}".format(conn.read()))
 conn.close()
 
 buzzer.beep(0.05, 0.05, 1)
 sleep(1)
 
except KeyboardInterrupt:
 conn.close()
Example #29
0
buzzer = Buzzer(26)

serialPort = serial.Serial("/dev/ttyUSB0", 9600, timeout=0.5)

def sw1Pressed():
    serialPort.write("SW1 Pressed".encode('utf-8'))

def sw2Pressed():
    serialPort.write("SW2 Pressed".encode('utf-8'))

def sw3Pressed():
    serialPort.write("SW3 Pressed".encode('utf-8'))

sw1.when_pressed = sw1Pressed
sw2.when_pressed = sw2Pressed
sw3.when_pressed = sw3Pressed

try:
    while True:
        command = serialPort.read_until('\0', size=None)
        commandString = command.decode('utf-8')
        if len(commandString) > 0:
            print(commandString)
            if commandString == "Button Pressed":
                led1.on()
                buzzer.beep(0.1, 0.1, 2)
                led1.off()

except KeyboardInterrupt:
    led1.off()
    buzzer.off()
#-----------------------------------------------------------
# File name   : 03_activeBuzzer_0.py
# Description : Wire up a simple on/off buzzer to play when
#               the script runs.
# Wiring      : See the Adeept Wiring PNG 02_activeBuzzer.png
#
# Pretty boring, but get introduced to a transistor.
#-----------------------------------------------------------

# Import Buzzer  and pause functions only... not the entire libraries
from gpiozero import Buzzer
from signal import pause

# Set pins for Buzzer control
myBuzz = Buzzer(18)  # GPIO18 / pin 12

# Use included function 'beep' to play the sound
# parameters are beep(on_time, off_time, repeat), with time in seconds
myBuzz.beep(2, 1)

# ... to keep script running. That's it.
pause()
Example #31
0
	led.on() # or, led.blink() or, led.blink(2,2) which means 2 seconds on, 2 seconds off
	button.wait_for_release()
	led.off()"""


from gpiozero import Button, Buzzer, LED
from time import sleep 

red = LED(25)
amber = LED(8)
green = LED(7)
buzzer = Buzzer(15)

while True: 
	button.wait_for_press()
	red.on
	buzzer.beep(.01,1)
	sleep(1)
	amber.on()
	buzzer.beep(.01,1)
	sleep(1)
	green.on()
	buzzer.beep(.01,1)
	buzzer.off()
	sleep(1)
	red.off()
	amber.off()
	green.off()
	

Example #32
0
from gpiozero import Button, TrafficLights, Buzzer
from time import sleep

button = Button(21)
lights = TrafficLights(25, 8, 7)
buzzer = Buzzer(15)

while True:
    buzzer.beep(1)
    lights.green.on()
    sleep(20)
    buzzer.beep(0.5, 0.5)
    lights.green.blink(0.5, 0.5)
    sleep(3)
    lights.green.off()
    buzzer.beep(1)
    lights.amber.on()
    sleep(2)
    buzzer.beep(0.5, 0.5)
    lights.amber.blink(0.5, 0.5)
    sleep(3)
    lights.amber.off()
    buzzer.beep(1)
    lights.red.on()
    sleep(20)
    lights.red.off()