Ejemplo n.º 1
0
 def disconnect():
     spi.close()  #ensures the correct disconnection from the radio module
     GPIO.cleanup()  #cleanup the GPIO setup for next use
     print("\n\nThe LCP scrip will now terminate!")
     time.sleep(1)
     exit()
     return
Ejemplo n.º 2
0
    def _setup_sensor(self):
        GPIO.cleanup()
        GPIO.setmode(GPIO.SUNXI)
        # Enable Filament Sensor
        if self.filament_sensor_enabled():
            self._logger.info("Filament Sensor active on GPIO Pin [%s]" %
                              self.pin)
            GPIO.setup(self.pin, GPIO.IN)
            try:
                GPIO.remove_event_detect(self.pin)
            except:
                self._logger.info("Pin " + str(self.pin) + " not used before")

            GPIO.add_event_detect(self.pin,
                                  GPIO.BOTH,
                                  callback=self.filament_sensor_callback,
                                  bouncetime=self.poll_time)

        # Enable Relay Sensor
        if self.relay_sensor_enabled():
            self._logger.info("Relay Sensor active on GPIO Pin [%s]" %
                              self.pin_relay)
            GPIO.setup(self.pin_relay, GPIO.IN)
            try:
                GPIO.remove_event_detect(self.pin_relay)
            except:
                self._logger.info("Pin " + str(self.pin_relay) +
                                  " not used before")

            GPIO.add_event_detect(self.pin_relay,
                                  GPIO.BOTH,
                                  callback=self.relay_sensor_callback,
                                  bouncetime=self.poll_time)
Ejemplo n.º 3
0
 def clearChannel(self,channel):
     try:
         GPIO.cleanup(self.toInt(channel))
     except Exception as ex:
         template = "An exception of type {0} occurred on clearChannel. Arguments:\n{1!r}"
         message = template.format(type(ex).__name__, ex.args)
         self._logger.warn(message)
         pass
Ejemplo n.º 4
0
def cleanAndExit():
    print "Cleaning..."

    if not EMULATE_HX711:
        GPIO.cleanup()

    print "Bye!"
    sys.exit()
Ejemplo n.º 5
0
 def cleanup(self):
     """Disable TX and RX and clean up GPIO."""
     if self.tx_enabled:
         self.disable_tx()
     if self.rx_enabled:
         self.disable_rx()
     _LOGGER.debug("Cleanup")
     GPIO.cleanup()
Ejemplo n.º 6
0
def test_mode():
    assert GPIO.getmode() is None
    GPIO.setmode(GPIO.BCM)
    assert GPIO.getmode() == GPIO.BCM
    GPIO.cleanup()
    assert GPIO.getmode() is None
    with pytest.raises(AssertionError):
        GPIO.setmode(54335)
Ejemplo n.º 7
0
def cleanup():
    if pwm != False:
        pwm.stop()

    # close the GPIO
    GPIO.cleanup()

    # stop the TL
    tl.stop()
Ejemplo n.º 8
0
def test_custom_dict():
    GPIO.cleanup()
    assert GPIO.getmode() is None
    with patch("OPi.GPIO.sysfs") as mock:
        GPIO.setmode({"A": 5, "B": 37})
        assert GPIO.getmode() is GPIO.CUSTOM
        GPIO.setup("A", GPIO.IN)
        mock.export.assert_called_with(5)
        mock.direction.assert_called_with(5, GPIO.IN)
        assert "A" in GPIO._exports
Ejemplo n.º 9
0
    def _unregister_leds(self):
        self._logger.debug(u"_unregister_leds()")
        for i in ('r', 'g', 'b', 'w'):
            if self._leds[i]:
                self._leds[i].ChangeDutyCycle(0)
                self._leds[i].stop()

        if not self._settings.get_boolean(['pigpiod']) and GPIO:
            GPIO.cleanup()
        self._leds = dict(r=None, g=None, b=None)
Ejemplo n.º 10
0
    def stop(self):
        """
    Stops PWM output.
    """
        self.toTerminate = True
        while self.terminated == False:
            # Just wait
            time.sleep(0.01)

        GPIO.output(self.gpioPin, GPIO.LOW)
        GPIO.cleanup()
