def digitalGpioExamples(): # Set up pin P8_10 as an output GPIO.setup("P8_10", GPIO.OUT) # or GPIO.setup("GPIO0_26", GPIO.OUT) referring to the actual pin name instead of header_number GPIO.output("P8_10", GPIO.HIGH) GPIO.cleanup() # Set up pin P8_14 as an input GPIO.setup("P8_14", GPIO.IN) # Check to see if there is a signal or not and report on the status if GPIO.input("P8_14"): print("HIGH") else: print("LOW") # If you want edge detection instead, look no further (THIS IS BLOCKING, so be aware) GPIO.wait_for_edge("P8_14", GPIO.RISING) # Non blocking version GPIO.add_event_detect("P9_12", GPIO.FALLING) #your amazing code here #detect wherever: if GPIO.event_detected("P9_12"): print "event detected!"
def digitalinp(inp): print 'INPUT', inp, 'IS', 'open' if GPIO.input(INPUTS[inp]) else 'close' print print 'Waiting for a state change... (or ctrl+C to exit)' GPIO.wait_for_edge(INPUTS[inp], GPIO.BOTH) time.sleep(.01) # Adafruit library needs a little time to detect right status print 'INPUT', inp, 'IS NOW', 'open' if GPIO.input(INPUTS[inp]) else 'close'
def main(): #input the pin that the alert signal is fed into input = "P9_13" triggerLevel = 0x19 #25C or 77F GPIO.setup(input, GPIO.IN) tmp1 = Adafruit_I2C(0x48, busnum=2) tmp2 = Adafruit_I2C(0x4a, busnum=2) #set the values of the registers to enable alert pin tmp1.write8(0x01, 0x00) #sets alert flag to be in comapare mode, active low tmp2.write8(0x01, 0x00) #sets alert flag to be in comapare mode, active low tmp1.write8(0x02, triggerLevel) tmp1.write8(0x03, triggerLevel) tmp2.write8(0x02, triggerLevel) tmp2.write8(0x03, triggerLevel) ALERT_ALERT = GPIO.input(input) #check if we alert has allready happend if (not ALERT_ALERT): subprocess.call(['./readTMP.sh']) sys.exit(1) GPIO.wait_for_edge( input, GPIO.FALLING) #technically this call waits for an interupt subprocess.call(['./readTMP.sh'])
def irqWait(self): # A race condition may occur here. # TODO: Should set a timeout if GPIO.input(self.irq_pin) == 0: return GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING)
def main(): global running # other wise we cant stop thread #set up pins for out in outputs: GPIO.setup(out,GPIO.OUT) GPIO.output(out,GPIO.LOW) GPIO.output(outputs[0], GPIO.HIGH) GPIO.output(outputs[1], GPIO.HIGH) GPIO.setup("P9_18",GPIO.IN) GPIO.add_event_detect("P9_18",GPIO.FALLING) GPIO.wait_for_edge("P9_18",GPIO.FALLING) #start thread to run program thread = threading.Thread(target= lambda:function()) thread.start() print("Enter anything to quit") raw_input() #stall program till user presses enter, #clean up running = False for out in outputs: GPIO.output(out,GPIO.LOW) GPIO.cleanup()
def start(): global audioplaying, p while True: print("{}Ready to Record.{}".format(bcolors.OKBLUE, bcolors.ENDC)) GPIO.wait_for_edge( button, GPIO.FALLING) # we wait for the button to be pressed if audioplaying: volume = p.audio_get_volume() p.audio_set_volume(int(volume * .75)) print("{}Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC)) GPIO.output(rec_light, GPIO.HIGH) inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device) inp.setchannels(1) inp.setrate(16000) inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setperiodsize(500) audio = "" while (GPIO.input(button) == 0 ): # we keep recording while the button is pressed l, data = inp.read() if l: audio += data print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC)) if audioplaying: p.audio_set_volume(volume) # restore volume rf = open(path + 'recording.wav', 'w') rf.write(audio) rf.close() inp = None alexa_speech_recognizer()
def waitForFallingEdge(): pub = rospy.Publisher('encoderData', String, queue_size=10) rate = rospy.Rate(20) # 20hz while not rospy.is_shutdown(): GPIO.wait_for_edge("P8_14", GPIO.RISING) encoder.tsPrev = encoder.tsCurr encoder.tsCurr = time.time() encoder.counter = encoder.counter + 1 #print("Falling edge detected" + str(tsCurr)) if encoder.tsCurr != 0 and encoder.tsCurr - encoder.tsPrev != 0: encoder.currVel = (L / ticsPerRev) / (encoder.tsCurr - encoder.tsPrev) encoder.distance = +L / ticsPerRev print(encoder.m_name + " VL: " + str(encoder.currVel) + " SL: " + str(encoder.counter * (L / ticsPerRev))) pub.publish(encoder.name, encoder.speed, encoder.distance) rate.sleep()
def wait_for_button(): log.warning("waiting for button press") while True: GPIO.wait_for_edge(pin, GPIO.RISING) # try to avoid noise issues that cause false triggers time.sleep(0.25) # if button still pressed if GPIO.input(pin): break
def confirmTarget(): GPIO.wait_for_edge(yesButton, GPIO.FALLING) GPIO.wait_for_edge(noButton, GPIO.FALLING) while 1: #Confirm with button press that this is the intended target (use a toggle switch possibly) if GPIO.event_detected(yesButton): return True elif GPIO.event_detected(noButton): return False
def digitalinp(inp): print 'INPUT', inp, 'IS', 'open' if GPIO.input(INPUTS[inp]) else 'close' print print 'Waiting for a state change... (or ctrl+C to exit)' GPIO.wait_for_edge(INPUTS[inp], GPIO.BOTH) time.sleep( .01) # Adafruit library needs a little time to detect right status print 'INPUT', inp, 'IS NOW', 'open' if GPIO.input( INPUTS[inp]) else 'close'
def waitForButton(pin): # # Debounce! # pushed = False while not pushed: GPIO.wait_for_edge(pin, GPIO.FALLING) time.sleep(0.033) if (GPIO.input(pin) == 0): pushed = True
def read_n_sample_w_config(self, n, conf): self.stop_conversion() self.write_register(1,conf) self.start_conversion() read_data = [] read_timestamps = [] for i in range(n): GPIO.wait_for_edge(r.DrdyPin, GPIO.FALLING) read_timestamps.append(datetime.utcnow().isoformat()) read_data.append(self.read_adc_data()) return read_timestamps, read_data
def irqWait(self, timeout=30000): # TODO: A race condition may occur here. => wait for level? if GPIO.input( self.irq_pin) == 0: # Pin is already down. Packet is waiting? return True try: return GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING, timeout) == 1 except TypeError: # Timeout parameter not supported return GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING) == 1 except AttributeError: raise RuntimeError("GPIO lib does not support wait_for_edge()")
def edge_callback(pin): global flag global pulse_duration global falling_edge_time global rising_edge_time if not flag: rising_edge_time = time.time() flag = True GPIO.wait_for_edge(pin, GPIO.FALLING) falling_edge_time = time.time() pulse_duration = falling_edge_time - rising_edge_time
def handshake(): if not GPIO.input(slaveSelect): # print "slave low" GPIO.output(MOSI, GPIO.LOW) GPIO.output(spiClock, GPIO.LOW) else: # print "wait for slave low" GPIO.wait_for_edge(slaveSelect, GPIO.FALLING) GPIO.output(MOSI, GPIO.LOW) GPIO.output(spiClock, GPIO.LOW) # print "START" GPIO.wait_for_edge(slaveSelect, GPIO.RISING) GPIO.output(MOSI, GPIO.HIGH) GPIO.output(spiClock, GPIO.HIGH) # print "A" GPIO.wait_for_edge(slaveSelect, GPIO.FALLING) GPIO.output(MOSI, GPIO.LOW) GPIO.output(spiClock, GPIO.LOW) # print "B" GPIO.wait_for_edge(slaveSelect, GPIO.RISING) GPIO.setup(slaveSelect, GPIO.OUT) GPIO.output(slaveSelect, GPIO.LOW) # print "C" time.sleep(pause) GPIO.output(spiClock, GPIO.HIGH) # print "END" time.sleep(pause) GPIO.output(spiClock, GPIO.LOW)
def irqWait(self, timeout = 30000): # CHANGE: detect module name because wait_for_edge is not available in # other libraries if not self.using_adafruit_bbio_gpio: raise Exception("IRQ Wait only available on the BBB") # TODO: A race condition may occur here. if GPIO.input(self.irq_pin) == 0: # Pin is already down. Packet is waiting? return True #HACK to detect GPIO lib type if GPIO.wait_for_edge.func_code.co_argcount == 4: return GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING, timeout) == 1 else: return GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING) == 1
def clickMonitor(self): self.logger.info("click monitor engaged") previousTime = time.time() while self.isClickThreadRunning: GPIO.wait_for_edge(self.gpioPins[Click.CLICK], GPIO.RISING) currentTime = time.time() timeDelta = currentTime - previousTime if timeDelta >= self.debounceTimeout: self.logger.info("CLICK") try: self.eventQueue.put(Click.CLICK, block=True, timeout=5) except Queue.Full: pass previousTime = currentTime self.logger.intfo("click monitor terminated")
def boom(): while 1: cap = cv2.VideoCapture(0) print "Awaiting start signal" GPIO.wait_for_edge(startButton, GPIO.RISING) GPIO.cleanup() distanceToTarget = scanForFace(cap) # distanceToTarget = 50 # distanceToTarget = getDistanceToFace(faces) rightTarget = confirmTarget() if rightTarget: angleD = getLaunchAngle(distanceToTarget) aim(angleD) clearedForLaunch = confirmLaunch() launchBaby(distanceToTarget) resetAngle()
def button_response(button, led): # callback function state = GPIO.input(button) if state: GPIO.output(led, state) if button == button1: print("Button1 pressed") elif button == button2: print("Button2 pressed") elif button == button3: print("Button3 pressed") elif button == button4: print("Button4 pressed") GPIO.wait_for_edge(button, GPIO.BOTH) else: GPIO.output(led, 0) return 0
def irqWait(self, timeout = 30000): # CHANGE: detect module name because wait_for_edge is not available in # other libraries if GPIO.__name__ != "Adafruit_BBIO.GPIO": return False # TODO: A race condition may occur here. if GPIO.input(self.irq_pin) == 0: # Pin is already down. Packet is waiting? return True return GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING, timeout) == 1
def calc_pulse_width(pin_name, avg_num, sig_freq): """Calculate the pulse width of a PWM signal input. This function stores the time of day on a Rising Edge and subsequent Falling Edge event, calculates the average of multiple such events, and returns the difference in milliseconds. Function will halt if run on 0 or 100% Duty Cycle signals. Args: pin_name: A String specifying the pin name on which the PWM signal is expected. The pin name should be in the format defined by the Adafruit_BBIO library. avg_num: An Integer specifying the sample size. sig_freq: An Integer specifying the expected frequency of the PWM signal [Hz]. Returns: pulse_avg: The calculated pulse width [milliseconds]. """ pulse_avg = 0.0 __rise_flag = 0.0 __fall_flag = 0.0 __pulse_width = 0.0 for i in range(avg_num) # Determine incoming signal Pulse Width. GPIO.wait_for_edge(pin_name, GPIO.RISING) __rise_flag = time.time() GPIO.wait_for_edge(pin_name, GPIO.FALLING) __fall_flag = time.time() __pulse_width = __fall_flag - __rise_flag # Adjust for missed Pulses (CPU busy during Edge event). # This is done by subtracting the PWM period value if the # measured pulse width is found to be greater than the period. while __pulse_width > (1/signal_freq) __pulse_width -= (1/signal_freq) pulse_avg += __pulse_width return (pulse_avg /= avg_num)
def Launch(distance): #Calculate the require launch angle and initial velocity #Aim the Barrel #Load the can #Spin up the wheels #Get one last confirmation GPIO.wait_for_edge(yesButton, GPIO.FALLING) GPIO.wait_for_edge(noButton, GPIO.FALLING) while 1: #Confirm with button press that this is the intended target (use a toggle switch possibly) if GPIO.event_detected(yesButton): launchConfirmed = True break elif GPIO.event_detected(noButton): break if not launchConfirmed: return
def handshake(): GPIO.wait_for_edge(slaveSelect, GPIO.RISING) GPIO.output(MOSI, GPIO.HIGH) GPIO.output(spiClock, GPIO.HIGH) time.sleep(0.01) GPIO.output(spiClock, GPIO.LOW) GPIO.output(MOSI, GPIO.LOW) time.sleep(0.01) # GPIO.wait_for_edge(slaveSelect, GPIO.RISING) GPIO.output(spiClock, GPIO.HIGH) time.sleep(0.01) GPIO.output(spiClock, GPIO.LOW) time.sleep(0.01) GPIO.output(MOSI, GPIO.HIGH) GPIO.output(spiClock, GPIO.HIGH) GPIO.setup(slaveSelect, GPIO.OUT) GPIO.output(slaveSelect, GPIO.HIGH) time.sleep(0.01) GPIO.output(spiClock, GPIO.LOW) GPIO.output(MOSI, GPIO.LOW) time.sleep(0.01)
def encoderMonitor(self): self.logger.info("encoder monitor engaged") previousTime = time.time() while self.pinThreadRunning: GPIO.wait_for_edge(self.gpioPins[EncoderChannel.A], GPIO.FALLING) channelBState = GPIO.input(self.gpioPins[EncoderChannel.B]) currentTime = time.time() timeDelta = currentTime - previousTime self.logger.debug("Edge detected on channel A. B:%s Delta: %s", channelBState, timeDelta) if timeDelta >= self.debounceTimeout: if channelBState == 0: self.logger.info("Counter-Clockwise rotation") try: self.eventQueue.put(Direction.COUNTER_CLOCKWISE, block=True, timeout=5) except Queue.Full: pass else: self.logger.info("Clockwise rotation") try: self.eventQueue.put(Direction.CLOCKWISE, block=True, timeout=5) except Queue.Full: pass previousTime = currentTime self.logger.info("encoder monitor terminated")
def wait_for_edge(pin, edgeType): if (globalCfg.platform == "bbb"): if (edgeType == "rising"): GPIO.wait_for_edge(self.ppsPin, GPIO.RISING) elif (edgeType == "falling"): GPIO.wait_for_edge(self.ppsPin, GPIO.FALLING) elif (edgeType == "both"): GPIO.wait_for_edge(self.ppsPin, GPIO.BOTH) else: # invalid edge type return -1 return 0 else: return -1
GPIO.setup(ButtonPin, GPIO.IN) GPIO.setup(ButtonLed, GPIO.OUT) GPIO.setup(ButtonPower, GPIO.OUT) with Stream: while True: print("Loop started!") print("Setting pins...") for Pin in LedPins: GPIO.output(Pin, GPIO.LOW) GPIO.output(ButtonPower, GPIO.HIGH) GPIO.output(ButtonLed, GPIO.HIGH) print("Press the microswitch to start.") GPIO.wait_for_edge(ButtonPin, GPIO.RISING) print("Calibrating RMS...") RefRMS = np.zeros([100]) for _ in range(100): print(_) RefRMS[_] = ProcessData(Rate, FreqBand) RefRMS = np.mean(RefRMS) Slot = int(RefRMS / (len(LedPins))) print(RefRMS, Slot) print("Starting game...") GPIO.output(ButtonLed, GPIO.LOW) GPIO.output(ButtonPower, GPIO.LOW) for Pin in LedPins: GPIO.output(Pin, GPIO.HIGH)
GPIO.output(A4, GPIO.LOW) elif abs(state) == 4: GPIO.output(A1, GPIO.HIGH) GPIO.output(A2, GPIO.LOW) GPIO.output(A3, GPIO.LOW) GPIO.output(A4, GPIO.HIGH) time.sleep(0.05) def thatDogWillHunt(): #function to continually track the IR emitter while True: rightptval = ADC.read(rightPT) leftptval = ADC.read(leftPT) if rightptval > leftptval: oneStep(1) else: oneStep(-1) def main(): #called after the start button to begin setup and tracking print "Start button has been pressed!" strongestRead = setup() for i in range(strongestRead): oneStep(1) thatDogWillHunt() while True: #initial loop to run waiting for a start button input GPIO.wait_for_edge(startButton, GPIO.RISING) main()
import os import datetime import threading button="P2_17" # PAUSE=P8_9, MODE=P8_10 LED = "USR3" def takePic(): print("Pressed") # Turn LED on to show it's working GPIO.output(LED, 1) file = "/tmp/" + datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S") + ".jpg" # print(file) os.system("./fb2jpg.sh /dev/fb0 " + file) os.system("rclone copy " + file + " drive:Pictures") # Turn LED off GPIO.output(LED, 0) # Set the GPIO pin: GPIO.setup(button, GPIO.IN) GPIO.setup(LED, GPIO.OUT) GPIO.output(LED, 0) print("Running...") while True: GPIO.wait_for_edge(button, GPIO.RISING) # FALLING, RISING, BOTH takePic()
import Adafruit_BBIO.GPIO as GPIO from time import sleep from subprocess import call '''No es necesario especificar cuanto tiempo se queda dormido, porque el script de los sensores espera el toque del swtich''' sleep(10) GPIO.cleanup() sleep(2) GPIO.setup("P9_11", GPIO.IN) GPIO.setup("P9_13", GPIO.OUT) GPIO.wait_for_edge("P9_11", GPIO.FALLING) #esperando para activar el switch print 'Hola' flag = 1 conteo = 10 #cantidad de veces a intentar while flag: GPIO.output("P9_13", GPIO.HIGH) sleep(0.5) GPIO.output("P9_13", GPIO.LOW) sleep(2) GPIO.cleanup() sleep(10) x = call("systemctl start sensor.service",shell=True) conteo -= 1 if x == 0: flag = 0 elif x != 0: call("systemctl start sensor.service",shell=True) elif conteo == 0: #se acabaron las oportunidades flag = 0 break
def wait_pressed(self): """ Wait for the switch to be pressed (waits for a falling edge). """ GPIO.wait_for_edge(self.pin, GPIO.FALLING) return
import Adafruit_BBIO.GPIO as GPIO import time pin = "P9_12" GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.wait_for_edge(pin, GPIO.RISING) print "started" def callback(channel): print "event detected!" GPIO.add_event_detect(pin, GPIO.RISING, callback=callback) #GPIO.add_event_detect(pin, GPIO.RISING) try: while True: time.sleep(0.5) # if GPIO.event_detected(pin): # print "event detected!" except KeyboardInterrupt as e: GPIO.cleanup()
def ap1_read_pressure_using_strobe(): GPIO.wait_for_edge("P8_10", GPIO.RISING) time_aux=time.time() GPIO.wait_for_edge("P8_10", GPIO.FALLING) time_a=time.time()-time_aux return '%.0f' % round(time_a/0.0003)
def wait_pushed(self): """ Wait for the switch to be pressed and released (waits for a falling edge followed by a rising edge. """ GPIO.wait_for_edge(self.pin, GPIO.FALLING) GPIO.wait_for_edge(self.pin, GPIO.RISING) return
import Adafruit_BBIO.GPIO as GPIO from time import sleep import os import sys import tweepy CONSUMER_KEY = 'xxxxxxxxxxxxxxxxxx' CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxx' ACCESS_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ACCESS_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx' GPIO.setup("P8_19", GPIO.IN) while True: GPIO.wait_for_edge("P8_19", GPIO.RISING) print ("Motion detected") auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth) api.update_status('ALERT!! Motion detected in Zone 1 - Message sent from #BeagleBoneBlack') sleep(60)
def main(): print("Welcome to etch a sketch!") print("") print("8x8 LED edition") xdim = 8 ydim = 8 print("Preparing an ", xdim, "x", ydim, "etch a sketch grid") xpoint = int( (xdim + 1) / 2 - 1) # use "ceiling" function to start drawing in center of sketch ypoint = int((ydim + 1) / 2 - 1) coordinates = [0] * xdim for x in range(0, xdim): # create coordinates (currently matrix of zeros) coordinates[x] = [0] * ydim # when pointer moves, change entry to 1. # whenever there's a 1, place an x in the sketch; otherwise place a space coordinates[xpoint][ypoint] = 1 grid = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, # create grid of all zeros 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] bus.write_i2c_block_data( matrix, 0, grid) # write zeros to each LED (i.e. all LEDs off) while True: # loop print( "Use leftmost, left middle, right middle, or rightmost buttons to draw left, up, down, or right" ) #print("Use wa, sa, sd, or wd to draw diagonals") #print("Type 'clear' to erase the sketch") switchmapping = ["a", "w", "s", "d"] direction = "" while (direction == ""): for i in range(0, 4): if GPIO.input(SW[i]) == 1: direction = switchmapping[i] GPIO.wait_for_edge(SW[i], GPIO.FALLING) i = 4 if len(direction) > 2: # if "clear" is typed, erase sketch & reset if if direction == "clear": print("Erasing sketch") print("") print("") break else: print( "Please enter a valid direction" ) # if more than two characters are entered (other than "clear"), throw a warning elif (direction == "ss") | (direction == "ww") | ( direction == "aa") | (direction == "dd"): print("Please enter a valid direction" ) # if ww, aa, ss, or dd is entered, throw a warning else: originalxpoint = xpoint originalypoint = ypoint valid = 1 for l in range(0, len(direction)): if str( direction[l] ) == "w": # if cursor gets to edge of sketch, it cannot go any further if ypoint == ( ydim - 1 ): # (i.e. it will not wrap around the sketch to the other side) ypoint = ydim - 1 else: ypoint += 1 elif str(direction[l]) == "d": if xpoint == 0: xpoint = 0 else: xpoint -= 1 elif str(direction[l]) == "s": if ypoint == 0: ypoint = 0 else: ypoint -= 1 elif str(direction[l]) == "a": if xpoint == (xdim - 1): xpoint = xdim - 1 else: xpoint += 1 else: print( "Please enter a valid direction" ) # if any character other than wasd is entered, throw a warning valid = 0 xpoint = originalxpoint ypoint = originalypoint if valid == 1: coordinates[xpoint][ ypoint] = 1 # change entry in coordinates matrix based on where the pointer is etchasketch(xdim, ydim, coordinates, grid) # draw the updated sketc if valid == 0: xpoint = originalxpoint ypoint = originalypoint
# Define program constants BUTTON_PIN = 'P9_11' LED_PIN = 'P9_12' # Configure the GPIO pins and set the initial state of variables to track the # state of the button. GPIO.setup(BUTTON_PIN, GPIO.IN) GPIO.setup(LED_PIN, GPIO.OUT) GPIO.output(LED_PIN, GPIO.LOW) # print out a nice message to let the user know how to quit. print('Starting, press <control>-c to quit.\n') # Execute until a keyboard interrupt try: while True: # Wait for the BUTTON_PIN to have a falling edge, indicating the # button has been pressed. GPIO.wait_for_edge(BUTTON_PIN, GPIO.RISING) # Button has been pressed so turn on the LED and start your program GPIO.output(LED_PIN, GPIO.HIGH) subprocess.call(['/path/to/the/program', '-argument']) # Program is done, turn off the LED and start waiting again. GPIO.output(LED_PIN, GPIO.LOW) except KeyboardInterrupt: GPIO.cleanup()
def wait_released(self): """ Wait for the switch to be released (waits for a raising edge). """ GPIO.wait_for_edge(self.pin, GPIO.RISING) return
import tweepy from subprocess import call from datetime import datetime from time import sleep import subprocess import Adafruit_BBIO.GPIO as GPIO GPIO.setup("P9_14", GPIO.IN) while True: i = datetime.now() now = i.strftime('%Y%m%d-%H%M%S') GPIO.wait_for_edge("P9_14", GPIO.RISING) kill = 'killall mjpg_streamer' cmd = 'wget -O /root/frontdoor.jpg http://192.168.7.2:8090/?action=snapshot' webcam = '/root/mjpg-streamer/mjpg_streamer -i "/root/mjpg- streamer/input_uvc.so" -o "/root/mjpg-streamer/output_http.so -p 8090 -w ./www" &' call([webcam], shell=True) sleep(5) call ([cmd], shell=True) consumer_key = 'xxxxxxxxxxxxx' consumer_secret = 'xxxxxxxxxxxxxxx' access_token = xxxxxxxxxxxxxxxxx' access_token_secret = 'xxxxxxxxxxxxxxxxxx' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) authentication api = tweepy.API(auth) photo_path = '/root/123.jpg'
import time import subprocess import os import signal button="PAUSE" # PAUSE or MODE LED ="WIFI" # Set the GPIO pins: GPIO.setup(LED, GPIO.OUT) GPIO.setup(button, GPIO.IN) print("Running...") GPIO.output(LED, 1) GPIO.wait_for_edge(button, GPIO.RISING) print("i2cmatrix.py") proc1 = subprocess.Popen(["./i2cmatrix.py"]) print(proc1.pid) GPIO.wait_for_edge(button, GPIO.RISING) print("sequence.py") proc2 = subprocess.Popen(["./sequence.py"]) print(proc2.pid) GPIO.wait_for_edge(button, GPIO.RISING) print("fbi") subprocess.run(["./on.sh"]) time.sleep(0.5) subprocess.run(["fbi", "-noverbose", "-T", "1", "-a", "boris.png"])
def init_robot(): global black_button_pressed try: GPIO.setup(robot.trig_button, GPIO.IN) GPIO.setup(robot.col_button, GPIO.IN) GPIO.setup(robot.but1_button, GPIO.IN) GPIO.setup(robot.but2_button, GPIO.IN) GPIO.add_event_detect(robot.but2_button, GPIO.FALLING, callback=black_button_callback, bouncetime=300) except: pass boot_ok = False while (boot_ok == False): black_button_pressed = False print("BOOT ok.") if exists(robot.asserv_out_file) == False: print("start first robot deamon") robot.my_lcd.write("no deamon...") quit() if exists(robot.asserv_in_file) == False: print("start first robot deamon") robot.my_lcd.write("no deamon...") quit() print("ca va passer?") #config angulaire # fast_conf() print("stop asserv") robot.com("-B -m0") print("motor 1 back") robot.com("-B -x-0 -m1") print("motor 2 back") robot.com("-B -x-0 -m2") print("les choses serieuses") robot.my_lcd.write("deamon connected...") # reponse=robot.com("-E") # print(reponse) print("changer 3 fois la couleur pour selectionner la couleur") robot.my_lcd.write("chg 3 times col") GPIO.wait_for_edge(robot.col_button, GPIO.RISING) if (black_button_pressed == True): print("black button pressed, it should continue") continue print("changer 2 fois la couleur pour selectionner la couleur") robot.my_lcd.write("chg 2 times col") GPIO.wait_for_edge(robot.col_button, GPIO.RISING) if (black_button_pressed == True): print("black button pressed, it should continue") continue print("changer 1 fois la couleur pour selectionner la couleur") robot.my_lcd.write("chg 1 times col") GPIO.wait_for_edge(robot.col_button, GPIO.RISING) if (black_button_pressed == True): print("black button pressed, it should continue") continue robot.my_lcd.write("color : ") robot.my_lcd.write("press blue then") while GPIO.input(robot.but1_button) == 1: if GPIO.input(robot.col_button) == 1: robot.color = "jaune" robot.my_lcd.lcd_display_string("jaune ", 1, 8) else: robot.color = "violet" robot.my_lcd.lcd_display_string("violet", 1, 8) if (black_button_pressed == True): print("black button pressed, it should continue") continue time.sleep(0.1) if (black_button_pressed == True): print("black button pressed, it should continue") if GPIO.input(robot.trig_button) == 0: robot.my_lcd.write("remove trigger") GPIO.wait_for_edge(robot.trig_button, GPIO.RISING) if (black_button_pressed == True): print("black button pressed, it should continue") continue robot.my_lcd.write("insert trigger") GPIO.wait_for_edge(robot.trig_button, GPIO.FALLING) if (black_button_pressed == True): print("black button pressed, it should continue") continue robot.my_lcd.write("press blue again") GPIO.wait_for_edge(robot.but1_button, GPIO.FALLING) if (black_button_pressed): continue robot.my_lcd.write("red button and blue again") GPIO.wait_for_edge(robot.but1_button, GPIO.FALLING) if (black_button_pressed): continue print("couleur robot", robot.color) if (robot.color == "jaune"): reponse = robot.com("-Y -x500 -y 500 -t1.57079632679") robot.my_lcd.write("righ !") fthewall("derriere") robot.turn(-1.57079632679, 0) while (robot.com("-E") != "yes"): time.sleep(0.1) else: reponse = robot.com("-Y -x500 -y 2500 -t4.71238898038") robot.my_lcd.write("left !") fthewall("devant") robot.turn(1.57079632679, 0) while (robot.com("-E") != "yes"): time.sleep(0.1) print("F*** The Wall!") robot.my_lcd.write("f the wall : ") time.sleep(1) robot.my_lcd.write("go! ") fthewall("gauche") print("placement en position initiale") if (robot.color == "jaune"): print("pour les JAUNE") # reponse=robot.com("-G -x470 -y250 -t3.14159265359 -m0") robot.go_direct(470, 250, 3.14159265359, -1, False) else: print("pour le VIOLET") # reponse=robot.com("-G -x470 -y2750 -t3.14159265359 -m0") robot.go_direct(470, 2750, 3.14159265359, -1, False) print(reponse) truc = "" while (robot.com("-E") != "yes"): time.sleep(0.1) print("wait for trigger") GPIO.wait_for_edge(robot.trig_button, GPIO.RISING) if (black_button_pressed == True): print("black button pressed, it should continue") continue time.sleep(0.1) boot_ok = True
#!/usr/bin/env python import Adafruit_BBIO.GPIO as GPIO PIN = 'P9_23' GPIO.setup(PIN, GPIO.IN) print "Done setting up pin" + PIN + " as an input" while True: print "Waiting for interrupt..." GPIO.wait_for_edge(PIN, GPIO.RISING) print "Detected rising edge on pin " + PIN
# when a rising edge is detected, regardless of whatever # else is happening in the program, the function 'my_callback' will be run # It will happen even while the program is waiting for # a falling edge on the other button. # GPIO.add_event_detect('P8_16', GPIO.RISING, callback=my_callback, bouncetime=200) # GPIO.add_event_detect('P8_16', GPIO.RISING, bouncetime=200) switch_thread = threading.Thread(name = 'check_switch', target = check_switch, args = ('P8_16',)) switch_thread.daemon = True switch_thread.start() # Create a lock lock = threading.Lock() try: logging.debug('Waiting for falling edge on P8_14.') GPIO.wait_for_edge('P8_14', GPIO.RISING) logging.debug('Falling edge on P8_14 detected.') time.sleep(1) logging.debug('/nNow, let\'s try it in a for loop') while not GPIO.input('P8_14'): logging.debug(pressed) time.sleep(1) except KeyboardInterrupt: GPIO.cleanup() # clean up GPIO on CTRL+C exit GPIO.cleanup() # clean up GPIO on normal exit
def ap1_read_pressure_using_strobe(): GPIO.wait_for_edge("P8_10", GPIO.RISING) time_aux = time.time() GPIO.wait_for_edge("P8_10", GPIO.FALLING) time_a = time.time() - time_aux return '%.0f' % round(time_a / 0.0003)
#!/usr/bin/python3 import time import Adafruit_BBIO.GPIO as GPIO ADC_T = 0.001 # How often the program will read data from ADC GPIO.setup('P8_8', GPIO.IN) # GPIO line for triggering this program adc_path = '/sys/bus/iio/devices/iio:device0/in_voltage3_raw' # ADC's file path time_point = 0 # Used for the time delay (seconds) f = open(adc_path, 'r') # Open ADC file buf = open('buffer.txt', 'w') # Name of my buffer print('Wait for edge...') GPIO.wait_for_edge('P8_8', GPIO.BOTH) # Trigger for edge on GPIO line while GPIO.input('P8_8'): # While the GPIO line is high while time.time() - time_point < ADC_T: # Time delay None N = int(f.read()) # Read the ADC's file buf.write(str(N) + '\n') # Write to buffer time_point = time.time() f.seek(0) # set pointer in ADC's file to the start position f.close() buf.close()
GPIO.add_event_detect(E_STOP, GPIO.RISING, callback=ESTOP_callback, bouncetime=200) try: # while True: if not GPIO.input(E_STOP): GPIO.cleanup() # clean up GPIO on normal exit sys.exit('\nE-STOP switch is in the emergency stop state. Exiting...\n') # Move down motorA.start(100, 'CW') motorB.start(100, 'CCW') print 'Moving down...' time.sleep(0.5) GPIO.wait_for_edge(BOTTOM_LIMIT, GPIO.RISING) print 'Bottom limit reached.' motorA.hard_stop() motorB.hard_stop() time.sleep(2) # Start Moving Motors Up motorA.start(100, 'CCW') motorB.start(100, 'CW') print 'Moving up...' time.sleep(0.5) GPIO.wait_for_edge(TOP_LIMIT, GPIO.RISING) print 'Top limit reached.'
#!/usr/bin/env python3 # Reads the PAUSE button using interupts and sets the LED # Pin table at https://github.com/beagleboard/beaglebone-blue/blob/master/BeagleBone_Blue_Pin_Table.csv # Import PyBBIO library: import Adafruit_BBIO.GPIO as GPIO import time button = "PAUSE" # PAUSE=P8_9, MODE=P8_10 LED = "RED_LED" # Set the GPIO pins: GPIO.setup(LED, GPIO.OUT) GPIO.setup(button, GPIO.IN) print("Running...") while True: state = GPIO.input(button) GPIO.output(LED, state) GPIO.wait_for_edge(button, GPIO.BOTH) print("Pressed")
#!/usr/bin/env python3 # Reads the PAUSE button using interupts and sets the LED # Pin table at https://github.com/beagleboard/beaglebone-blue/blob/master/BeagleBone_Blue_Pin_Table.csv # Import PyBBIO library: import Adafruit_BBIO.GPIO as GPIO import time button="PAUSE" # PAUSE or MODE LED ="USR3" # Set the GPIO pins: GPIO.setup(LED, GPIO.OUT) GPIO.setup(button, GPIO.IN) print("Running...") while True: state = GPIO.input(button) GPIO.output(LED, state) GPIO.wait_for_edge(button, GPIO.BOTH) print("Pressed")
return (-R0*A +(R0**2 * A**2 - 4 * R0 * B * (R0 - R))**0.5)\ /(2*R0*B) def C2R(C): if C >= 0.0: return R0 * (1 + A * C + B * C**2) c = 0 while True: try: GPIO.wait_for_edge(DRDY_PIN, GPIO.FALLING) # rp = spi.xfer2([0, 0, 0, 0, 0, 0]) # data = (rp[1] << 24) | (rp[2] << 16) | (rp[3] << 8) | rp[4] print data * 5000.0 / 2**32 # R2C(data * 5000.0 / 2**32) except KeyboardInterrupt: break def ADS126xReadRegister(StartAddress, pdata): cmd = [0x20 + StartAddress, len(pdata) - 1] return spi.xfer2(cmd + pdata)[2:] def ADS126xWriteRegister(StartAddress, pdata): cmd = [0x40 + StartAddress, len(pdata) - 1]
version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ''' # general pin input/output for motion detector device import time import Adafruit_BBIO.GPIO as GPIO GPIO.setup('P9_15', GPIO.IN) file_handle = open('movement_log.txt', 'w') while True: GPIO.wait_for_edge("P9_15", GPIO.RISING) log_start = time.strftime("%a, %d %b %Y %H:%M:%S") GPIO.wait_for_edge("P9_15", GPIO.FALLING) log_end = time.strftime("%a, %d %b %Y %H:%M:%S") file_handle.write("+" + "-" * 40 + "\n") file_handle.write("| Start: %s\n" % log_start) file_handle.write("| End: %s\n" % log_end)