Esempio n. 1
0
def setupButtons():
    global buttonLeft, buttonMiddle, buttonRight
    buttonLeft = Button(BUTTON_LEFT_GPIO_PIN)
    buttonMiddle = Button(BUTTON_MIDDLE_GPIO_PIN)
    buttonRight = Button(BUTTON_RIGHT_GPIO_PIN)

    buttonLeft.when_pressed = leftPressed
    buttonMiddle.when_pressed = middlePressed
    buttonRight.when_pressed = rightPressed

    buttonLeft.when_held = leftHeld
    buttonMiddle.when_held = middleHeld
    buttonRight.when_held = rightHeld

    buttonLeft.when_released = leftReleased
    buttonMiddle.when_released = middleReleased
    buttonRight.when_released = rightReleased

    buttonLeft.hold_time = 1
    buttonMiddle.hold_time = 1
    buttonRight.hold_time = 1

    buttonLeft.hold_repeat = True
    buttonMiddle.hold_repeat = True
    buttonRight.hold_repeat = True
Esempio n. 2
0
def main():
    # setup
    # See https://www.raspberrypi.org/documentation/usage/gpio/
    # Pins are on the edge of the connector, right next to each-other
    # Indicator should connect the positive side (anode, yellow wire) to GPIO pin 23
    # and negative side (cathode, orange wire) to ground
    # Button should connect 3V3 (blue wire) to GPIO pin 24 (green wire)
    away_indicator = PWMLED(pin=18, active_high=False, initial_value=False)
    home_indicator = LED(pin=23, active_high=False, initial_value=False)
    button = Button(pin=17, pull_up=False)
    button.when_held = handle_button
    button.hold_time = 0.5

    # Setup logging
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler()
    handler.setLevel(logging.INFO)
    handler.setFormatter(
        logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    logger.addHandler(handler)

    # This is used to communicate the state relatively "thread-safely"
    # to the Sopel bot
    presence_file = Path(PRESENCE_FILE)

    # Prime the state from file, defaults to False if file does not exist
    last_state = state = read_state(presence_file)

    logger.info('Starting main loop')

    while True:
        # Update the state from file
        state = read_state(presence_file)

        # Check if state changed
        if state != last_state:
            # Set LED based on the state
            if state:
                home_indicator.on()
                away_indicator.off()
            else:
                home_indicator.off()
                away_indicator.pulse(fade_in_time=1, fade_out_time=3)
            logger.info('Toggling LED state: %s', 'on' if state else 'off')
            last_state = state

        # Sleep before next round
        sleep(0.5)
Esempio n. 3
0
 def add_button(self, pin, name, pull_up=True, bounce_time=None, hold_time=None, hold_repeat=None):
     if self._button_map.has_key(pin):
         return
     # TODO: Reference http://stackoverflow.com/a/21986301/1846662 for a better way to call Button()
     if bounce_time > 0:
         button = Button(pin, pull_up, bounce_time)
     else:
         button = Button(pin, pull_up)
     if hold_time > 0:
         button.hold_time = hold_time
     if type(hold_repeat) is bool:
         button.hold_repeat = hold_repeat
     button.when_activated = self._handle_pressed
     button.when_deactivated = self._handle_released
     button.when_held = self._handle_held
     self._button_map[pin] = NamedButton(name, button, pin)
Esempio n. 4
0
configFile.close()

cpuLed = RGBLED(
    config.get('cpuLed').get('r'),
    config.get('cpuLed').get('g'),
    config.get('cpuLed').get('b'))
memLed = RGBLED(
    config.get('memLed').get('r'),
    config.get('memLed').get('g'),
    config.get('memLed').get('b'))
diskIoLed = LED(config.get('diskIoLed'))
diskLed = RGBLED(
    config.get('diskLed').get('r'),
    config.get('diskLed').get('g'),
    config.get('diskLed').get('b'))
netIoLed = LED(config.get('netIoLed'))
btLed = LED(config.get('btLed'))

rebootButton = Button(config.get('rebootButton'))
rebootButton.hold_time = 2
rebootButton.when_held = shutdown
rebootButton.when_released = reboot

disksBefore = 0
netBefore = 0

pairedBefore = False
connectedBefore = False

main()
Esempio n. 5
0
"""Camera software for Lego Minfig Portrait Studio."""

from datetime import datetime
from gpiozero import Button, LED
from time import sleep
from os import mkdir
import subprocess

button = Button(16)
button.hold_time = 6

light = LED(14)

# Flash light 3 times to indicate camera program is running
for x in range(3):
    light.off()
    sleep(.2)
    light.on()
    sleep(.2)

# on() turns OFF the LED because it pulls signal high on the pin
light.on()


def shutdown_pi():
    """Function to shutdown pi, called when button is pressed for over 6s."""
    # Flash light 3 times to indicate camera program is running
    light.on()
    for x in range(3):
        light.off()
        sleep(.2)
Esempio n. 6
0
def main(input_file, output_file, speed, debug=False):
    """
    Main control flow for Voice Assistant device.
    """
    GPIO.setmode(GPIO.BOARD)
    button = Button(17)
    button.hold_time = 2
    button.when_held = play_tutorial
    light = led.LED()
    # pull last saved speed from json
    with open('save_state.json', 'r') as saveFile:
        response = json.load(saveFile)
    speed = float(response['savedSpeed'])

    client = avs.connect_to_avs()
    dialog_req_id = [helpers.generate_unique_id()]
    audio_process = Processing(input_file, output_file, speed, 15)
    os.system("mpg321 audio_instrs/startup.mp3")

    # check if should play tutorial, requires holding for 2 sec
    time.sleep(5)

    if IN_TUTORIAL:
        print("hello in tutorial")
        time.sleep(78)

    if speed == 1:
        os.system("mpg321 " + menu_filenames[int(speed) - 1])
        light.flash(led.RED)
    elif speed == 2:
        os.system("mpg321 " + menu_filenames[int(speed) - 1])
        light.flash(led.GRN)
    else:
        os.system("mpg321 " + menu_filenames[int(speed) - 1])
        light.flash(led.BLUE)

    # reset hold time/when_held func to go to menu
    button.hold_time = 5
    button.when_held = partial(launch_menu, button, light, audio_process)

    try:
        while True:
            print("ready for input")
            light.change_color(led.GRN)

            # record from mic
            if input_file == "in.wav":
                button.wait_for_press()

                if button.is_pressed:
                    button.wait_for_release()

                if IN_MENU:
                    while IN_MENU:
                        pass
                    continue

                rec = Recording(input_file)
                light.change_color(led.BLU)
                rec.record(button)

            light.change_color(led.ALL)
            if debug:
                output_file = input_file
            else:
                audio_process.apply()

            # send to avs
            # outfiles = avs.send_rec_to_avs(output_file, client)
            outfiles = avs.send_rec_to_avs(output_file, client, dialog_req_id)

            # play back avs response
            light.change_color(led.PUR)
            if not outfiles:
                light.change_color(led.RED)
                os.system("mpg321 audio_instrs/alexa-noresponse.mp3")
                print("Error, no outfiles")
                time.sleep(1)

            for of in outfiles:
                print("playing: " + of)
                os.system("mpg321 " + of)

            if input_file == 'in.wav':
                print("Command completed! Waiting for new input!")
            else:
                light.interrupt()
                break

    except KeyboardInterrupt:
        light.interrupt()
Esempio n. 7
0
#captouch pin number
CAPPIN = 256
#location
LOCATION = "uk"

#music file
MUSIC = "person_cheering.wav"

print("Hello Maker Faire UK - Sqeeze button and Cap Touch")

#squeez button type
squeeze_button = Button(4)

#enable  button. Enable all buttons to trigger the capturing process
enable_button = Button(5)
enable_button.hold_time = 1.5

#enable_status: 1press-->enable; 2press-->disable; hold-->trigger the capturing process when enabled
enable_status = False

#emergency status led: on-->activated; off-->deactivated
status_led = LED(18)
status_led.off()

#emergency_status: emergency status is enabled with the emergency
#emergency_status is enable (True) when enable_status is True
emergency_status = False

#countdown led
countdown_led = LED(17)
countdown_led.off()
Esempio n. 8
0
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'
CLOCK_STATE = 'clock_state'

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 = CLOCK_STATE
play_to_score = 25
scores = [0, 0]

#States
def setup_online():
    global game_id
    global state
    global play_to_score
Esempio n. 9
0
from gpiozero import MotionSensor, LED, Button
from signal import pause
from time import sleep

## A little laggy, but button hold activates, then motion does set routing


myLed = LED(17) # pin 11 / GPIO17
pir = MotionSensor(27) # pin 13 GPIO27 (wonky zero GPIO02).. test on Pi3, works 0
# pir = MotionSensor(4) # as in pin 7, GPIO4.. works on Pi 3

## Button setup
button = Button(16) ## PiZero.. grr Pin 38 GPIO16, 3rd from end outside
# button = Button(20) # Pi3 standard map, GPIO20, pin 38
button.hold_time = 4 # secs?

## Action setting for single button press, i.e, busily do nothing
def btnPressFun():
    myLed.blink(.1)
    print("do nothing")
    pir.when_motion = noPicsFun

## Action sequence for after button held.
def btnHoldFun():
    myLed.blink(3)
    print("Run camera")
    sleep(12)
    myLed.off()
    pir.when_motion = cameraEmailFun

## This will be the big function to do everything    
Esempio n. 10
0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0", 1234))

# LED strip configuration:
LED_COUNT = 60  # Number of LED pixels. Change to 120 for both strips
LED_PIN = 21  # GPIO pin connected to the pixels (18 uses PWM!).     # GPIO pin connected$
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10  # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
LED_INVERT = False  # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0  # set to '1' for GPIOs 13, 19, 41, 45 or 53

button = Button(13)
button.hold_time = 0.1
pillowState = "0"


def lightShow(strip, color):
    for j in range(strip.numPixels() + 10):
        strip.setPixelColor(j, color)
        strip.setPixelColor(j - 10, Color(0, 0, 0))
        strip.show()
        time.sleep(0.03)


def pressed():
    lightShow(strip, Color(0, 0, 255))
    conn.send(bytes("1"))
    time.sleep(1)
Esempio n. 11
0
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
    end_result = manager.dict()
    end_result['description'] = ''
    end_result['text'] = ''
    end_result['emotion'] = ''

    main()
    while (engine.isBusy()):
        pass
Esempio n. 12
0
        print("Called reset")
        jamid.reset()
        mgr = intercom.Intercom(self)

if __name__ == "__main__":
    call_button = Button(26)
    reset_button = Button(17)

    if not jamid.is_daemon_running():
        jamid.start_daemon(debug=True)

    # Debounce invocations of on_conf_change
    handler = Handler()
    print("intercom manager started")
    debounce_call = Debouncer(call_button, handler.on_conf_change, edge='both')
    call_button.when_pressed = debounce_call
    call_button.when_released = debounce_call

    call_button.hold_time = 1
    # Already debounced based on hold_time
    call_button.when_held = handler.on_conf_held

    # Number of times pressed and length of time pressed don't matter here
    reset_button.when_pressed = handler.reset

    # this prevents receiving the hangup invite for some reason
    mgr = intercom.Intercom(handler)
    signal.signal(signal.SIGINT, mgr.interruptHandler)
    mgr.start()
    print("run complete")
Esempio n. 13
0
from gpiozero import Button
from gpiozero import LED
from time import sleep
import subprocess
from datetime import datetime

button = Button(5)
button.hold_time = 1.5

led = LED(18)
#Toggle button state. Default is False --> deactivated.
toggle_state = False
led.off()

countdown_led = LED(17)
countdown_led.off()

#Emergency state --> False when toggle_state is deactivated
emergency_state = False


def check_toggle():
    global toggle_state
    global emergency_state
    if not toggle_state and not emergency_state:  #light was off --> to on
        print("on")
        led.on()
        toggle_state = True
    else:  #light was on --> to off
        led.off()
        print("off")