Ejemplo n.º 11
0
    def destroy(self):
        if self.is_destroyed:
            return

        logger.debug("destroy")
        # shutdown all output-pins
        for output_pin in self._OutputPins:
            self.set_output(output_pin, 0, False)
        OPiGPIO.cleanup()
        doorpi.DoorPi().event_handler.unregister_source(__name__, True)
        self.__destroyed = True
Ejemplo n.º 12
0
def addpin():
    if request.method == 'POST':
        name = request.form['name']
        pin = request.form['pin']
        io = bool(int(request.form['io']))
        newpin = Pin(name=name, pin=pin, io=io)
        db.session.add(newpin)
        db.session.commit()
        GPIO.cleanup()
        setup_gpio()
        flash(f'Sucessfull add!', 'success')
        return redirect(url_for('index'))
Ejemplo n.º 13
0
def setup_gpio():
    print('Setting GPIO....')
    GPIO.cleanup()
    GPIO.setmode(GPIO.BOARD)
    GPIO.setwarnings(False)
    pins = Pin.query.all()
    for pin in pins:
        if pin.io:  # Output
            print('Set OUTPUT : ', pin.pin)
            GPIO.setup(pin.pin, GPIO.OUT, initial=GPIO.HIGH)
        else:  # Input
            print('Set INPUT : ', pin.pin)
            GPIO.setup(pin.pin, GPIO.IN)
Ejemplo n.º 14
0
 def read_tag_serial(self):
     GPIO.cleanup()
     MIFAREReader = MFRC522.MFRC522()
     (status, TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
     if status == MIFAREReader.MI_OK:
         (status, uid) = MIFAREReader.MFRC522_Anticoll()
         if status == MIFAREReader.MI_OK:
             result = hex(uid[0])[2:].zfill(2) + hex(uid[1])[2:].zfill(2) + hex(uid[2])[2:].zfill(2) + hex(uid[3])[2:].zfill(2)
             return result
         else:
             return None
     else:
         return None
Ejemplo n.º 15
0
def test_custom_object():
    class mapper(object):
        def __getitem__(self, value):
            return value + 4

    GPIO.cleanup()
    assert GPIO.getmode() is None
    with patch("OPi.GPIO.sysfs") as mock:
        GPIO.setmode(mapper())
        assert GPIO.getmode() is GPIO.CUSTOM
        GPIO.setup(11, GPIO.IN)
        mock.export.assert_called_with(15)
        mock.direction.assert_called_with(15, GPIO.IN)
        assert 11 in GPIO._exports
Ejemplo n.º 16
0
    def main(self):
        lastVolume = self.volume
        clkLastState = GPIO.input(config.clk)
        newVolume = lastVolume
        try:
            print("Started cattrotar!");
            while True:

                clkState = GPIO.input(config.clk)
                dtState = GPIO.input(config.dt)

                # see if we got a change since last iteration of loop
                if clkState != clkLastState:
                    if dtState != clkState:
                        newVolume += .5
                    else:
                        newVolume -= .5

                    # only if new volume has changed more than .5 and it's different than prior
                    # volume levels do we actually update volume
                    if newVolume % 1 == 0 and lastVolume != newVolume:
                        # reset button state to be up
                        self.button = 0

                        # set volume
                        newVolume = self.setVolume(newVolume)
                        lastVolume = newVolume

                # empty screen after 10 seconds
                if (time.time() - self.last_screen_update) > 10:
                    self.show(' ')

                clkLastState = clkState
                sleep(0.001)

        except KeyboardInterrupt:
            print("\nkeyboard killed the process")

        finally:
            self.show('Bye!')
            sleep(0.5)
            self.show(' ')
            self.show(' ')
            print('cattrotar exiting')
            GPIO.cleanup()
Ejemplo n.º 17
0
    def run(self):
        try:
            print("Press CTRL+C to exit")
            # This loop keeps checking for chips. If one is near it will get the UID and authenticate
            while self.continue_reading:
                # Scan for cards
                (status, TagType) = self.MIFAREReader.MFRC522_Request(
                    self.MIFAREReader.PICC_REQIDL)

                # If a card is found
                if status == self.MIFAREReader.MI_OK:
                    print("Card detected")

                (status, uid) = self.MIFAREReader.MFRC522_Anticoll()

                # If we have the UID, continue
                if status == self.MIFAREReader.MI_OK:
                    # Print UID
                    print("Card read UID: " + str(uid[0]) + "," + str(uid[1]) +
                          "," + str(uid[2]) + "," + str(uid[3]))

                # This is the default key for authentication
                key = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]

                # Select the scanned tag
                self.MIFAREReader.MFRC522_SelectTag(uid)

                # Authenticate
                status = self.MIFAREReader.MFRC522_Auth(
                    self.MIFAREReader.PICC_AUTHENT1A, 8, key, uid)

                # Check if authenticated
                if status == self.MIFAREReader.MI_OK:
                    self.MIFAREReader.MFRC522_Read(8)
                    self.MIFAREReader.MFRC522_StopCrypto1()
                else:
                    print("Authentication error")

        except KeyboardInterrupt:
            GPIO.output(7, 0)  # set port/pin value to 0/LOW/False
            GPIO.cleanup()  # Clean GPIO
            print("Bye.")
