def setup(self): # configure default audio output os.system("amixer -q cset numid=3 1") # hijack the Ctrl+C event and run teardown() signal.signal(signal.SIGINT, self.teardown) # setup the board type and clean the board config GPIO.setmode(GPIO.BOARD) GPIO.cleanup() # configure inputs and outputs GPIO.setup(self.PIN_LED_GREEN, GPIO.OUT) # green led GPIO.setup(self.PIN_LED_RED, GPIO.OUT) # red led GPIO.setup(self.PIN_TILT_SWITCH, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.PIN_EXT_SWITCH, GPIO.IN, pull_up_down=GPIO.PUD_UP) # add an event listener and callback function for the ext switch GPIO.add_event_detect(self.PIN_EXT_SWITCH, GPIO.RISING, bouncetime=500) GPIO.add_event_callback(self.PIN_EXT_SWITCH, self.EXT_SWITCH_CALLBACK, bouncetime=500) #GPIO.add_event_callback(self.PIN_EXT_SWITCH, self.extSwitchCallBack, bouncetime=200) # add an event listener and callback function for the tilt switch GPIO.add_event_detect(self.PIN_TILT_SWITCH, GPIO.RISING, bouncetime=500) GPIO.add_event_callback(self.PIN_TILT_SWITCH, self.TILT_SWITCH_CALLBACK, bouncetime=500) #GPIO.add_event_callback(self.PIN_TILT_SWITCH, self.tiltSwitchCallBack, bouncetime=500) # turn on the LEDs for 1 seconds to indicated that player booted up self.toggleGreenLed() self.toggleRedLed() time.sleep(1) self.toggleGreenLed() self.toggleRedLed() # wait until Ctrl+C is pressed signal.pause()
def __init__(self, pin, value=0, callback=None, edge=edges.BOTH, bouncetime=None, header=None): """ :param pin: GPIO pin to setup as an input. :param value: Pull-up/down resistor value. :type callback: callable :param callback: Callback function for edge event. Must :param edge: Edge event to detect. :param bouncetime: Time in ms to ignore further edge events. :type header: Header :param header: Header with which to register input pin assignments, for eventual clean-up. """ self._pin = int(pin) self._edge = _edge_to_rpi_edge[edge] self._header = header GPIO.setup(self._pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN if value == 0 else GPIO.PUD_UP) event_kwargs = {} if bouncetime: event_kwargs['bouncetime'] = bouncetime GPIO.add_event_detect(gpio=self._pin, edge=self._edge, **event_kwargs) if callable(callback): GPIO.add_event_callback(self._pin, callback) if header is not None: header.registerPinForCleanup(self)
def __init__(self, trigger, echo, rango, continuous=None, name=''): self.trigger = trigger self.echo = echo self.name = str(name) GPIO.setup(trigger, GPIO.OUT) GPIO.setup(echo, GPIO.IN) self._pulse_start = 0 self._pulse_end = 0 self._rango = rango self.__trigger_timer = None self._avgq = deque(maxlen=5) # setup events and callback GPIO.add_event_detect(self.echo, GPIO.BOTH) GPIO.add_event_callback(self.echo, self._set_times) # settle the sensor GPIO.output(self.trigger, GPIO.LOW) if continuous: self.continuous_read(float(continuous))
def __init__(self, id, json_config): Sensor.__init__(self, id, json_config) self.change_detected = True io.setup(self.config.pin_id, io.IN) io.add_event_detect(self.config.pin_id, io.BOTH, bouncetime=(self.config.no_movement_timeout_s*1000)) print("Setting up sensor on pin: "+str(self.config.pin_id)) io.add_event_callback(self.config.pin_id, self.motion_detected)
def test_rising(): def cb(chan): xprint('Callback 1 - this should produce an exception') def cb2(chan): print('Callback 2 called - channel %s'%chan) print('Rising edge test') print('5 second sample for event_detected function') try: GPIO.add_event_detect(LED_PIN, GPIO.RISING) print('Fail - added event to an output, not produced RuntimeError') except RuntimeError: pass GPIO.add_event_detect(SWITCH_PIN, GPIO.RISING) time.sleep(5) if GPIO.event_detected(SWITCH_PIN): print('Event detected') else: print('Event not detected') print('5 seconds for callback function (which should produce exceptions)') input('Press return to start: ') GPIO.add_event_callback(SWITCH_PIN, cb) GPIO.add_event_callback(SWITCH_PIN, cb2) time.sleep(5) GPIO.remove_event_detect(SWITCH_PIN); print('Blocking wait for rising edge...') GPIO.wait_for_edge(SWITCH_PIN, GPIO.RISING)
def test_rising(): def cb(chan): print "Callback 1 - this should produce an exception" def cb2(chan): print "Callback 2 called - channel", s, chan print "Rising edge test" print "5 second sample for event_detected function" try: GPIO.add_event_detect(LED_PIN, GPIO.RISING) print "Fail - added event to an output, not produced RuntimeError" except RuntimeError: pass GPIO.add_event_detect(SWITCH_PIN, GPIO.RISING) time.sleep(5) if GPIO.event_detected(SWITCH_PIN): print "Event detected" else: print "Event not detected" print "5 seconds for callback function (which should produce exceptions)" input ("Press return to start: ") GPIO.add_event_callback(SWITCH_PIN, cb) GPIO.add_event_callback(SWITCH_PIN, cb2) time.sleep(5) GPIO.remove_event_detect(SWITCH_PIN); print "Blocking wait for rising edge..." GPIO.wait_for_edge(SWITCH_PIN, GPIO.RISING)
def main(): GPIO.setmode(GPIO.BCM) GPIO.setup(2,GPIO.IN) GPIO.add_event_detect(2,GPIO.FALLING) GPIO.add_event_callback(2,buttonEventHandler,100) GPIO.cleanup()
def pwr_state(): pin = (pins['led']) try: GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) class Counter(object): def __init__(self, start=0): self.x = start def __call__(self, channel): self.x += 1 return self.x count = Counter() GPIO.add_event_detect(pin, GPIO.RISING) GPIO.add_event_callback(pin, count) time.sleep(1.2) GPIO.remove_event_detect(pin) if (count.x > 0): print "sleep" elif (GPIO.input(pin)): print "on" else: print "off" finally: GPIO.cleanup()
def __init__(self, setmode = True): if setmode: GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers GPIO.setup(LCD_E, GPIO.OUT) # E GPIO.setup(LCD_RS, GPIO.OUT) # RS GPIO.setup(LCD_D4, GPIO.OUT) # DB4 GPIO.setup(LCD_D5, GPIO.OUT) # DB5 GPIO.setup(LCD_D6, GPIO.OUT) # DB6 GPIO.setup(LCD_D7, GPIO.OUT) # DB7 GPIO.setup(LED_ON, GPIO.OUT) # Backlight enable GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # LED Light Switch # Initialise display self.lcd_init() # Toggle backlight off-on GPIO.output(LED_ON, False) time.sleep(1) GPIO.output(LED_ON, True) # LED Light Switch Event self.led_state = True self.led_last_event = time.time() GPIO.add_event_detect(4, GPIO.RISING, bouncetime=700) GPIO.add_event_callback(4, self.toggle_light) print "LCD Initialised"
def main(): GPIO.setmode(GPIO.BOARD) print "Current Board Revision: ", GPIO.RPI_REVISION print "Current Board Version: ", GPIO.VERSION GPIO.setup(12, GPIO.OUT) GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(11, GPIO.BOTH) GPIO.add_event_callback(11, my_callback) if GPIO.input(11): print('Input was HIGH') else: print('Input was LOW') print "Initial state of pin 12 is: ", GPIO.input(12) GPIO.output(12, GPIO.HIGH) print "State at stage 1 of pin 12 is: ", GPIO.input(12) if GPIO.input(11): print('State at stage 1 is HIGH') else: print('State at stage 1 is LOW') GPIO.output(12, GPIO.LOW) print "State at stage 2 of pin 12 is: ", GPIO.input(12) GPIO.cleanup() print "a = ", a
def interrupt(self, callback, pin, pull_up_down=None, bouncetime=200): """Init interrupt callback function for pin. Args: callback (function): function to call on interrupt pin (int): the pin to monitor for interrupts """ with self._gpio_lock: if pull_up_down is not None: if pull_up_down: GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Use falling detection since we are pulled up GPIO.add_event_detect( pin, GPIO.FALLING, bouncetime=bouncetime) else: GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Use rising detection since we are pulled down GPIO.add_event_detect( pin, GPIO.RISING, bouncetime=bouncetime) else: GPIO.setup(pin, GPIO.IN) GPIO.add_event_detect(pin, GPIO.BOTH, bouncetime=bouncetime) GPIO.add_event_callback(pin, callback) self.logger.debug( "Set interrupt callback of GPIO pin {}".format(pin))
def main(): global card_id # setup yhy522 Card Reader to callback on card present rfid.Sense_Mode(0x01) channel = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(channel, GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.add_event_detect(channel, GPIO.FALLING) GPIO.add_event_callback(channel, read_card_send_MQTT, bouncetime=400) # loop to detect when card is removed while 1: continue # Read the Card ID and compare with the previously stored value try: newly_read_card_id = rfid.Card_ID() if not(card_id == newly_read_card_id): card_id = newly_read_card_id payload = ', '.join(map(str, card_id)) client.publish("/fablab/log/laser/black", payload, 0) except: print("Could read card ID") client.loop() # Need to call this to process MQTT messages time.sleep(1)
def main(): initRadio() GPIO.add_event_detect(13,GPIO.FALLING) GPIO.add_event_callback(13,handleMsgReceived) while(True): time.sleep(10) pass
def main(): global button_push # tell the GPIO module that we want to use # the chip's pin numbering scheme GPIO.setmode(GPIO.BCM) # setup pin 23 as an input # and set up pins 24 and 25 as outputs GPIO.setup(23,GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(24,GPIO.OUT) GPIO.setup(25,GPIO.OUT) # tell the GPIO library to look out for an # event on pin 23 and deal with it by calling # the buttonEventHandler function GPIO.add_event_detect(23,GPIO.FALLING, bouncetime=200) GPIO.add_event_callback(23,buttonEventHandler) # turn off both LEDs GPIO.output(25,False) GPIO.output(24,True) # make the red LED flash while True: GPIO.output(24,True) time.sleep(1) GPIO.output(24,False) time.sleep(1) print ("main ", button_push) if button_push > 7: button_push = 0 GPIO.cleanup()
def change(self, fn, edge=edges.BOTH): """Allow for `@change` decorator""" def wrapped(pin): fn(self.value) GPIO.add_event_callback(self._pin, wrapped, _edge_to_rpi_edge[edge])
def setup(lights, buttons): GPIO.setmode(GPIO.BOARD) GPIO.setup(buttons, GPIO.IN, pull_up_down=GPIO.PUD_UP) for button in buttons: GPIO.add_event_detect(button, GPIO.FALLING, bouncetime=200) GPIO.add_event_callback(button, button_push) GPIO.setup(lights, GPIO.OUT, initial=GPIO.HIGH)
def main(): pin = 11 GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(pin, GPIO.RISING) GPIO.add_event_callback(pin,takepic,100) while True: GPIO.wait_for_edge(pin) GPIO.cleanup()
def __init__(self, pin, value=0, callback=None, edge=edges.BOTH, bouncetime=0): self._pin = int(pin) self._edge = _edge_to_rpi_edge[edge] GPIO.setup(self._pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN if value == 0 else GPIO.PUD_UP) GPIO.add_event_detect(self._pin, self._edge, bouncetime=bouncetime) if callback is not None: GPIO.add_event_callback(self._pin, callback)
def readCompass(channel): # Setup button GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(channel, GPIO.IN, GPIO.PUD_UP) GPIO.add_event_detect(channel, GPIO.FALLING, bouncetime=3000) GPIO.add_event_callback(channel, runCam) while True: time.sleep(0.1)
def watch(self): # This line tells our script to keep an eye on our gpio pin and let us know when the pin goes HIGH or LOW GPIO.add_event_detect(self.v_GPIO_pin, GPIO.BOTH, bouncetime=300) # This line asigns a function to the GPIO pin so that when the above line tells us there is a change on the pin, run this function GPIO.add_event_callback(self.v_GPIO_pin, self.v_callback_function) time.sleep(sys_config['min_sensor_interval']) print "watching..." return
def initHeatingMassFlowPulseCounter (self): gpio.setmode(gpio.BOARD) gpio.setup(16, gpio.IN) def incrementHeatingMassFlowPulseCounter ( pin ): # callback-function global HeatingMassFlowPulseCounter HeatingMassFlowPulseCounter = HeatingMassFlowPulseCounter+1 print(HeatingMassFlowPulseCounter) gpio.add_event_detect(16, gpio.FALLING, bouncetime = 100) gpio.add_event_callback(16, incrementHeatingMassFlowPulseCounter)
def add_edge_callback(self, callback, type_=None): """Adds a callback to execute as soon as an edge was detected :callback: TODO :type_: TODO :returns: TODO """ if type_: self.add_edge_detection(type_) _GPIO.add_event_callback(self.gpio, callback)
def __init__(self): self.tick_counter = 0 if geiger_simulate: self.simulator = threading.Thread(target=self.simulate_ticking) self.simulator.daemon = True self.simulator.start() else: GPIO.setmode(GPIO.BCM) GPIO.setup(GPIO_PIGI,GPIO.IN) GPIO.add_event_detect(GPIO_PIGI,GPIO.FALLING) GPIO.add_event_callback(GPIO_PIGI,self.tick)
def __init__(self, filename, gpio_pin): # Setup player self.__gpio_pin = gpio_pin self.__playing = False # start mixer and load music pygame.mixer.init() pygame.mixer.music.load(filename) # Setup GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(gpio_pin, GPIO.IN) GPIO.add_event_detect(gpio_pin, GPIO.BOTH) GPIO.add_event_callback(gpio_pin, self.update_state) self.update_state(gpio_pin)
def __init__(self, pin, value=0, callback=None, edge=edges.BOTH, bouncetime=0, header=None): self._pin = int(pin) self._edge = _edge_to_rpi_edge[edge] self._header = header GPIO.setup(self._pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN if value == 0 else GPIO.PUD_UP) GPIO.add_event_detect(self._pin, self._edge, bouncetime=bouncetime) if callback is not None: GPIO.add_event_callback(self._pin, callback) if header != None: header.registerPinForCleanup(self)
def setGpioInput(pin_number, pull_up_down, call_back_func, bounce_time): if (pin_number not in Pi_Non_GPIO_Pin_List) and pin_number<=30: setting = GPIO.gpio_function(pin_number) #if setting==GPIO.IN: # return GPIO.setup(pin_number, GPIO.IN, pull_up_down) GPIO.add_event_detect(pin_number, GPIO.BOTH) #if pull_up_down==GPIO.PUD_UP: # GPIO.add_event_detect(pin_number, GPIO.FALLING) #elif pull_up_down==GPIO.PUD_DOWN: # GPIO.add_event_detect(pin_number, GPIO.RISING) #if call_back_func in vars(): GPIO.add_event_callback(pin_number, call_back_func, bounce_time)
def main(): import RPi.GPIO as GPIO import logging, logging.handlers logger = logging.getLogger("ringd") logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s %(message)s") handler = logging.handlers.RotatingFileHandler(LOGFILE, maxBytes=5242880, backupCount=5) handler.setFormatter(formatter) logger.addHandler(handler) def capture_photo(*args, **kwargs): cap = cv2.VideoCapture(0) ret, frame = cap.read() if ret: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(frame) (w, h) = image.size draw = ImageDraw.Draw(image) draw.text((20, h - 20), "{0:%Y-%m-%d %H:%M:%S}".format(datetime.today()), fill="black") del draw filename = "{0:%Y-%m-%d_%H:%M:%S}.jpg".format(datetime.today()) image.save(filename) logger.info("Captured file %s from webcam. Someone behind the door!" % filename) return True return False def tweet_photo(api, filename): try: api.update_with_media(filename, status="Ура! Кто-то пришел!") os.unlink(filename) logger.info("Sent tweet with photo %s" % filename) except tweepy.error.TweepError: pass # GPIO initial configuration GPIO.setmode(GPIO.BOARD) GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(5, GPIO.FALLING) GPIO.add_event_callback(5, capture_photo, bouncetime=3000) # tweepy initialization auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(KEY, SECRET) api = tweepy.API(auth) while True: filelist = [os.path.join(WORKDIR, onefile) for onefile in sorted(filter(os.path.isfile, os.listdir(WORKDIR)))] for onefile in filelist: tweet_photo(api, onefile) sleep(5)
def run(self): if self._ping['discover']: self._ping['discover'].listen() if self._pir['discover']: import RPi.GPIO as GPIO pin = self._pir['gpio'] GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(pin, GPIO.RISING) GPIO.add_event_callback(pin, self._pir['discover'].motion) self._pir['discover'].start() rf = [] if self._pipe['discover']: self._pipe['discover'].listen() rf.append(self._pipe['discover'].fifo) if self._http['discover']: self._http['discover'].listen() rf.append(self._http['discover'].socket) if self._bluetooth['discover']: rf.append(self._bluetooth['discover']) self._bluetooth['discover'].find_devices() # rf = [self._bluetooth['discover'], self._pipe['discover'].fifo, self._http['discover'].socket, ] while True: rfds = select.select(rf, [], [])[0] if self._pipe['discover']: if self._pipe['discover'].fifo in rfds: self._pipe['discover'].process_event() if self._http['discover']: if self._http['discover'].socket in rfds: self._http['discover'].httpd.handle_request() if self._bluetooth['discover']: if self._bluetooth['discover'] in rfds: self._bluetooth['discover'].process_event() if self._bluetooth['discover'].done: # time.sleep(1) self._bluetooth['discover'].expired(self._bluetooth['expire']) self._bluetooth['discover'].find_devices()
def setup(): gpio.setmode(gpio.BOARD) display.setup() gpio.setup(leds, gpio.OUT) gpio.output(leds, gpio.LOW) gpio.setup(buttons, gpio.IN, pull_up_down=gpio.PUD_UP) for pin in buttons: gpio.add_event_detect(pin, gpio.FALLING, bouncetime=200) gpio.add_event_callback(pin, set_active_destination) set_active_destination_led()
def MeasureEvent(self): #GPIO.add_event_detect(self.trigger,GPIO.RISING) GPIO.add_event_detect(self.echo,GPIO.RISING) #GPIO.add_event_callback(self.trigger,self.measureTime) GPIO.add_event_callback(self.echo,self.measureTime) GPIO.output(self.trigger,True) time.sleep(0.00001) GPIO.output(self.trigger,False) self.startTime=time.time() while GPIO.input(self.echo) == False: self.startTime = time.time() self.elapsedTime=self.stopTime-self.startTime self.distance=(self.elapsedTime*34000.0)/2.0 return self.distance
#API_Key From Push Bullet API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Fill your API_Key from Push Bullet def pushMessage(title, body): data = {'type': 'note', 'title': title, 'body': body} resp = requests.post('https://api.pushbullet.com/api/pushes', data=data, auth=(API_KEY, '')) def action(pin): print 'Sensor detected action!' pushMessage("Test message", "*****Alert****** Fire Deteced in Room *****Alert****** ") return GPIO.add_event_detect(7, GPIO.RISING) GPIO.add_event_callback(7, action) try: while True: print 'alive' time.sleep(0.5) except KeyboardInterrupt: GPIO.cleanup() sys.exit()
global count global ledon global switch switch = 1 count = count + 1 if count == 2: count = 0 if count == 0: ledon = 0 elif count == 1: ledon = 1 GPIO.setmode(GPIO.BCM) GPIO.setup(led_pin, GPIO.OUT) GPIO.setup(button_pin, GPIO.IN) GPIO.add_event_detect(button_pin, GPIO.RISING) GPIO.add_event_callback(button_pin, buttonpress) try: while 1: if switch == 1: print(count) switch = 0 GPIO.output(led_pin, ledon) time.sleep(0.01) except KeyboardInterrupt: pass GPIO.cleanup()
""" Button-Callback. Wird immer dann aufgerufen, wenn sich der Zustand des Hardware-Button Ändert. """ if GPIO.input(button) == GPIO.HIGH: print("Der Button ist UNTEN / AN") GPIO.output(GPIO_LED, True) else: print("Der Button ist OBEN / AUS") print("") GPIO.output(GPIO_LED, False) if __name__ == "__main__": try: # GPIO-Pins initialisieren GPIO.setmode(GPIO.BCM) GPIO.setup(GPIO_BUTTON, GPIO.IN) GPIO.setup(GPIO_LED, GPIO.OUT) GPIO.add_event_detect(GPIO_BUTTON, GPIO.BOTH) GPIO.add_event_callback(GPIO_BUTTON, on_button_event) # Endlosschleife, damit das Hauptprogramm weiterläuft while True: time.sleep(10) except KeyboardInterrupt: pass GPIO.cleanup()
# button plug pb_plug=27 GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # pir sensor sen_pir=11 GPIO.setup(11, GPIO.IN) #GPIO.add_event_detect(11, GPIO.RISING) #GPIO.add_event_callback(11, pir_event) # pb lamp1 pb_lamp1=5 GPIO.setup(5, GPIO.IN) # PB LAMP2 pb_lamp2=6 GPIO.setup(6, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(6, GPIO.RISING) GPIO.add_event_callback(6, pb_lamp2_event) # pb lamp3 pb_lamp3=13 GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(13, GPIO.RISING) GPIO.add_event_callback(13, pb_lamp3_event) # pb pir pb_pir=19 GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) def on_connect(mqttc, obj, flags, rc): print("rc: "+ str(rc)) def on_message(mqttc, obj, msg): global turn_off_alarm, turn_off_pir, turn_off_door, ready, start print(msg.topic+ " "+ str(msg.payload))
from RPi import GPIO GPIO.setmode(GPIO.BCM) fotopin = 20 GPIO.setup(fotopin, GPIO.IN) GPIO.input(fotopin) def lees_phototransitor(fotopin): waarde = GPIO.input(fotopin) try: if waarde == 1: print("ok") except: print("error lezen transistor") GPIO.add_event_detect(fotopin, GPIO.RISING, bouncetime=300) GPIO.add_event_callback(fotopin, callback=lees_phototransitor) while True: pass
GPIO.setmode(GPIO.BCM) #BCM pin numbering GPIO.setup(button_list, GPIO.IN, pull_up_down=GPIO.PUD_UP) #setup all buttons as input #when button pushed declare an event GPIO.add_event_detect(button1, GPIO.RISING) GPIO.add_event_detect(button2, GPIO.RISING) GPIO.add_event_detect(button3, GPIO.RISING) GPIO.add_event_detect(button4, GPIO.RISING) GPIO.add_event_detect(button5, GPIO.RISING) GPIO.add_event_detect(button6, GPIO.RISING) #When event declared run a function GPIO.add_event_callback(button1, button1_pushed) GPIO.add_event_callback(button2, button2_pushed) GPIO.add_event_callback(button3, button3_pushed) GPIO.add_event_callback(button4, button4_pushed) GPIO.add_event_callback(button5, button5_pushed) GPIO.add_event_callback(button6, button6_pushed) #setup LEDs as output GPIO.setup(led_list, GPIO.OUT, initial=GPIO.LOW) GPIO.output(led6, GPIO.HIGH) #turn on [ABORT] LED def main(): #buttons are pushed and variables save choices while choice_made == False:
import subprocess import requests from datetime import datetime from pprint import pprint import sys chanel = 10 GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(chanel, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) def callbackCamera(chanel): if GPIO.input(chanel) == GPIO.HIGH: print("Input detected") subprocess.call(['fswebcam -r 640x480 --no-banner /home/pi/Desktop/Semana\ i/tmma.jpg', '-1'], shell=True) face_uri = "https://raspberrycp.cognitiveservices.azure.com/vision/v1.0/analyze?visualFeatures=Faces&language=en" pathToFileInDisc = r'/home/pi/Desktop/Semana i/tmma.jpg' with open( pathToFileInDisc, "rb") as f: data = f.read() headers = {"Content-Type": "application/octet-stream", 'Ocp-Apim-Subscription-Key': '7e9cfbb244204fb994babd6111235269'} response = requests.post(face_uri, headers = headers, data = data) faces = response.json() pprint(faces) GPIO.add_event_detect(chanel, GPIO.BOTH, bouncetime=100) while(True): GPIO.add_event_callback(chanel, callbackCamera) print("\nI neva freeze\n")
stopRobot() def terminate(x): reallyStop() command[-2] = 50 updateArduino() exit() if __name__ == "__main__": reallyStop() closeAngle = 80 farAngle = 50 ballHave = 0 starttime = time.time() # cameraItr, _ = cameraInit() limit = [farAngle - 5, 120] GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP) #front GPIO.add_event_detect(4, GPIO.RISING) GPIO.add_event_callback(4, terminate) main() # calibration() # print(getVal())
def callback_high(channel): high_input = GPIO.input(channel) if high_input == 1: print "PANIC" send_message("PANIC!") else: print "Stop Panicking" send_message("Stop Panicking") # This line tells our script to keep an eye on our gpio pin and let us know when the pin goes HIGH or LOW GPIO.add_event_detect(channel_high, GPIO.BOTH, bouncetime=1) # This line asigns a function to the GPIO pin so that when the above line tells us there is a change on the pin, run this function GPIO.add_event_callback(channel_high, callback_high) # Define the GPIO pin that we have our digital output from our sensor connected to channel_low = 22 # Set the GPIO pin to an input GPIO.setup(channel_low, GPIO.IN) # This is our callback function, this function will be called every time there is a change on the specified GPIO channel, in this example we are using 17 def callback_low(channel): # print GPIO.input(channel_low) if GPIO.input(channel): print "COME HOME" send_message("Water Level is High in Sump Pump") else:
# This is our callback function, this function will be called every time there is a change on the specified GPIO channel, in this example we are using 17 def callback(sensor): if GPIO.input(sensor): GPIO.output(pump, GPIO.HIGH) print "Dry" else: GPIO.output(pump, GPIO.LOW) print "Water" # Set our GPIO numbering to BCM GPIO.setmode(GPIO.BCM) # Define the GPIO pin that we have our digital output from our sensor connected to sensor = 17 pump = 22 # Set the GPIO pin to an input GPIO.setup(sensor, GPIO.IN) GPIO.setup(pump, GPIO.OUT) # This line tells our script to keep an eye on our gpio pin and let us know when the pin goes HIGH or LOW GPIO.add_event_detect(sensor, GPIO.BOTH, bouncetime=300) # This line asigns a function to the GPIO pin so that when the above line tells us there is a change on the pin, run this function GPIO.add_event_callback(sensor, callback) # This is an infinte loop to keep our script running while True: # This line simply tells our script to wait 0.1 of a second, this is so the script doesnt hog all of the CPU time.sleep(0.1)
vibrating = False appliance_active = False last_vibration_time = time.time() start_vibration_time = last_vibration_time config = SafeConfigParser() config.read(sys.argv[1]) sensor_pin = config.getint('main', 'SENSOR_PIN') begin_seconds = config.getint('main', 'SECONDS_TO_START') end_seconds = config.getint('main', 'SECONDS_TO_END') pushbullet_api_key = config.get('pushbullet', 'API_KEY') pushbullet_api_key2 = config.get('pushbullet', 'API_KEY2') start_message = config.get('main', 'START_MESSAGE') end_message = config.get('main', 'END_MESSAGE') twitter_api_key = config.get('twitter', 'api_key') twitter_api_secret = config.get('twitter', 'api_secret') twitter_access_token = config.get('twitter', 'access_token') twitter_access_token_secret = config.get('twitter', 'access_token_secret') slack_api_token = config.get('slack', 'api_token') send_alert(config.get('main', 'BOOT_MESSAGE')) GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(sensor_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(sensor_pin, GPIO.RISING) GPIO.add_event_callback(sensor_pin, vibrated) print 'Running config file {} monitoring GPIO pin {}'\ .format(sys.argv[1], str(sensor_pin)) threading.Timer(1, heartbeat).start()
GPIO.output(3,0) os.system('sudo iptables -t nat -I POSTROUTING -o usb0 -s 192.168.0.0/24 -j MASQUERADE') GPIO.output(3,1) elif status=='OFF': print('OFF') GPIO.output(3,1) os.system('sudo ifdown usb0') GPIO.output(3,0) os.system('sudo systemctl stop hostapd') GPIO.output(3,1) #os.system('sudo ifconfig wlan0 down') GPIO.output(3,0) if __name__=="__main__": init() GPIO.add_event_callback(4,my_gpioCallback) temp = buttonStat while True: if(temp!=buttonStat): if buttonStat==False: buttonStat=False service('OFF') else: buttonStat=True service('ON') temp=buttonStat
#!/usr/bin/python3 import RPi.GPIO as GPIO import time SW_PIN = 18 def switch_callback(gpio_pin): print("SW ON!") GPIO.setmode(GPIO.BCM) GPIO.setup(SW_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(SW_PIN, GPIO.FALLING) GPIO.add_event_callback(SW_PIN, switch_callback) try: print("Type control-c to stop.\n") while True: time.sleep(0.05) finally: print("Cleaning up.") GPIO.cleanup()
import RPi.GPIO as GPIO import time #GPIO SETUP channel = 20 GPIO.setmode(GPIO.BCM) GPIO.setup(channel, GPIO.IN) GPIO.setwarnings(False) GPIO.setup(22,GPIO.OUT) #GPIO.setup(27,GPIO.OUT) def callback(channel): if GPIO.input(channel): GPIO.output(22,GPIO.HIGH) print("Water Detected!") time.sleep(1) else: GPIO.output(22,GPIO.LOW) print("Water not Detected!") time.sleep(1) GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) # let us know when the pin goes HIGH or LOW GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN, Run function on change # infinite loop while True: time.sleep(1) if __name__ == '__main__': try: main() except KeyboardInterrupt: GPIO.cleanup()
def start(self): print('Start soil moisture detection.') GPIO.add_event_detect(self.channel, GPIO.BOTH, bouncetime=300) GPIO.add_event_callback(self.channel, self.callback)
def motion(pin): tstamp = time.strftime("%H.%M.%S") print("Achtung! Bewegung erkannt - " + actual_time()) led() pic() return #Program Start actual_time() t=0.5 print('Überwachung gestartet...' + actual_time()) led() t=0.2 #deactivate display os.system("vcgencmd display_power 0") GPIO.add_event_detect(7, GPIO.RISING) GPIO.add_event_callback(7, motion) try: while True: time.sleep(t) except KeyboardInterrupt: os.system("vcgencmd display_power 1") print('Programm abgebrochen!') f.close GPIO.cleanup() sys.exit()
import sys from datetime import datetime from sender import Sender def sound_sensor_callback(channel): if GPIO.input(channel): print('SOUND') val = 1 msg = { 'sensorId': 7, 'sensorType': 'SOUND_SENSOR', 'value': val, 'date': str(datetime.now()), 'houseId': 1, } sender.send(msg) # Configure Sender sender = Sender() # SOUND SENSOR SOUND_SENSOR_PIN = 22 GPIO.setmode(GPIO.BCM) GPIO.setup(SOUND_SENSOR_PIN, GPIO.IN) GPIO.add_event_detect(SOUND_SENSOR_PIN, GPIO.BOTH, bouncetime=300) GPIO.add_event_callback(SOUND_SENSOR_PIN, sound_sensor_callback) while True: time.sleep(0.1)
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() # if args.mode == 'both' or args.mode == 'subscribe': # myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) time.sleep(2) # hardware code Create NeoPixel object with appropriate configuration. strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP) # Intialize the library (must be called once before other functions). strip.begin() LEFT_FLAG = 0 RIGHT_FLAG = 0 COUNTER = 0 color = (0, 0, 0, 0) GPIO.add_event_detect(PIN1, GPIO.FALLING, bouncetime=debounce_thresh) GPIO.add_event_detect(PIN2, GPIO.FALLING, bouncetime=debounce_thresh) GPIO.add_event_callback(PIN2, press_left) GPIO.add_event_callback(PIN1, press_right) print('Press Ctrl-C to quit.') while True: pass GPIO.cleanup()
print("handling button event") global processRunning time.sleep(0.1) if GPIO.input(25) == False and processRunning == False: state["process"] = subprocess.Popen( ["sudo", "./rpi-rgb-led-matrix/examples-api-use/demo", "-D", "6"], stdout=subprocess.PIPE, shell=False, preexec_fn=os.setsid) processRunning = True elif GPIO.input(25) == True and processRunning == True: os.killpg(os.getpgid(state["process"].pid), signal.SIGTERM) # Send the signal to all the process groups processRunning = False GPIO.add_event_detect(25, GPIO.RISING) GPIO.add_event_callback(25, buttonEventHandler) while True: pass # while True: # if GPIO.input(25) != previousLightState and state["process"]: # os.killpg(os.getpgid(state["process"].pid), signal.SIGTERM) # Send the signal to all the process groups # previousLightState = GPIO.input(25) # elif GPIO.input(25) != previousLightState: # state["process"] = subprocess.Popen(["sudo", "./rpi-rgb-led-matrix/examples-api-use/demo", "-D", "6"], stdout=subprocess.PIPE, # shell=False, preexec_fn=os.setsid) # previousLightState = GPIO.input(25)
# the sensor has to be connected to pin 1 for power, pin 6 for ground # and pin 7 for signal(board numbering!). import time, sys import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) pin = 7 GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) def action(pin): print('Sensor detected action!') return GPIO.add_event_detect(pin, GPIO.RISING) GPIO.add_event_callback(pin, action) try: while True: print('alive') time.sleep(0.5) except KeyboardInterrupt: GPIO.cleanup() sys.exit()
# set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) GPIO.setup(mybutton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(mywindspeed, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(myraingauge, GPIO.IN, pull_up_down=GPIO.PUD_UP) # tell the GPIO library to look out for an # event on pin x and deal with it by calling # the buttonEventHandler function GPIO.add_event_detect(mybutton, GPIO.FALLING) GPIO.add_event_callback(mybutton, buttonEventHandler) GPIO.add_event_detect(mywindspeed, GPIO.FALLING) GPIO.add_event_callback(mywindspeed, windEventHandler) GPIO.add_event_detect(myraingauge, GPIO.FALLING) GPIO.add_event_callback(myraingauge, rainEventHandler) try: gpsp.start() # start it up while (runner == True): #It may take a second or two to get good data print 'GPS reading' print 'latitude ', gpsd.fix.latitude print 'longitude ', gpsd.fix.longitude
iftt_maker_channel_event = config.get('iftt', 'maker_channel_event') iftt_maker_channel_key = config.get('iftt', 'maker_channel_key') email_recipient = config.get('email', 'recipient') email_sender = config.get('email', 'sender') email_password = config.get('email', 'password') email_server = config.get('email', 'server') email_port = config.get('email', 'port') telegram_api_token = config.get('telegram', 'telegram_api_token') telegram_user_id = config.get('telegram', 'telegram_user_id') if verbose: logging.getLogger().setLevel(logging.DEBUG) send_alert(config.get('main', 'BOOT_MESSAGE')) GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(dryer_sensor_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(dryer_sensor_pin, GPIO.RISING) GPIO.add_event_callback(dryer_sensor_pin, vibrated_dryer) GPIO.setup(washer_sensor_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(washer_sensor_pin, GPIO.RISING) GPIO.add_event_callback(washer_sensor_pin, vibrated_washer) logging.info('Running config file {}'.format(sys.argv[1])) logging.info('Monitoring dryer on GPIO pin {}'.format(str(dryer_sensor_pin))) logging.info('Monitoring washer on GPIO pin {}'.format(str(washer_sensor_pin))) threading.Timer(1, heartbeat).start()
s += '{0:x} '.format(message.data[i]) print(plus, ' {}'.format(c + s)) def callbackFromDue10ms(triggerInputPin): global plus message = getCANMessage(0x407) printCANMessage(message) #Id = ffff is no found Id error message # msg = can.Message(arbitration_id=0x7de,data=[0x00,0x01,0x02, 0x03, 0x04, 0x05,0x06, count & 0xff],extended_id=False) # bus.send(msg) plus += 1 #print(plus) GPIO.setmode(GPIO.BCM) GPIO.setup(triggerInputPin, GPIO.IN) GPIO.add_event_detect(triggerInputPin, GPIO.BOTH) GPIO.add_event_callback(triggerInputPin, callbackFromDue10ms) try: plus = 0 while True: time.sleep(10) finally: GPIO.cleanup() os.system("sudo /sbin/ip link set can0 down")
def sendChargeState(): charging = isCharging() chargeState = {'robot_id': robotID, 'charging': charging} appServerSocketIO.emit('charge_state', chargeState) print("charge state:", chargeState) def sendChargeStateCallback(x): sendChargeState() if commandArgs.type == 'motor_hat': GPIO.add_event_detect(chargeIONumber, GPIO.BOTH) GPIO.add_event_callback(chargeIONumber, sendChargeStateCallback) def identifyRobotID(): """tells the server which robot is using the connection""" print("sending identify robot id messages") if commandArgs.enable_chat_server_connection: chatSocket.emit('identify_robot_id', robotID) appServerSocketIO.emit('identify_robot_id', robotID) def setSpeedBasedOnCharge(): global dayTimeDrivingSpeedActuallyUsed global nightTimeDrivingSpeedActuallyUsed if chargeValue < 30: multiples = [0.2, 1.0]
# turn on gpio pin BELL pin GPIO.setmode(GPIO.BCM) GPIO.setup(BELL_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(BELL_PIN, GPIO.RISING) # set volume cmd = "mpc volume " + str(VOLUME) + limitMPCoutput subprocess.call(cmd, shell=True) # clear playlist cmd = "mpc clear " + limitMPCoutput subprocess.call(cmd, shell=True) # add ring tone cmd = "mpc insert /home/pi/ring2.m4a" + limitMPCoutput subprocess.call(cmd, shell=True) # run this when the button is pressed def my_callback(self): cmd = "mpc play 1 " + limitMPCoutput subprocess.call(cmd, shell=True) time.sleep(1) GPIO.add_event_callback(BELL_PIN, my_callback) # loop forever and sleep most of the time while True: time.sleep(1000)
{"_id": ObjectId("5b07c63274fece7f5b506a4d")}, {"$set": { "humiditysensor": "Behöver inte vattnas" }}) else: data = db.greenhous.update( {"_id": ObjectId("5b07c63274fece7f5b506a4d")}, {"$set": { "humiditysensor": "Behöver vattnas" }}) # Set our GPIO numbering to BCM GPIO.setmode(GPIO.BCM) # Define the GPIO pin that we have our digital output from our sensor connected to channel = 17 # Set the GPIO pin to an input GPIO.setup(channel, GPIO.IN) # This line tells our script to keep an eye on our gpio pin and let us know when the pin goes HIGH or LOW GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) # This line asigns a function to the GPIO pin so that when the above line tells us there is a change on the pin, run this function GPIO.add_event_callback(channel, moistureSensor) # This is an infinte loop to keep our script running while True: # This line simply tells our script to wait 0.1 of a second, this is so the script doesnt hog all of the CPU time.sleep(0.1) #---------------------------------------------------Moisture Sensor----------------------------------------------------------------------------
import RPi.GPIO as GPIO # This is the GPIO library we need to use the GPIO pins on the Raspberry Pi import time # This is the time library, we need this so we can use the sleep function def callback(channel): if GPIO.input(channel): print "LED off" else: print "LED on" # Set our GPIO numbering to BCM GPIO.setmode(GPIO.BCM) # Define the GPIO pin that we have our digital output from our sensor connected to channel = 17 # Set the GPIO pin to an input GPIO.setup(channel, GPIO.IN) # This line tells our script to keep an eye on our gpio pin and let us know when the pin goes HIGH or LOW GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) # This line asigns a function to the GPIO pin so that when the above line tells us there is a change on the pin, run this function GPIO.add_event_callback(channel, callback) # This is an infinte loop to keep our script running while True: # This line simply tells our script to wait 0.1 of a second, this is so the script doesnt hog all of the CPU time.sleep(0.1)
print("Picture taken and sent to ", email) elif "pump" in message or "on" in message: print("Watering system is on!") activate() elif "@" in message: email = message print("Email changed to "+email) else: print("Unknown message!") #Connection events client.on_connect = on_connect client.on_message = on_message client.connect("m15.cloudmqtt.com", 13159, 60) #Enable GPIO configuration gpioSetup() state = bin(gpio.input(moist)) gpio.add_event_detect(moist, gpio.BOTH, bouncetime=300) gpio.add_event_callback(moist,humidity) thread = threading.Thread(target=water) thread.daemon = True thread.start() # Infinite loop to keep program running until it is closed client.loop_forever()
def setup(robot_config): global mh global motorA global motorB global turningSpeedActuallyUsed global dayTimeDrivingSpeedActuallyUsed global nightTimeDrivingSpeedActuallyUsed global secondsToCharge global secondsToDischarge global chargeIONumber global forward global backward global left global right global straightDelay global turnDelay GPIO.setmode(GPIO.BCM) chargeIONumber = robot_config.getint('motor_hat', 'chargeIONumber') GPIO.setup(chargeIONumber, GPIO.IN) secondsToCharge = 60.0 * 60.0 * robot_config.getfloat( 'motor_hat', 'charge_hours') secondsToDischarge = 60.0 * 60.0 * robot_config.getfloat( 'motor_hat', 'discharge_hours') forward = json.loads(robot_config.get('motor_hat', 'forward')) backward = times(forward, -1) left = json.loads(robot_config.get('motor_hat', 'left')) right = times(left, -1) straightDelay = robot_config.getfloat('robot', 'straight_delay') turnDelay = robot_config.getfloat('robot', 'turn_delay') if motorsEnabled: # create a default object, no changes to I2C address or frequency mh = Adafruit_MotorHAT(addr=0x60) #mhArm = Adafruit_MotorHAT(addr=0x61) atexit.register(turnOffMotors) motorA = mh.getMotor(1) motorB = mh.getMotor(2) # Initialise the PWM device # pwm = PWM(0x42) # pwm.setPWMFreq(60) # Set frequency to 60 Hz turningSpeedActuallyUsed = robot_config.getint('motor_hat', 'turning_speed') dayTimeDrivingSpeedActuallyUsed = robot_config.getint( 'motor_hat', 'day_speed') nightTimeDrivingSpeedActuallyUsed = robot_config.getint( 'motor_hat', 'night_speed') if robot_config.getboolean('motor_hat', 'slow_for_low_battery'): GPIO.add_event_detect(chargeIONumber, GPIO.BOTH) GPIO.add_event_callback(chargeIONumber, sendChargeStateCallback) chargeCheckInterval = int( robot_config.getint('motor_hat', 'chargeCheckInterval')) if (robot_config.get('tts', 'type') != 'none'): schedule.repeat_task(60, reportBatteryStatus_task) schedule.repeat_task(17, reportNeedToCharge) schedule.task(chargeCheckInterval, sendChargeState_task)
laser_email.send_email() print("A border violation message has been sent.") laser_db.create_commit() print("Border violation data is recorded in the database.") def gas_callback(channel): speak("Gas leak detected") time.sleep(2) gas_email.send_email() print("A gas leak message has been sent.") gas_db.create_commit() print("Gas leakage data is recorded in the database.") flame_sensor = GPIO.add_event_detect(FLAME_CHANNEL, GPIO.BOTH, bouncetime=300) flame_sensor = GPIO.add_event_callback(FLAME_CHANNEL, flame_callback) vibration_sensor = GPIO.add_event_detect(VIBRATION_CHANNEL, GPIO.BOTH, bouncetime=300) vibration_sensor = GPIO.add_event_callback(VIBRATION_CHANNEL, vibration_callback) laser_sensor = GPIO.add_event_detect(LASER_CHANNEL, GPIO.BOTH, bouncetime=300) laser_sensor = GPIO.add_event_callback(LASER_CHANNEL, laser_callback) gas_sensor = GPIO.add_event_detect(GAS_CHANNEL, GPIO.BOTH, bouncetime=300) gas_sensor = GPIO.add_event_callback(GAS_CHANNEL, gas_callback)