def __init__(self, node1, node2, node3, node4): self.anode = InputDevice(node1) self.cathode = InputDevice(node2) self.node1 = node1 self.node2 = node2 self.node3 = node3 self.node4 = node4
def __init__(self, Channel=0, Frequency=434.250, Mode=1, DIO0=0, DIO5=0): self.SentenceCount = 0 self.ImagePacketCount = 0 self.sending = False self.listening = False self.CallbackWhenSent = None self.CallbackWhenReceived = None self.CurrentBandwidth = 20.8 self.FreqError = 0 if DIO0 == 0: if Channel == 1: DIO0 = 16 else: DIO0 = 25 if DIO5 == 0: if Channel == 1: DIO5 = 12 else: DIO5 = 24 self.Channel = Channel self.Frequency = Frequency self.Mode = Mode self.DIO0 = InputDevice(DIO0) self.DIO5 = InputDevice(DIO5) self.currentMode = 0x81 self.Power = PA_MAX_UK self.spi = spidev.SpiDev() self.spi.open(0, Channel) self.spi.max_speed_hz = 976000 self.__writeRegister(REG_DIO_MAPPING_2, 0x00) self.__SetLoRaFrequency(Frequency) self.__SetStandardLoRaParameters(Mode)
def __init__(self, remote_address): # set PINs on BOARD log.debug("Initializing Distance...") log.debug("> echo 1 pin: " + str(_conf['echo_1_pin'])) log.debug("> trig 1 pin: " + str(_conf['trig_1_pin'])) log.debug("> echo 2 pin: " + str(_conf['echo_2_pin'])) log.debug("> trig 2 pin: " + str(_conf['trig_2_pin'])) # using InputDevice and OutputDevice rem_pi = PiGPIOFactory(host=remote_address) self.distance1_trig = OutputDevice(pin=_conf['trig_1_pin'], pin_factory=rem_pi) self.distance1_echo = InputDevice(pin=_conf['echo_1_pin'], pin_factory=rem_pi) self.distance2_trig = OutputDevice(pin=_conf['trig_2_pin'], pin_factory=rem_pi) self.distance2_echo = InputDevice(pin=_conf['echo_2_pin'], pin_factory=rem_pi) # values self.distance1 = Value('i', 0) self.distance2 = Value('i', 0) # processes log.debug("Initializing Distance processes...") self.process1 = Process(target=self.D1) self.process2 = Process(target=self.D2) self.process1.start() self.process2.start() log.debug("...init done!")
def __init__(self, spi_bus=0, spi_device=0, spi_freq=12000000, verbose_level=VerboseLevel.NONE): # -------------------Hardware modules init------------------------ # Instanciate a SPI controller. self.spi = spidev.SpiDev() # Open SPI device self.spi.open(spi_bus, spi_device) # Configure SPI speed self.spi.max_speed_hz = spi_freq # Init interrup pin self.int_pin = InputDevice("GPIO6") self.reset_pin = OutputDevice("GPIO5") self.reset_pin.on() # -------------------Private variables definition------------------ self.video_mode = VideoMode.OBP self.video_status = VideoStatus.IDLE self.verbose_level = verbose_level self.video_data_size = 6400 self.serial = (0, 0, 0) self.temp_raw = 0 self.temp = 0 self.brightness_live_change = False self.contrast_live_change = False self.brightness_live_value = 0 self.contrast_live_value = 0
def water(): no_rain = InputDevice(27) buzzer = 12 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(buzzer, GPIO.OUT) while True: if not no_rain.is_active: print("Water detected") elif no_rain.is_active: #while True: #global waterstatus global count print("No water for", count, "hours") count = count + 1 if count == 3: GPIO.output(buzzer, GPIO.HIGH) print("Beep") GPIO.setup(11, GPIO.OUT) print("LED on") GPIO.output(11, GPIO.HIGH) time.sleep(1) #global buzzer #buzzer = True print("No water for", count, "hours") count = 0 #else: #continue sleep(5) return (count)
def __init__(self, Channel=0, Frequency=434.250, Mode=1, DIO0=0, DIO5=0): """ This library provides access to one LoRa (Long Range Radio) module on the PITS Zero board or the add-on board for the PITS+ board. The LoRa object is **non-blocking**. The calling code can either poll to find out when the transmission has completed, or can be notified via a callback. Channel should match the number of the position occupied by the LoRa module (as labelled on the LoRa board). The frequency is in MHz and should be selected carefully: - If you are using RTTY also, it should be at least 25kHz (0.025MHz) away from the RTTY frequency - It should be different to that used by any other HAB flights that are airborne at the same time and within 400 miles (600km) - It should be legal in your country (for the UK see [https://www.ofcom.org.uk/__data/assets/pdf_file/0028/84970/ir_2030-june2014.pdf](https://www.ofcom.org.uk/__data/assets/pdf_file/0028/84970/ir_2030-june2014.pdf "IR2030")) Mode should be either 0 (best if you are not sending image data over LoRa) or 1 (best if you are). When setting up your receiver, use matching settings. """ self.SentenceCount = 0 self.ImagePacketCount = 0 self.sending = False self.CallbackWhenSent = None if DIO0 == 0: if Channel == 1: DIO0 = 16 else: DIO0 = 25 if DIO5 == 0: if Channel == 1: DIO5 = 12 else: DIO5 = 24 self.Channel = Channel self.Frequency = Frequency self.DIO0 = InputDevice(DIO0) self.DIO5 = InputDevice(DIO5) self.currentMode = 0x81 self.Power = PA_MAX_UK self.spi = spidev.SpiDev() self.spi.open(0, Channel) self.spi.max_speed_hz = 976000 self.__writeRegister(REG_DIO_MAPPING_2, 0x00) self.SetLoRaFrequency(Frequency) self.SetStandardLoRaParameters(Mode)
def getEstado(estado_anterior, gpio=21): botao = InputDevice(21) # led = LED(26) estado = "desligado" if not botao.is_active: return not estado_anterior else: return estado_anterior
def build_power_detector() -> InputDevice: """ Creates a device for detecting power activity """ is_dev = get_config('dev_mode') if is_dev: Device.pin_factory = MockFactory() power_pin = get_config('device.power_pin') return InputDevice(power_pin)
def __init__(self, sensor_pin=None, switch_pin=None, light_pin=None, pin_factory=DefaultPinFactory()): self._pin_factory = pin_factory self.sensor = InputDevice(pin=sensor_pin, pin_factory=pin_factory) self.door = LED(pin=switch_pin, pin_factory=pin_factory) self.light = LED(pin=light_pin, pin_factory=pin_factory)
def __init__(self, pin, on_toggle, led_strip): self.pin = pin self.device = InputDevice(pin) self.last_state = False self.on_toggle = on_toggle self.led_strip = led_strip reactor.callLater(0, self.check_myself)
def __init__(self, pin, on_activation, on_deactivation): self.pin = pin self.device = InputDevice(pin) self.last_state = False self.on_activation = on_activation self.on_deactivation = on_deactivation callLater(0, self.check_myself)
def __init__(self) : # set PINs on BOARD log.debug("Initializing Rotary Encoder...") log.debug("> Button:" + str(_conf['btn_pin'])) self.btn = Button(_conf['btn_pin']) log.debug("> Clock:" + str(_conf['clock_pin'])) self.clock = InputDevice(_conf['clock_pin']) log.debug("> DT:" + str(_conf['dt_pin'])) self.dt = InputDevice(_conf['dt_pin']) # values self.counter = Value('i', 0) # processes log.debug("Initializing Rotary processes...") self.process = Process(target=self.worker) self.process.start() log.debug("...init done!")
def __init__(self, pin_no, pin_name=None): # Set initial variables to invalid value self.pin = InputDevice(pin_no) # Monitor variable self.prev_state = -1 self.prev_toggle_time = -1 self.toggle_period = -1 # Test variable self.has_toggled = False
def __init__(self, *args, **kwargs): super(Table, self).__init__(*args, **kwargs) self.switch = InputDevice(self.node_params["switch_pin"]) self.motor = Motor(self.node_params["motor_up_pin"], self.node_params["motor_down_pin"], self.node_params["up_down_minimum_delay"]) self.led = OutputDevice(self.node_params["led_pin"]) self.pull_delay = self.node_params["pull_delay"] self.led_task = None self.stop_motor_task = None self.check_switch_task = LoopingCall(self.check_switch) self.check_switch_task.start(1 / 25)
def main(): print("pi-rain-sensor launched.") tune = load_tune(args.tune) buzzer = Buzzer(args.pin_buzzer) rain_sensor = InputDevice(args.pin_sensor) while True: if rain_detected(rain_sensor): play_tune(buzzer, tune) sleep(args.buzzer_suspension_time) continue sleep(args.poll_time)
def __init__(self, ID, db, user, echoPin=24, triggerPin=23, waterPin=18, smellPin=17, buttonPin=20, LEDPin=26): self.ID = str(ID) self.US = DistanceSensor(echo=echoPin, trigger=triggerPin) self.water = InputDevice(waterPin) self.smell = InputDevice(smellPin) self.button = Button(buttonPin) self.button.when_pressed = self.button_pressed self.LED = LED(LEDPin) self.sensors = {'us': False, 'water': False, 'smell': False} self.needClean = self.sensors['us'] or self.sensors[ 'water'] or self.sensors['smell'] self.cleaning = False self.db = db self.user = user
def __init__(self, index, on_plug_callback, on_unplug_callback, reaction_pin, led_pin, success_color): self._color = None self.index = index self.on_plug_callback = on_plug_callback self.on_unplug_callback = on_unplug_callback self.reaction_pin = InputDevice(reaction_pin, pull_up=True) self.is_chopstick_plugged = self.reaction_pin.is_active self.led_pin = OutputDevice(led_pin) self.success_color = success_color
def get_pulse_time(trig_pin, echo_pin): ###### Add your echo and trig pin as an argument trig = OutputDevice(trig_pin) echo = InputDevice(echo_pin) trig.on() sleep(0.00001) trig.off() pulse_start = time() while echo.is_active == False: pulse_start = time() pulse_end = time() while echo.is_active == True: pulse_end = time() return pulse_end - pulse_start
def startService(): print(">> Water Level Monitoring Started!") global status sensor = InputDevice(18) x = 1 while True: if not sensor.is_active: if (x == 0): print("Tank Full!") status = 1 Relay.switch("post/motor", "0") MQTT_Publisher.publish("get/water", "1") x = 1 else: if (x == 1): status = 0 print("Water Level Dropped!") MQTT_Publisher.publish("get/water", "0") x = 0 sleep(1)
def __init__( self, plug_reactions, unplug_reactions, periodic_reactions, reaction_pin, led_index, led_success_color, ): self._difficulty = None self._led_color = None self.reaction_pin = InputDevice(reaction_pin) self.is_chopstick_plugged = self.reaction_pin.is_active self.led_index = led_index Letter.led_strip[self.led_index] = (0, 0, 0) self.led_success_color = led_success_color self.plug_reactions = {} for difficulty, reaction_method in plug_reactions.items(): self.plug_reactions[difficulty] = getattr( self, "reaction_{}".format(reaction_method)) self.unplug_reactions = {} for difficulty, reaction_method in unplug_reactions.items(): self.unplug_reactions[difficulty] = getattr( self, "reaction_{}".format(reaction_method)) self.periodic_reactions = periodic_reactions for _, reaction_task in self.periodic_reactions.items(): # Overwrite from string to actual method to ensure that all those methods exist # in order to reduce possible surprises during the game session. reaction_task["reaction"] = getattr( self, "reaction_{}".format(reaction_task["reaction"])) self.periodic_task = None self.delayed_reaction_task = None
from gpiozero import InputDevice, OutputDevice, PWMOutputDevice from math import e from threading import Thread from time import sleep, time # constants SPEED_OF_SOUND_CM = 34300 ULTRASOUND_MAX_RANGE = 400 ULTRASOUND_MIN_RANGE = 2 # see wolfram alpha for the decay curve. VIBRATION_EXPONENTIAL_DECAY_CONSTANT = 200 # ceiling sensing control gpio pins ceiling_trig = OutputDevice(4) ceiling_echo = InputDevice(17) ceiling_motor = PWMOutputDevice(22) # front sensing control gpio pins front_trig = OutputDevice(14) front_echo = InputDevice(15) front_motor = PWMOutputDevice(18) # left sensing control gpio pins left_trig = OutputDevice(10) left_echo = InputDevice(9) left_motor = PWMOutputDevice(11) # right sensing control gpio pins right_trig = OutputDevice(25) right_echo = InputDevice(8)
class RoPiDistance: # initialization def __init__(self, remote_address): # set PINs on BOARD log.debug("Initializing Distance...") log.debug("> echo 1 pin: " + str(_conf['echo_1_pin'])) log.debug("> trig 1 pin: " + str(_conf['trig_1_pin'])) log.debug("> echo 2 pin: " + str(_conf['echo_2_pin'])) log.debug("> trig 2 pin: " + str(_conf['trig_2_pin'])) # using InputDevice and OutputDevice rem_pi = PiGPIOFactory(host=remote_address) self.distance1_trig = OutputDevice(pin=_conf['trig_1_pin'], pin_factory=rem_pi) self.distance1_echo = InputDevice(pin=_conf['echo_1_pin'], pin_factory=rem_pi) self.distance2_trig = OutputDevice(pin=_conf['trig_2_pin'], pin_factory=rem_pi) self.distance2_echo = InputDevice(pin=_conf['echo_2_pin'], pin_factory=rem_pi) # values self.distance1 = Value('i', 0) self.distance2 = Value('i', 0) # processes log.debug("Initializing Distance processes...") self.process1 = Process(target=self.D1) self.process2 = Process(target=self.D2) self.process1.start() self.process2.start() log.debug("...init done!") # is close def is_close(self): distance1 = (self.distance1.value) < _conf['SAFETY_DISTANCE'] distance2 = (self.distance2.value) < _conf['SAFETY_DISTANCE'] log.debug("> is close ? " + str(distance1 or distance2)) return distance1 or distance2 # get distance 1 def get_distance1(self): log.debug("> Distance 1: " + str(self.distance1.value)) return self.distance1.value # get distance 2 def get_distance2(self): log.debug("> Distance 2: " + str(self.distance2.value)) return self.distance2.value # terminate def terminate(self): log.debug("Distance termination...") self.distance1_trig.close() self.distance1_echo.close() self.distance2_trig.close() self.distance2_echo.close() # control distance sensor 1 def D1(self): self.worker(self.distance1_trig, self.distance1_echo, self.distance1) # control distance sensor 1 def D2(self): self.worker(self.distance2_trig, self.distance2_echo, self.distance2) # worker def worker(self, trigger, echo, distance): while True: log.debug("Wait for sensor...") sleep(_conf['SENSORS_OFF_SPAN']) log.debug("Activate trigger...") trigger.on() sleep(_conf['TRIG_SPAN']) log.debug("Deactivate trigger...") trigger.off() log.debug("Calculate distance...") distance.value = self.calculate_distance( self.wait_for_signal(time(), echo), self.wait_for_distance(time(), echo)) # wait for pulse start def wait_for_signal(self, pulse_start, echo): log.debug("Wait for echo...") while echo.is_active == False: pulse_start = time() log.debug("echo started at:" + str(pulse_start)) return pulse_start # wait for pulse end def wait_for_distance(self, pulse_end, echo): log.debug("Wait for echo back...") while echo.is_active == True: pulse_end = time() log.debug("echo ended at:" + str(pulse_end)) return pulse_end # calculate distance def calculate_distance(self, pulse_start, pulse_end): log.debug("Calculate pulse duration...") pulse_duration = pulse_end - pulse_start distance = pulse_duration * _conf['SPEED_OF_SOUND'] log.debug("Distance is: " + str(distance)) return int(distance)
from guizero import App, Text, TextBox, PushButton import tkinter as tk import mysql.connector as mariadb import os from gpiozero import InputDevice from gpiozero import OutputDevice import time pir = InputDevice(17) def add(): t["state"] = "normal" b3["state"] = "normal" def enter(): print("opening recognizer..") os.system("python3 /home/pi/Documents/det_and_recog/recognizeface.py") def check(): mariadb_connection = mariadb.connect(user='******', password='******', database='securehome') cursor = mariadb_connection.cursor() cursor.execute("""SELECT Password FROM User WHERE Username = %s""", ("samrakhalid00", )) record = cursor.fetchall() for row in record:
#!/usr/bin/python3 import time import datetime from gpiozero import InputDevice, LED import subprocess import requests button_pin = 3 led_pin = 4 button = InputDevice(button_pin, pull_up=True) last_active = False last_press = None led = LED(led_pin) led.on() def button_hold(now, seconds): if seconds > 3: led.blink(.05, .5) requests.get('http://localhost:8080/home') time.sleep(2) subprocess.call(['shutdown', '-h', 'now'], shell=False) def button_release(now, seconds): requests.get('http://localhost:8080/button') while True: cur_active = button.is_active now = datetime.datetime.now() if cur_active and not last_active:
import time #Air quality import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(20, GPIO.IN) GPIO.setup(27, GPIO.OUT) #air quality #rain from time import sleep from gpiozero import Buzzer, InputDevice buzz = Buzzer(13) no_rain = InputDevice(18) def buzz_now(iterations): for x in range(iterations): buzz.on() sleep(0.1) buzz.off() sleep(0.1) #rain DHT_SENSOR = Adafruit_DHT.DHT22 DHT_PIN = 4 while(True): humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
import paho.mqtt.publish as publish import subprocess import re from mpu6050 import mpu6050 # Don't need the class, realized after I made it class Pi: def __init__(self, number, mA, mB, IMU): self.number = number self.mA = mA self.mB = mB self.IMU = IMU mSensor1 = InputDevice(17) mSensor2 = InputDevice(18) # i2c = busio.I2C(board.SCL, board.SDA) # msa = adafruit_msa301.MSA301(i2c) sensor = mpu6050(0x68) p1 = Pi(1, False, False, 1) def mqttInfo(): #msgs = [{'topic':"RPi/1", 'payload':p1.mA}, ("RPi/1", p1.mB, 0, False), ("RPi/1", p1.IMU, 0, False)] #publish.multiple(msgs, hostname="test.mosquitto.org") publish.single( "RPi/" + p1.number, p1.number + p1.mA[0] + p1.mB[0] + p1.IMU + "/" +
from time import sleep from gpiozero import InputDevice from firebase import firebase sensor = InputDevice(12) firebase = firebase.FirebaseApplication( 'https://smarthomeautomation-1aa7c.firebaseio.com/', None) x = 1 while True: if not sensor.is_active: if (x == 0): print("Tank Full!") firebase.put('', '/water', 1) x = 1 else: if (x == 1): print("Water Level Dropped!") firebase.put('', '/water', 0) x = 0 sleep(1)
from gpiozero import Robot, InputDevice, OutputDevice from time import sleep, time trig = OutputDevice(4) echo = InputDevice(17) olivia = Robot(right=(7, 8), left=(10, 9)) duration = 7 end_time = time() + duration running = True sleep(2) def get_pulse_time(): pulse_start, pulse_end = 0, 0 trig.on() sleep(0.00001) trig.off() while echo.is_active == False: pulse_start = time() while echo.is_active == True: pulse_end = time() return pulse_end - pulse_start
from time import sleep from gpiozero import InputDevice signal = InputDevice(21) #Pi pin 40 while True: if not signal.is_active: print("Moisture Detected") else: print("No moisture") sleep(1)
def rainy(): rain = InputDevice(18) if not rain.is_active: return 'It is raining' else: return 'Not raining'