Ejemplo n.º 18
0
def main():
    print('Main started')
    button, led_button = setup_button()
    try:
        while True:
            GPIO.output(led_button, 1)
            print('Waiting for button')
            GPIO.wait_for_edge(button, GPIO.RISING)
            GPIO.output(led_button, 0)
            raw_image = get_camera_image()
            prepared_image = prepear_image(raw_image)
            print_image(prepared_image)
            wait_for_print_finish(led_button)
    except KeyboardInterrupt:
        print('Keyboard interrupt')
        GPIO.cleanup()
    finally:
        print('Cleanup')
        GPIO.output(led_button, 0)
        GPIO.cleanup()  # Double cleanup
        print('Finished')
Ejemplo n.º 19
0
    def watch(self):

        if self.device is not None:
            for event in self.device.read_loop():
                if event.type == 2:
                    if event.value == 1:
                        self._clockwise_tick()
                    elif event.value == -1:
                        self._counterclockwise_tick()
        else:

            while True:
                try:
                    # Switch part
                    if self.sw_callback:
                        if GPIO.input(self.sw) == GPIO.LOW:
                            self._switch_press()
                        else:
                            self._switch_release()

                    # Encoder part
                    clkState = GPIO.input(self.clk)
                    dtState = GPIO.input(self.dt)

                    if clkState != self.clk_last_state:
                        if dtState != clkState:
                            self._clockwise_tick()
                        else:
                            self._counterclockwise_tick()

                    self.clk_last_state = clkState
                    sleep(self.polling_interval / 1000)

                except BaseException as e:
                    logger.info("Exiting...")
                    logger.info(e)
                    GPIO.cleanup()
                    break
        return
Ejemplo n.º 20
0
 def clearGPIO(self):
     try:
         for control in self.temperature_control:
             if control['isEnabled']:
                 GPIO.cleanup(self.toInt(control['gpioPin']))
         for rpi_output in self.rpi_outputs:
             if self.toInt(rpi_output['gpioPin']) not in self.previous_rpi_outputs:
                 GPIO.cleanup(self.toInt(rpi_output['gpioPin']))
         for rpi_input in self.rpi_inputs:
             try:
                 GPIO.remove_event_detect(self.toInt(rpi_input['gpioPin']))
             except:
                 pass
             GPIO.cleanup(self.toInt(rpi_input['gpioPin']))
     except Exception as ex:
         template = "An exception of type {0} occurred on clearGPIO. Arguments:\n{1!r}"
         message = template.format(type(ex).__name__, ex.args)
         self._logger.warn(message)
         pass
Ejemplo n.º 21
0
 def dectivate(self):
     if is_arm_platform:
         GPIO.cleanup()
Ejemplo n.º 22
0
                time.sleep(0.1)
                if time.time() - btn_timestamp > 2:
                    # Long press. Play first.
                    longPressFlag = True
                    play_mpc_number(1)
                    while not GPIO.input(BTN_NEXT):
                        pass

            if not longPressFlag:
                # Short press
                previous_station()

        elif not GPIO.input(BTN_PAUSE):
            btn_timestamp = time.time()

            while not GPIO.input(BTN_PAUSE):
                time.sleep(0.1)
                if time.time() - btn_timestamp > 3:
                    # Long press.Shutdown.
                    cmd = ['poweroff']
                    run_process(cmd)
                    exit(0)

            # Short press
            tgl_mpc()

        time.sleep(0.1)

finally:  # this block will run no matter how the try block exits
    GPIO.cleanup()  # clean up after yourself
Ejemplo n.º 23
0
 def cleanup_gpio(event):
     """Stuff to do before stopping."""
     GPIO.cleanup()
Ejemplo n.º 24
0
def end_read(signal, frame):
    global continue_reading
    print("Ctrl+C captured, ending read.")
    continue_reading = False
    GPIO.cleanup()
Ejemplo n.º 25
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import OPi.GPIO as GPIO
from time import sleep

GPIO.setboard(GPIO.ZERO)
GPIO.setmode(GPIO.BOARD)  # set up BOARD BCM numbering
GPIO.setup(26, GPIO.OUT)  # set pin 26 as an output (LED)

p = GPIO.PWM(26, 10)  # new PWM on channel=26 frequency=10Hz
p.start(0)
try:
    while 1:
        for dc in range(0, 101, 5):
            p.ChangeDutyCycle(dc)
            sleep(0.1)
        for dc in range(100, -1, -5):
            p.ChangeDutyCycle(dc)
            sleep(0.1)
except KeyboardInterrupt:
    pass
p.stop()
GPIO.output(26, 0)
GPIO.cleanup()
def cleanup(self):
    GPIO.cleanup()
Ejemplo n.º 27
0
 def cleanup(self):
     self.fan_switch(False)
     GPIO.cleanup()
     self.logger.info('Cleanup')
#!/usr/bin/python3           address Python 3 environment
# -*- coding: utf-8 -*-



import OPi.GPIO as GPIO
from time import sleep          # this lets us have a time delay

numgpio=23						# As defined on Rasperry Pi 40 pins Connector. OK for Orange PI PC2 H5
GPIO.setmode(GPIO.BCM)        # set up  BCM numbering
GPIO.setup(numgpio, GPIO.OUT)         # set BCM7 (pin 26) as an output (LED)

try:
    print ("Square signal 50Hz on pin 16. Press CTRL+C to exit")
    while True:
        GPIO.output(numgpio, 1)       # set port/pin value to 1/HIGH/True
        sleep(0.01)
        GPIO.output(numgpio, 0)       # set port/pin value to 0/LOW/False
        sleep(0.01)

        

except KeyboardInterrupt:
    GPIO.output(numgpio, 0)           # set port/pin value to 0/LOW/False
    GPIO.cleanup()              # Clean GPIO
    print ("Bye from F1ATB.")
Ejemplo n.º 29
0
 def clearGPIOMode(self):
     GPIO.cleanup()
     return flask.jsonify(success=True)
LED_PIN = 7
GPIO.setup(LED_PIN, GPIO.OUT, initial=GPIO.LOW)

print "LED-Test [press ctrl+c to end]"

# main program loop
try:
    while True:
        print("LED is on for 4 seconds")
        GPIO.output(LED_PIN, GPIO.HIGH)  #LED will be switched on
        time.sleep(4)  # Waitmode for 4 seconds
        print("LED is off for 2 seconds")
        GPIO.output(LED_PIN, GPIO.LOW)  #LED will be switched off
        time.sleep(2)  # Waitmode for another 2 seconds

# Scavenging work after the end of the program
except KeyboardInterrupt:
    # here you put any code you want to run before the program
    # exits when you press CTRL+C
    print "An error or exception occurred!"

except:
    # this catches ALL other exceptions including errors.
    # You won't get any error messages for debugging
    # so only use it once your code is working
    print "Other error or exception occurred!"

finally:
    GPIO.cleanup()  # this ensures a clean exit
Ejemplo n.º 31
0
 def end_read(self, signal, frame):
     print("Ctrl+C captured, ending read.")
     self.continue_reading = False
     GPIO.cleanup()