示例#1
0
    def update_lcd(self):
        """Update the front-panel LCD.

        This method updates the front-panel LCD, detecting front-panel button presses to
        change page and refreshing the content and colour of the display. This is
        intended to be called periodically as part of an update loop to keep the display
        output reflecting the PSCU state.
        """
        # Do nothing if display was not initialised OK
        if self.lcd_display_error:
            return

        # Detect front-panel button presses to cycle through the LCD pages
        if GPIO.event_detected("P9_11"):
            self.lcd.previous_page()
        elif GPIO.event_detected("P9_12"):
            self.lcd.next_page()

        # Set the LCD backlight colour depending on the overall system health
        if self.__healthy:
            self.lcd.set_colour(LcdDisplay.GREEN)
        else:
            self.lcd.set_colour(LcdDisplay.RED)

        # Update the LCD content
        self.lcd.update()
def main():
    PIR = "P8_11"
    GPIO.setup(PIR, GPIO.IN)
    GPIO.add_event_detect(PIR, GPIO.RISING)

    node = os.popen("uname -n").readline()
    node = node.split('\n')[0]
    """
        nome do arquivo:
        dadosTemperatura_Teste_nodeX_hora.mintus.segundo_dia.mes.ano.txt
    """
    nome_Arquivo =  node + 'Tempertatura_' + \
                    time.strftime('_%l.%M.%S_%d.%m.%Y')+'.txt'
    arquivo = open(nome_Arquivo, 'w')
    while True:
        if GPIO.event_detected(PIR):
            break

    while True:
        if GPIO.event_detected(PIR):
            break
        arquivo.writelines(
            time.strftime('Horario da captura: %l:%M:%S %p %Z on %d\
        , %Y; ') + 'Temperatura na CPU: ' + str(temp_cpu()) +
            '; Temperatura na GPU \
        :' + '0')
        time.sleep(1)

    arquivo.close()
    diretorio = "hduser@master:/home/hduser/HadoopDados"
    subprocess.call(["scp", nome_Arquivo, diretorio])
def switch():
    global posX
    global posY
    if GPIO.event_detected("P9_15"):
        posY -= 1
        if posY < 0:
            posY = n - 1

    elif GPIO.event_detected("P9_17"):
        posY += 1
        if posY > n - 1:
            posY = 0

    elif GPIO.event_detected("P9_11"):
        posX -= 1
        if posX < 0:
            posX = n - 1

    elif GPIO.event_detected("P9_13"):
        posX += 1
        if posX > n - 1:
            posX = 0

    else:
        return
    print("\033[H\033[J")
    array[posX + posY * n] = 'X'
    display(array, n)
    print('cursor <posX,posY>'),
    print(str(posX) + " " + str(posY))
    return
示例#4
0
    def check_state(self):
        new_state = None
        if GPIO.event_detected(PWMREFMODE):
            new_state = 'USER_CONTROL'
        elif GPIO.event_detected(PRESSUREREFMODE):
            new_state = 'USER_REFERENCE'
        elif GPIO.event_detected(PATTERNREFMODE):
            new_state = 'REFERENCE_TRACKING'

        change = False
        if new_state:
            potis = []
            for idx, pin in enumerate(CONTINUOUSPRESSUREREF):
                val = ADC.read(pin)
                val = ADC.read(pin)
                potis.append(round(val * 100))
            if sum(potis) == 0:
                change = True
            else:
                for i in range(3):
                    for led in self.leds:
                        GPIO.output(led, GPIO.HIGH)
                    time.sleep(.05)
                    for led in self.leds:
                        GPIO.output(led, GPIO.LOW)
                    time.sleep(.05)
        return (new_state if change else self.cargo.state, change)
示例#5
0
def waitingForSketch():
    if GPIO.event_detected(N):
        global toggle0
        GPIO.output(LED_list[0],toggle0)
        toggle0 ^= 1 
        move_N()
        
    if GPIO.event_detected(S):
        global toggle1
        GPIO.output(LED_list[1],toggle1)
        toggle1 ^= 1 
        move_S()
        
    if GPIO.event_detected(W):
        global toggle2
        GPIO.output(LED_list[2],toggle2)
        toggle2 ^= 1 
        move_W()
        
    if GPIO.event_detected(E):
        global toggle3
        GPIO.output(LED_list[3],toggle3)
        toggle3 ^= 1 
        move_E() 
        
    if GPIO.event_detected(C):
        erase_all()
        global x,y
        x=canvas_width/2
        y=canvas_height/2
# call itself every 10 ms
    window.after(10, waitingForSketch)    
示例#6
0
def main(stdscr):
    # Use --size to specify size of board. Defaults to 8x8
    parser = argparse.ArgumentParser()
    parser.add_argument("--size", type=int, default=8)
    args = parser.parse_args()
    size = args.size

    # Setup curses
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(True)
    curses.curs_set(1)

    # Setup GPIO
    GPIO.setup("P9_22", GPIO.IN)  # down
    GPIO.add_event_detect("P9_22", GPIO.RISING)

    GPIO.setup("P9_24", GPIO.IN)  # left
    GPIO.add_event_detect("P9_24", GPIO.RISING)

    GPIO.setup("P9_23", GPIO.IN)  # up
    GPIO.add_event_detect("P9_23", GPIO.RISING)

    GPIO.setup("P9_21", GPIO.IN)  # right
    GPIO.add_event_detect("P9_21", GPIO.RISING)

    GPIO.setup("P9_26", GPIO.IN)  # clear
    GPIO.add_event_detect("P9_26", GPIO.RISING)

    new_frame(stdscr, size)

    cur_x = 0
    cur_y = 0

    while True:
        stdscr.refresh()

        # Updates current position based on button pressed
        if GPIO.event_detected("P9_24"):
            if cur_x > 0:
                cur_x = cur_x - 1
        elif GPIO.event_detected("P9_21"):
            if cur_x < size - 1:
                cur_x = cur_x + 1
        elif GPIO.event_detected("P9_23"):
            if cur_y > 0:
                cur_y = cur_y - 1
        elif GPIO.event_detected("P9_22"):
            if cur_y < size - 1:
                cur_y = cur_y + 1
        elif GPIO.event_detected("P9_26"):
            new_frame(stdscr, size)
            cur_x = 0
            cur_y = 0

        # Prints an X in the current position
        stdscr.addstr(5 + cur_y, 2 + cur_x * 2, 'X')
        stdscr.move(5 + cur_y, 2 + cur_x * 2)
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
示例#8
0
def main():
    etchwinsize = int(input(
        "Window Size nxn n = "))  #window size plus one column for row numbers
    global matrixarray
    matrixarray = [0x00] * etchwinsize * 2
    cursorlocation = etchwinsize + 2  #sets default location of cursor
    display_array = ["1"] * etchwinsize * etchwinsize  #initial display array
    previouslocation = cursorlocation
    display_array = renderdisplay(previouslocation, cursorlocation,
                                  etchwinsize,
                                  display_array)  #renders the text display
    while (1):
        if GPIO.event_detected(Buttons[0]):
            break
        if GPIO.event_detected(Buttons[1]):
            display_array = ["1"] * etchwinsize * etchwinsize
            cursorlocation = etchwinsize + 2
            matrixarray = [0x00] * etchwinsize * 2
            previouslocation = cursorlocation
            display_array = renderdisplay(
                previouslocation, cursorlocation, etchwinsize,
                display_array)  #renders the text display
        elif (myEncoder.position < 0):  #up
            if (cursorlocation / etchwinsize > 0):
                previouslocation = cursorlocation
                cursorlocation = cursorlocation - etchwinsize
                display_array = renderdisplay(
                    previouslocation, cursorlocation, etchwinsize,
                    display_array)  #renders the text display
            myEncoder.zero()
        elif (myEncoder2.position < 0):  #left
            if (cursorlocation % etchwinsize > 0):
                previouslocation = cursorlocation
                cursorlocation = cursorlocation - 1
                display_array = renderdisplay(
                    previouslocation, cursorlocation, etchwinsize,
                    display_array)  #renders the text display
            myEncoder2.zero()
        elif (myEncoder2.position > 0):
            if (cursorlocation % etchwinsize < etchwinsize - 1):
                previouslocation = cursorlocation
                cursorlocation = cursorlocation + 1
                display_array = renderdisplay(
                    previouslocation, cursorlocation, etchwinsize,
                    display_array)  #renders the text display
            myEncoder2.zero()
        elif (myEncoder.position > 0):
            if (cursorlocation < etchwinsize * (etchwinsize - 1)):
                previouslocation = cursorlocation
                cursorlocation = cursorlocation + etchwinsize
                display_array = renderdisplay(
                    previouslocation, cursorlocation, etchwinsize,
                    display_array)  #renders the text display
            myEncoder.zero()
示例#9
0
def main():
    # Setup GPIO
    GPIO.setup("P9_22", GPIO.IN)  # down
    GPIO.add_event_detect("P9_22", GPIO.RISING)
    GPIO.setup("P9_12", GPIO.OUT)
    led0 = False

    GPIO.setup("P9_24", GPIO.IN)  # left
    GPIO.add_event_detect("P9_24", GPIO.RISING)
    GPIO.setup("P9_13", GPIO.OUT)
    led1 = False

    GPIO.setup("P9_23", GPIO.IN)  # up
    GPIO.add_event_detect("P9_23", GPIO.RISING)
    GPIO.setup("P9_11", GPIO.OUT)
    led2 = False

    GPIO.setup("P9_21", GPIO.IN)  # right
    GPIO.add_event_detect("P9_21", GPIO.RISING)
    GPIO.setup("P9_14", GPIO.OUT)
    led3 = False

    GPIO.setup("P9_26", GPIO.IN)  # clear
    GPIO.add_event_detect("P9_26", GPIO.RISING)

    # If button is pressed, switch the appropriate LED
    while True:
        if GPIO.event_detected("P9_23"):
            switch_led(11, led2)
            led2 = not led2

        if GPIO.event_detected("P9_22"):
            switch_led(12, led0)
            led0 = not led0

        if GPIO.event_detected("P9_24"):
            switch_led(13, led1)
            led1 = not led1

        if GPIO.event_detected("P9_21"):
            switch_led(14, led3)
            led3 = not led3

        if GPIO.event_detected("P9_26"):
            GPIO.output("P9_11", GPIO.LOW)
            led2 = False
            GPIO.output("P9_12", GPIO.LOW)
            led0 = False
            GPIO.output("P9_13", GPIO.LOW)
            led1 = False
            GPIO.output("P9_14", GPIO.LOW)
            led3 = False
示例#10
0
def switchOnFall(inPins, outPins):
    #thread function
    while running:
        event = False
        #GPIO.wait_for_edge(inPin,GPIO.FALLING) #blocking call
        for Kappa in range(0, len(inPins)):
            inPin = inPins[Kappa]
            outPin = outPins[Kappa]
            if (GPIO.event_detected(inPin)):  #polls the flag
                GPIO.output(outPin, 1 ^ GPIO.input(outPin))
                event = True
        time.sleep(0.1)  # debouncing time frame
        if (event):
            for inPin in inPins:
                GPIO.event_detected(inPin)  # clears all pin flags
示例#11
0
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!"
示例#12
0
 def set_refzero(self):
     if GPIO.event_detected(WALKINGCONFIRM):
         if time.time() - self.lastmode1 > 1:
             state = self.refzero
             self.refzero = not state
             self.rootLogger.info('RefZero was turned {}'.format(not state))
             self.lastmode1 = time.time()
示例#13
0
 def set_mode2(self):
     if GPIO.event_detected(INFINITYMODE):
         if time.time() - self.lastmode2 > 1:
             state = self.mode2
             self.mode2 = not state
             self.rootLogger.info('Mode2 was turned {}'.format(not state))
             self.lastmode2 = time.time()
示例#14
0
    def _loop(self):
        """Inner loop of the driver."""
        while True:
            beginT = time.time()  # Save start time of loop cycle

            if self._mode == 'State':
                if (self._muxedPin != None):
                    MuxModule.activate(self._muxName,
                                       self._muxedPin)  # Activate mux pin
                self._currentValue = GPIO.input(self._pin)  # Read the value
                if (self._muxedPin != None):
                    MuxModule.deactivate(self._muxName)  # Deactivate mux
            elif self._mode == 'Rising Edge' or self._mode == 'Falling Edge':
                if GPIO.event_detected(self._pin):
                    self._currentValue = 1  # Return 1 for event
                else:
                    self._currentValue = 0  # Return 0 for no event

            self._values.append([time.time(), [self._currentValue]
                                 ])  # Save timestamp and value

            endT = time.time()  # Save start time of loop cycle
            deltaT = endT - beginT  # Calculate time used for loop cycle
            self._cycleDuration = deltaT  # Save time needed for a cycle
            if (deltaT < self._period):
                time.sleep(self._period -
                           deltaT)  # Sleep until next loop period

            if not self._threadActive:  # Stop the thread
                return
示例#15
0
def waitingForSketch():
    if GPIO.event_detected(N):
        move_N()
    if GPIO.event_detected(S):
        move_S()
    if GPIO.event_detected(W):
        move_W()
    if GPIO.event_detected(E):
        move_E() 
    if GPIO.event_detected(C):
        erase_all()
        global x,y
        x=0
        y=0
# call itself every 100 ms
    sleep(0.1)  
示例#16
0
def main():
	print "Setting up GPIO"

	# Variables
	GPIO.setup("P9_11", GPIO.IN)
	GPIO.add_event_detect("P9_11", GPIO.BOTH)
	GPIO.setup("P9_15", GPIO.OUT)
	global running

	try:

		while True:
			if GPIO.event_detected("P9_11"):
				if GPIO.input("P9_11"):
					print "Hazards on"
					running = True
					t1 = threading.Thread( target = blink_leds, args = ( "P9_15", ) )
					t1.setDaemon( True )
					t1.start()
				else:
					running = False
					print "Hazards off"
					GPIO.output("P9_15", GPIO.LOW)	


	except KeyboardInterrupt:

		GPIO.cleanup()
		print "Ending program"
示例#17
0
 def set_walking(self):
     if GPIO.event_detected(WALKINGCONFIRM):
         if time.time() - self.lastconfirm > 1:
             confirm = self.cargo.wcomm.confirm
             self.cargo.wcomm.confirm = not confirm
             self.rootLogger.info(
                 'Walking was turned {}'.format(not confirm))
             self.lastconfirm = time.time()
示例#18
0
 def fun1():
     if GPIO.event_detected(FUN1):
         if time.time()-self.lastfun1 > 1:
             state = self.fun1
             self.fun1 = not state
             self.rootLogger.info('Fun1 turned {}'.format(not state))
             self.lastfun1 = time.time()
     return self.fun1
示例#19
0
 def fun2():
     if GPIO.event_detected(FUN2):
         if time.time()-self.lastfun2 > 1:
             state = self.fun2
             self.fun2 = not state
             self.rootLogger.info('Fun2 turned {}'.format(not state))
             self.lastfun2 = time.time()
     return self.fun2
	def run(self):
		GPIO.add_event_detect(self.pins[0], GPIO.RISING)
		while True:
			if GPIO.event_detected(self.pins[0]):
				self.edgeDetected()
			if time.time() - self.currentEdge > self.timeout:
				self.setZero()
				self.publish()
示例#21
0
def event_detected(pin_id):
	if pin_id[0] == 'P':
		return GPIO.event_detected(pin_id)
	elif pin_id[0] == 'E':
		raise Exception("Interrupt feature is not yet implemented on this pin (" + pin_id + ")")
	else:
		pin_id_error()
	return 0
示例#22
0
def main():
    global status
    status = -1  # up = 1, down = 0
    motor = pinConfig()
    motor.setPin()

    if GPIO.input(motor.upperSW):  # if on upperSW move down
        print "@Upper switch..."
        status = motor.moveDOWN()
    elif GPIO.input(motor.lowerSW):  # if on lowerSW move up
        print "@Lower switch..."
        status = motor.moveUP()
    else:
        print "@Middle..."
        status = motor.moveUP()

    # print "GPIO event enabled"
    GPIO.add_event_detect(motor.upperSW, GPIO.RISING, bouncetime=1000)
    GPIO.add_event_detect(motor.lowerSW, GPIO.RISING, bouncetime=1000)

    try:
        while True:
            # print status
            if status == 1:
                if GPIO.input(motor.upperSW) and GPIO.event_detected(
                        motor.upperSW):
                    print "@Upper switch..."
                    motor.moveStop()
                    print "... ... Sleep ZZZzz"
                    time.sleep(pinConfig.restTIme)
                    status = motor.moveDOWN()

            elif status == 0:
                if GPIO.input(motor.lowerSW) and GPIO.event_detected(
                        motor.lowerSW):
                    print "@Lower switch..."
                    motor.moveStop()
                    print "... ... Sleeping ZZZzz"
                    time.sleep(pinConfig.restTIme)
                    status = motor.moveUP()

    except KeyboardInterrupt:
        motor.moveStop()
        GPIO.cleanup()
示例#23
0
def event_detected(pin_id):
    if pin_id[0] == 'P':
        return GPIO.event_detected(pin_id)
    elif pin_id[0] == 'E':
        raise Exception(
            "Interrupt feature is not yet implemented on this pin (" + pin_id +
            ")")
    else:
        pin_id_error()
    return 0
示例#24
0
 def run(self):
     for pin in self.input_pins:
         GPIO.add_event_detect(pin, GPIO.FALLING)
     while True:
         for pin in self.input_pins:
             if GPIO.event_detected(pin):
                 t = time()
                 if t > self.ltime[pin] + self.EVENT_INTERVAL:
                     self.ltime[pin] = t
                     self.handlers[pin]()
示例#25
0
def main():
    global status
    status = -1  # up = 1, down = 0
    motor = pinConfig()
    motor.setPin()

    if GPIO.input(motor.upperSW):  # if on upperSW move down
        print "@Upper switch..."
        status = motor.moveDOWN()
    elif GPIO.input(motor.lowerSW):  # if on lowerSW move up
        print "@Lower switch..."
        status = motor.moveUP()
    else:
        print "@Middle..."
        status = motor.moveUP()

    # print "GPIO event enabled"
    GPIO.add_event_detect(motor.upperSW, GPIO.RISING, bouncetime=1000)
    GPIO.add_event_detect(motor.lowerSW, GPIO.RISING, bouncetime=1000)

    try:
        while True:
            # print status
            if status == 1:
                if GPIO.input(motor.upperSW) and GPIO.event_detected(motor.upperSW):
                    print "@Upper switch..."
                    motor.moveStop()
                    print "... ... Sleep ZZZzz"
                    time.sleep(pinConfig.restTIme)
                    status = motor.moveDOWN()

            elif status == 0:
                if GPIO.input(motor.lowerSW) and GPIO.event_detected(motor.lowerSW):
                    print "@Lower switch..."
                    motor.moveStop()
                    print "... ... Sleeping ZZZzz"
                    time.sleep(pinConfig.restTIme)
                    status = motor.moveUP()

    except KeyboardInterrupt:
        motor.moveStop()
        GPIO.cleanup()
示例#26
0
def __check_for_events():
    global __pool_pin_codes
    for pin_code in __pool_pin_codes:
        if GPIO.event_detected(pin_code):
            state = GPIO.input(pin_code)
            # Log.logger.info('Pooling event detected gpio {} val {}'.format(pin_code, state))
            dispatcher.send(Constant.SIGNAL_GPIO,
                            gpio_pin_code=pin_code,
                            direction='in',
                            pin_value=state,
                            pin_connected=(state == 0))
示例#27
0
def gridMove(grid, i2cDisplay, inputs):
    #copy pasted from last assignment
    x = 0
    y = 0
    grid[y][x] = 1
    writeToDisplay(grid, i2cDisplay)
    while running:
        event = False
        #check for events
        for Kappa in range(0, len(inputs)):
            if (GPIO.event_detected(inputs[Kappa])):
                event = True
                if (Kappa == 0):  #hardcoded, ew
                    x -= 1
                elif (Kappa == 1):
                    x += 1
                elif (Kappa == 2):
                    y -= 1
                elif (Kappa == 3):
                    y += 1
                elif (Kappa == 4):
                    for NotLikeThis in range(0, size):
                        for BabyRage in range(0, size):
                            grid[NotLikeThis][BabyRage] = 0

#keep the pen inside the grid
        if (x > size - 1):
            x = size - 1
        if (x < 0):
            x = 0
        if (y > size - 1):
            y = size - 1
        if (y < 0):
            y = 0

        time.sleep(0.2)  #debouncing
        if (event):
            grid[y][x] = min(2, grid[y][x] + 1)
            writeToDisplay(grid, i2cDisplay)
            for inPin in inputs:
                GPIO.event_detected(inPin)  # clears all pin flags
示例#28
0
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
示例#29
0
def main():
	etchwinsize=int(input("Window Size nxn n = "))+1 #window size plus one column for row numbers
	cursorlocation = etchwinsize+2 #sets default location of cursor
	display_array = ["1"]*etchwinsize*etchwinsize #initial display array
	display_array = renderdisplay(cursorlocation,etchwinsize,display_array)#renders the text display
	while(1):
		if GPIO.event_detected(Buttons[0]):
			break
		if GPIO.event_detected(Buttons[1]):
			display_array = ["1"]*etchwinsize*etchwinsize
			cursorlocation = etchwinsize+2
			display_array = renderdisplay(cursorlocation,etchwinsize,display_array)#renders the text display
		elif GPIO.event_detected(Buttons[2]):
			if (cursorlocation/etchwinsize>2):
				cursorlocation=cursorlocation-etchwinsize
				display_array = renderdisplay(cursorlocation,etchwinsize,display_array)#renders the text display
		elif GPIO.event_detected(Buttons[3]):
			if (cursorlocation%etchwinsize>1):
				cursorlocation=cursorlocation-1
				display_array = renderdisplay(cursorlocation,etchwinsize,display_array)#renders the text display
		elif GPIO.event_detected(Buttons[4]):
			if (cursorlocation%etchwinsize<etchwinsize-1):
				cursorlocation=cursorlocation+1
				display_array = renderdisplay(cursorlocation,etchwinsize,display_array)#renders the text display
		elif GPIO.event_detected(Buttons[5]):
			if (cursorlocation/etchwinsize<etchwinsize-1):
				cursorlocation=cursorlocation+etchwinsize
				display_array = renderdisplay(cursorlocation,etchwinsize,display_array)#renders the text display
示例#30
0
 def checkFlow(self):
     self.currentTime = datetime.datetime.now().replace(microsecond = 0)
     if GPIO.event_detected("P9_41"):
         self.lastDetected = datetime.datetime.now().replace(microsecond = 0)
         self.totalPulses = self.totalPulses + 1
         self.eventPulses = self.eventPulses + 1
         if self.longTimer != None:
             self.longTimer.cancel()
             self.log()
     elif isFlowing() == False:
         if self.shortTimer != None:
             self.shortTimer.cancel()
             self.log()
示例#31
0
    def test_the_thing(self):
        state, change = self.check_state()
        if change:
            print(state)

        for idx, pin in enumerate(DISCRETEPRESSUREREF):
            print('DValve Ref', idx, ': ', True if GPIO.input(pin) else False)

        # check pattern btns
        if GPIO.event_detected(INFINITYMODE):
            print('Infmode btn pushed')
        if GPIO.event_detected(WALKINGCONFIRM):
            print('WALKING START btn pushed')

        # check adc potis
        for idx, pin in enumerate(CONTINUOUSPRESSUREREF):
            val = ADC.read(pin)
            val = ADC.read(pin)
            print('POTI Ref', idx, ': ', val)
        time.sleep(1)

        print('\n')
示例#32
0
        def mode_changed():
            new_state = None
            if GPIO.event_detected(MODE1):
                new_state = MODE[1]['ui_state']
            elif GPIO.event_detected(MODE2):
                new_state = MODE[2]['ui_state']
            elif GPIO.event_detected(MODE3):
                new_state = MODE[3]['ui_state']
            elif self.ui_state == 'EXIT':
                new_state = 'EXIT'

            change = False
            if new_state and time.time()-self.lastchange > 1:
                if all_potis_zero() and new_state is not self.ui_state or new_state == 'EXIT':
                    change = True
                    self.ui_state = new_state
                    self.rootLogger.info("UI goes to: {}".format(new_state))
                    reset_events()
                    self.lastchange = time.time()
                else:
                    flicker_leds()
            return change
示例#33
0
def moveOnGrid(grid, inputs, sizeX, sizeY):
    x = 0
    y = 0
    grid[y][x] = True
    printGrid(grid)
    while running:
        event = False
        for Kappa in range(0, len(inputs)):
            if (GPIO.event_detected(inputs[Kappa])):
                event = True
                if (Kappa == 0):  #hardcoded, ew
                    x -= 1
                elif (Kappa == 1):
                    x += 1
                elif (Kappa == 2):
                    y -= 1
                elif (Kappa == 3):
                    y += 1
                elif (Kappa == 4):
                    for NotLikeThis in range(0, len(grid)):
                        for BabyRage in range(0, len(grid[0])):
                            grid[NotLikeThis][BabyRage] = False
        #keep the pen inside the grid
        if (x > sizeX - 1):
            x = sizeX - 1
        if (x < 0):
            x = 0
        if (y > sizeY - 1):
            y = sizeY - 1
        if (y < 0):
            y = 0

        time.sleep(0.2)  #debouncing
        if (event):
            grid[y][x] = True
            printGrid(grid)
            for inPin in inputs:
                GPIO.event_detected(inPin)  # clears all pin flags
示例#34
0
 def updateButtonStates(self):
     """
     
     Input: N/A
     Output: int(self.buttonState)
     
     Check input pins for button presses and record them into button state, and then return it.
     
     """
     self.buttonState = ButtonState.noBtn
     if GPIO.event_detected("P8_7"):
         self.buttonState |= ButtonState.frontBumper
     if GPIO.event_detected("P8_8"):
         self.buttonState |= ButtonState.backBumper
     if GPIO.event_detected("P8_9"):
         self.buttonState |= ButtonState.forwardBtn
     if GPIO.event_detected("P8_10"):
         self.buttonState |= ButtonState.backBtn
     if GPIO.event_detected("P8_11"):
         self.buttonState |= ButtonState.stopBtn
     #l = Log()
     #l.ShowDebug("ButtonState: %d" % self.buttonState)
     return self.buttonState
 def updateButtonStates(self):
     """
     
     Input: N/A
     Output: int(self.buttonState)
     
     Check input pins for button presses and record them into button state, and then return it.
     
     """    
     self.buttonState = ButtonState.noBtn
     if GPIO.event_detected("P8_7"):
         self.buttonState |= ButtonState.frontBumper
     if GPIO.event_detected("P8_8"):
         self.buttonState |= ButtonState.backBumper
     if GPIO.event_detected("P8_9"):
         self.buttonState |= ButtonState.forwardBtn
     if GPIO.event_detected("P8_10"):
         self.buttonState |= ButtonState.backBtn
     if GPIO.event_detected("P8_11"):
         self.buttonState |= ButtonState.stopBtn
     #l = Log()
     #l.ShowDebug("ButtonState: %d" % self.buttonState)
     return self.buttonState
示例#36
0
    def check_state(self):
        new_state = None
        if GPIO.event_detected(PWMREFMODE):
            new_state = 'USER_CONTROL'
        elif GPIO.event_detected(PRESSUREREFMODE):
            new_state = 'USER_REFERENCE'
        elif GPIO.event_detected(PATTERNREFMODE):
            new_state = 'PATTERN_REF'

        change = False
        if new_state:
            if self.all_potis_zero():
                change = True
            else:
                for i in range(3):
                    for led in self.leds:
                        GPIO.output(led, GPIO.HIGH)
                    time.sleep(.05)
                    for led in self.leds:
                        GPIO.output(led, GPIO.LOW)
                    time.sleep(.05)
        self.state = new_state if change else self.state
        return (self.state, change)
def interupts():
    if GPIO.event_detected("P9_11"):
        if GPIO.input("P8_39") == 0:
            GPIO.output("P8_39", GPIO.HIGH)
        else:
            GPIO.output("P8_39", GPIO.LOW)

    if GPIO.event_detected("P9_13"):
        if GPIO.input("P8_41") == 0:
            GPIO.output("P8_41", GPIO.HIGH)
        else:
            GPIO.output("P8_41", GPIO.LOW)

    if GPIO.event_detected("P9_15"):
        if GPIO.input("P8_43") == 0:
            GPIO.output("P8_43", GPIO.HIGH)
        else:
            GPIO.output("P8_43", GPIO.LOW)

    if GPIO.event_detected("P9_17"):
        if GPIO.input("P8_45") == 0:
            GPIO.output("P8_45", GPIO.HIGH)
        else:
            GPIO.output("P8_45", GPIO.LOW)
示例#38
0
文件: lift.py 项目: vedantini/codes
def main():
    ## pin setup and initialization ##
    for key in sevenSegDisplay:
        GPIO.setup(sevenSegDisplay[key], GPIO.OUT)

    for pin in floorButtons:
        GPIO.setup(pin, GPIO.IN)
        GPIO.add_event_detect(pin, GPIO.FALLING)

    currentFloor = 0
    destFloor = 0
    displayNum(0) ## lift is at floor 0 ##

    while True:
        for pin in floorButtons:
            if GPIO.event_detected(pin):
                destFloor = floorButtons.index(pin)
                break

        time.sleep(0.02)

        if currentFloor != destFloor:
            time.sleep(0.25)

            step = 0
            if currentFloor < destFloor:
                step = 1
            else:
                step = -1

            while (currentFloor + step) != destFloor:
                time.sleep(2)
                currentFloor += step
                displayNum(currentFloor)

            time.sleep(2.25)
            currentFloor += step
            for i in range (3):
                setAllLeds(0)
                time.sleep(0.5)
                displayNum(currentFloor)
                time.sleep(0.5)
示例#39
0
文件: run.py 项目: jflowaa/smart_home
def run_detector():
    model = config["DEVICE"]["Model"]
    pin = config["DEVICE"]["GPIOPin"]
    delay = int(config["DEVICE"]["NotifyRate"])
    if model == "pi":
        import RPi.GPIO as io
        io.setmode(io.BCM)
        io.setup(int(pin), io.IN)
        while True:
            if io.input(pin):
                send_motion_event()
                time.sleep(delay * 60)
            time.sleep(1)
    elif model == "bone":
        from Adafruit_BBIO import GPIO
        GPIO.setup(pin, GPIO.IN)
        GPIO.add_event_detect(pin, GPIO.RISING)
        while True:
            if GPIO.event_detected(pin):
                send_motion_event()
                time.sleep(delay * 60)
            time.sleep(1)
示例#40
0
import Adafruit_BBIO.GPIO as GPIO


GPIO.setup("P9_11", GPIO.IN) #OUTA
GPIO.setup("P9_12", GPIO.IN) #OUTB

GPIO.add_event_detect("P9_11", GPIO.RISING)
GPIO.add_event_detect("P9_12", GPIO.RISING)

while True:

	if GPIO.event_detected("P9_11") or GPIO.event_detected("P9_12"):
		print 'Robot is moving.\n'

示例#41
0
#!/usr/bin/env python
import Adafruit_BBIO.GPIO as GPIO
import time

pin = "P8_12"
GPIO.setup(pin, GPIO.IN)

'''
switch_state = 0

while True:
    GPIO.wait_for_edge(pin, GPIO.RISING)
    print ("pressed")
    GPIO.wait_for_edge(pin, GPIO.FALLING)
    print ("released")
'''

GPIO.add_event_detect(pin, GPIO.RISING)
time.sleep(10)
if GPIO.event_detected(pin):
    print ("detected!")
示例#42
0
文件: tmp101.py 项目: MikuZZZ/ECE597
import Adafruit_BBIO.GPIO as GPIO
from time import sleep

#ALERT_1 = "P8_45"
ALERT_1 = "P9_41"
ALERT_2 = "P8_43"
ALERT_LED = "P9_12"
TMP_1 = Adafruit_I2C(0x48)
TMP_2 = Adafruit_I2C(0x4a)

TMP_1.write8(3, 0x1c)
TMP_1.write8(2, 0x1a)
TMP_1.write8(1, 0x04)

TMP_2.write8(3, 0x1c)
TMP_2.write8(2, 0x1a)
TMP_2.write8(1, 0x04)

GPIO.setup(ALERT_1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(ALERT_2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(ALERT_LED, GPIO.OUT)

GPIO.add_event_detect(ALERT_1, GPIO.BOTH)

while(True):
    print "TMP1: ", TMP_1.readU8(0)
    if GPIO.event_detected(ALERT_1):
        sleep(0.2)
        print "ALERT1 detected"

示例#43
0
文件: LEDetch.py 项目: vaddera/ECE597
#display.begin()

# Clearing the LED matrix to begin:
display.clear()

while True:
	# Updates the LED display:
	#display.write_display()

	fs1 = open('/sys/devices/ocp.3/48302000.epwmss/48302180.eqep/position','r')
	fs2 = open('/sys/devices/ocp.3/48304000.epwmss/48304180.eqep/position','r')

	curr_read1 = int(fs1.read())/4
	curr_read2 = int(fs2.read())/4

	if GPIO.event_detected("P9_21") or curr_read1 < prev_read1:
	#if GPIO.input("P9_21"):
		if curr_row <= 0:
			curr_row = 0
		else:
			curr_row = curr_row - 1
		first_stroke = 1

	if GPIO.event_detected("P9_23") or curr_read1 > prev_read1:
	#if GPIO.input("P9_23"):
		if curr_row >= 7:
			curr_row = 7
		else:
			curr_row = curr_row + 1
		first_stroke = 1
示例#44
0
文件: run.py 项目: jflowaa/PIR_light
parser.add_argument("-pin", type=str, help="GPIO pin of sensor", default="P9_12", dest="PIR")
parser.add_argument("IP", type=str, help="IP of WiFi lightbulb")
parser.add_argument("offset", type=int, help="How long the light stays on")
parser.add_argument("-schedule", type=bool, help="Run system on schedule?", default=False)
args = parser.parse_args()

if args.schedule:
    print("TODO: Schedule feature")

GPIO.setup(args.PIR, GPIO.IN)
GPIO.add_event_detect(args.PIR, GPIO.RISING)
lightcontrol = LightControl(args.IP, 5577)

turn_off_time = current_time  = datetime.now()
print("Starting System")
print("Offset is set at {} minutes.".format(args.offset))
while True:
    try:
        if current_time >= turn_off_time:
            lightcontrol.turn_off()
        if GPIO.event_detected(args.PIR):
            lightcontrol.turn_on()
            turn_off_time = datetime.now() + timedelta(minutes=args.offset)
        current_time = datetime.now()
        time.sleep(1)
    except:
        try:
            lightcontrol = LightControl(args.IP, 5577)
        except:
            time.sleep(15)
            if pressed_key and time.time() >= (keydown_time + 0.1):
                # Deassert all of the key lines
                for i in xrange(5):
                    GPIO.output(OUTPUTS['MKEY%u' % (i+1)], GPIO.LOW)

                # Deassert RSET's line
                GPIO.output(OUTPUTS['CAURST'], GPIO.LOW)

                # Assert MAINRS
                GPIO.output(OUTPUTS['MAINRS'], GPIO.HIGH)
                pressed_key = False

            # Handle relay words
            relayword_changed = False
            for net in RELAYWORD_NETS:
                if GPIO.event_detected(INPUTS[net]):
                    relayword_changed = True

            if relayword_changed:
                relayword_time = time.time()
                relays_latching = True

            if relays_latching and time.time() >= (relayword_time + 0.005):
                relays_latching = False
                relayword = 0
                for i,net in enumerate(RELAYWORD_NETS):
                    if GPIO.input(INPUTS[net]):
                        relayword |= (1 << i)

                send_io_packet(conn, 0o10, relayword)
示例#46
0
def main():
    status = [0, -1, -1]  # [ignore,device1,device2] up = 1, down = 0
    startTime = [0, 0, 0]
    ready = [0, 0, 0]
    sleepTimer = [0, 0, 0]
    motor1 = pinConfig()
    motor1.setGPIO("P9_15", "P9_12", "P9_25", "P9_28", "P9_14")
    motor1.setPin()

    motor2 = pinConfig()
    motor2.setGPIO("P8_17", "P8_15", "P9_29", "P9_31", "P8_13")
    motor2.setPin()

    if GPIO.input(motor1.upperSW):  # if on upperSW move down
        print "Motor1 @Upper switch..."
        status[1], startTime[1] = motor1.moveDOWN(1)
    elif GPIO.input(motor1.lowerSW):  # if on lowerSW move up
        print "Motor1 @Lower switch..."
        status[1], startTime[1] = motor1.moveUP(1)
    else:
        print "Motor1 @Middle..."
        status[1], startTime[1] = motor1.moveUP(1)

    if GPIO.input(motor2.upperSW):
        print "Motor2 @Upper switch..."
        status[2], startTime[2] = motor2.moveDOWN(2)
    elif GPIO.input(motor2.lowerSW):
        print "Motor2 @Lower switch..."
        status[2], startTime[2] = motor2.moveUP(2)
    else:
        print "Motor2 @Middle..."
        status[2], startTime[2] = motor2.moveUP(2)

    print "GPIO event enabled"
    GPIO.add_event_detect(motor1.upperSW, GPIO.RISING, bouncetime=1000)
    GPIO.add_event_detect(motor1.lowerSW, GPIO.RISING, bouncetime=1000)
    GPIO.add_event_detect(motor2.upperSW, GPIO.RISING, bouncetime=1000)
    GPIO.add_event_detect(motor2.lowerSW, GPIO.RISING, bouncetime=1000)

    try:
        while True:
            # print status
            if status[1] == 1:
                if GPIO.input(motor1.upperSW) and GPIO.event_detected(motor1.upperSW):
                    print "Motor1 @Upper switch..."
                    startTime[1], sleepTimer[1] = motor1.moveStop(1)

                if ready[1] == 1:
                    status[1], startTime[1] = motor1.moveDOWN(1)
                    ready[1] = 0

                if timeCal(startTime[1]) > pinConfig.timeout:
                    startTime[1], sleepTimer[1] = motor1.moveStop(1)
                    status[1] = 0

            elif status[1] == 0:
                if GPIO.input(motor1.lowerSW) and GPIO.event_detected(motor1.lowerSW):
                    print "Motor1 @Lower switch..."
                    startTime[1], sleepTimer[1] = motor1.moveStop(1)

                if ready[1] == 1:
                    status[1], startTime[1] = motor1.moveUP(1)
                    ready[1] = 0

                if timeCal(startTime[1]) > pinConfig.timeout:
                    startTime[1], sleepTimer[1] = motor1.moveStop(1)
                    status[1] = 1

            if status[2] == 1:
                if GPIO.input(motor2.upperSW) and GPIO.event_detected(motor2.upperSW):
                    print "Motor2 @Upper switch..."
                    startTime[2], sleepTimer[2] = motor2.moveStop(2)

                if ready[2] == 1:
                    status[2], startTime[2] = motor2.moveDOWN(2)
                    ready[2] = 0

                if timeCal(startTime[2]) > pinConfig.timeout:
                    startTime[2], sleepTimer[2] = motor2.moveStop(2)
                    status[2] = 0

            elif status[2] == 0:
                if GPIO.input(motor2.lowerSW) and GPIO.event_detected(motor2.lowerSW):
                    print "Motor2 @Lower switch..."
                    startTime[2], sleepTimer[2] = motor2.moveStop(2)

                if ready[2] == 1:
                    status[2], startTime[2] = motor2.moveUP(2)
                    ready[2] = 0

                if timeCal(startTime[2]) > pinConfig.timeout:
                    startTime[2], sleepTimer[2] = motor2.moveStop(2)
                    status[2] = 1

            if timeCal(sleepTimer[1]) > pinConfig.restTime:
                ready[1] = 1
            if timeCal(sleepTimer[2]) > pinConfig.restTime:
                ready[2] = 1


    except KeyboardInterrupt:
        motor1.moveStop()
        motor2.moveStop()
        GPIO.cleanup()
示例#47
0
def main():
    global status
    global motor
    status = -1  # up = 1, down = 0
    nextMove = -1
    startTime = 0
    sleepTimer = 1000
    motor = pinConfig()
    motor.setPin()

    if GPIO.input(motor.upperSW):  # if on upperSW move down
        print "@Upper switch..."
        nextMove, startTime = motor.moveDOWN()

    elif GPIO.input(motor.lowerSW):  # if on lowerSW move up
        print "@Lower switch..."
        nextMove, startTime = motor.moveUP()

    else:
        print "@Middle...no switch detected"
        nextMove, startTime = motor.moveUP()


    try:
        while True:
            #stop motor when upper switch trigger
            if GPIO.event_detected(motor.upperSW) and GPIO.input(motor.upperSW):
                sleepTimer = motor.moveStop(motor.upperSW)
                status = 1
                print "stop1"

            #timeout condition @ upperSW
            elif GPIO.input(motor.upperSW) and timeCal(startTime) > pinConfig.timeout:
                print "Motor @Upper Switch timeout..."
                sleepTimer = motor.moveStop(motor.upperSW)
                nextMove, startTime = motor.moveDOWN()
                status = 0

            #stop motor when lower switch trigger
            if GPIO.event_detected(motor.lowerSW) and GPIO.input(motor.lowerSW):
                sleepTimer = motor.moveStop(motor.lowerSW)
                status = 1
                print "stop2"

            #timeout condition @ lowerSW
            elif GPIO.input(motor.lowerSW) and timeCal(startTime) > pinConfig.timeout:
                print "Motor @Lower Switch timeout..."
                sleepTimer = motor.moveStop(motor.lowerSW)
                nextMove, startTime = motor.moveUP()
                status = 0

            # motor timeout without upperSW/lowerSW
            if nextMove == 0 and GPIO.input(motor.lowerSW):
                if timeCal(startTime) > pinConfig.swTime:
                    print "Motor timeout...no movement detected"
                    try:
                        sleepTimer = motor.moveStop(motor.upperSW)
                    except RuntimeError:
                        pass

                    print "stop3"
                    nextMove, startTime = motor.moveUP()
                    status = 0


            elif nextMove == 1 and GPIO.input(motor.upperSW):
                if timeCal(startTime) > pinConfig.swTime:
                    print "Motor timeout...no movement detected"
                    try:
                        sleepTimer = motor.moveStop(motor.lowerSW)
                    except RuntimeError:
                        pass

                    print "stop4"
                    nextMove, startTime = motor.moveDOWN()
                    status = 0

            # motor timeout without upperSW/lowerSW
            if timeCal(startTime) > pinConfig.timeout:
                print "Motor timeout...no switch detected"
                if nextMove == 0:
                    print "stop3"
                    sleepTimer = motor.moveStop(motor.upperSW)
                    print "rest3"
                    time.sleep(pinConfig.restTime)
                    nextMove, startTime = motor.moveDOWN()
                    status = 0

                elif nextMove == 1:
                    print "stop4"
                    sleepTimer = motor.moveStop(motor.lowerSW)
                    print "rest4"
                    time.sleep(pinConfig.restTime)
                    nextMove, startTime = motor.moveUP()
                    status = 0


            #switch direction after rest time lapse
            if nextMove == 0 and status == 1:
                if timeCal(sleepTimer) > pinConfig.restTime:
                    nextMove, startTime = motor.moveDOWN()
                    status = 0

            elif nextMove == 1 and status == 1:
                if timeCal(sleepTimer) > pinConfig.restTime:
                    nextMove, startTime = motor.moveUP()
                    status = 0


    except KeyboardInterrupt:
        motor.eStop()
        GPIO.cleanup()
import time
 
#create a variable called PIR, which refers to the P8_11 pin
PIR = "P8_11"
 
#initialize the pin as an INPUT
GPIO.setup(PIR, GPIO.IN)
GPIO.add_event_detect(PIR, GPIO.RISING)

def send_email():
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    my_email = "*****@*****.**"
    my_password = "******"
    destination = "*****@*****.**"
    text = "Motion has been detected at your house!"
    
    server.login(my_email, my_password)
    server.sendmail(my_email, destination, text)
    server.quit()
    print("Your email has been sent!")
       
#loop forever
while True:
    #sends an email when motion has been detected
    if GPIO.event_detected(PIR):
        send_email() 
    time.sleep(0.05) #loop every 50 miliseconds to not overburden the CPU
示例#49
0
GPIO.setup("P9_30",GPIO.IN)
GPIO.add_event_detect("P9_21", GPIO.FALLING)
GPIO.add_event_detect("P9_23", GPIO.FALLING)
GPIO.add_event_detect("P9_24", GPIO.FALLING)
GPIO.add_event_detect("P9_27", GPIO.FALLING)
GPIO.add_event_detect("P9_30", GPIO.FALLING)

display = Matrix8x8.Matrix8x8(address=0x70, busnum=1)

display.begin()

display.clear()
display.write_display()

while True:
	if GPIO.event_detected("P9_21"):
		for i in range(8):
			display.set_pixel(i,i,1)
			time.sleep(0.5)
			display.write_display()

	if GPIO.event_detected("P9_23"):
		for i in range(8):
			display.set_pixel(5,i,1)
			time.sleep(0.5)
			display.write_display()

	if GPIO.event_detected("P9_24"):
		for i in range(8):
			display.set_pixel(i,5,1)
			time.sleep(0.5)
示例#50
0
文件: gpio.py 项目: MikuZZZ/ECE597
GPIO.setup(BUTTON_2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(BUTTON_3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(BUTTON_4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

GPIO.setup(LED_1, GPIO.OUT)
GPIO.setup(LED_2, GPIO.OUT)
GPIO.setup(LED_3, GPIO.OUT)
GPIO.setup(LED_4, GPIO.OUT)

GPIO.add_event_detect(BUTTON_1, GPIO.RISING)
GPIO.add_event_detect(BUTTON_2, GPIO.RISING)
GPIO.add_event_detect(BUTTON_3, GPIO.RISING)
GPIO.add_event_detect(BUTTON_4, GPIO.RISING)

while (True):
	if GPIO.event_detected(BUTTON_1):
		sleep(0.1)
		GPIO.output(LED_1, ST_1)
		ST_1 = not ST_1
	if GPIO.event_detected(BUTTON_2):
		sleep(0.1)
		GPIO.output(LED_2, ST_2)
		ST_2 = not ST_2
	if GPIO.event_detected(BUTTON_3):
		sleep(0.1)
		GPIO.output(LED_3, ST_3)
		ST_3 = not ST_3
	if GPIO.event_detected(BUTTON_4):
		sleep(0.1)
		GPIO.output(LED_4, ST_4)
		ST_4 = not ST_4
示例#51
0
def main():
    global status
    global motor
    status = -1  # up = 1, down = 0
    nextMove = -1
    startTime = 0
    sleepTimer = 1000
    motor = pinConfig()
    motor.setPin()

    time.sleep(5)

    if GPIO.input(motor.upperSW):  # if on upperSW move down
        print "@Upper switch..."
        nextMove, startTime = motor.moveDOWN()
    elif GPIO.input(motor.lowerSW):  # if on lowerSW move up
        print "@Lower switch..."
        nextMove, startTime = motor.moveUP()
    else:
        print "@Middle..."
        nextMove, startTime = motor.moveUP()

    print "GPIO event enabled"
    GPIO.add_event_detect(motor.upperSW, GPIO.RISING, bouncetime=2000)
    GPIO.add_event_detect(motor.lowerSW, GPIO.RISING, bouncetime=2000)

    try:
        while True:
            #stop motor when switch trigger
            if GPIO.event_detected(motor.upperSW) and GPIO.input(motor.upperSW):
                sleepTimer = motor.moveStop()
                status = 1

            #timeout condition @ upperSW
            elif GPIO.input(motor.upperSW) and timeCal(startTime) > pinConfig.timeout:
                print "Motor timeout..."
                sleepTimer = motor.moveStop()
                time.sleep(pinConfig.restTime)
                status = 1
                if nextMove == 0:
                    nextMove, startTime = motor.moveDOWN()
                    status = 0
                elif nextMove == 1:
                    nextMove, startTime = motor.moveUP()
                    status = 0

            if GPIO.event_detected(motor.lowerSW) and GPIO.input(motor.lowerSW):
                sleepTimer = motor.moveStop()
                status = 1

            #timeout condition @ lowerSW
            elif GPIO.input(motor.lowerSW) and timeCal(startTime) > pinConfig.timeout:
                print "Motor timeout..."
                sleepTimer = motor.moveStop()
                time.sleep(pinConfig.restTime)
                status = 1
                if nextMove == 0:
                    nextMove, startTime = motor.moveDOWN()
                    status = 0
                elif nextMove == 1:
                    nextMove, startTime = motor.moveUP()
                    status = 0

            # motor timeout without upperSW/lowerSW
            if timeCal(startTime) > pinConfig.timeout:
                print "Motor timeout...no switch detected"
                sleepTimer = motor.moveStop()
                time.sleep(pinConfig.restTime)
                status = 1
                if nextMove == 0:
                    nextMove, startTime = motor.moveDOWN()
                    status = 0
                elif nextMove == 1:
                    nextMove, startTime = motor.moveUP()
                    status = 0

            #switch direction after rest time lapse
            if nextMove == 0 and status == 1:
                if timeCal(sleepTimer) > pinConfig.restTime:
                    nextMove, startTime = motor.moveDOWN()
                    status = 0

            elif nextMove == 1 and status == 1:
                if timeCal(sleepTimer) > pinConfig.restTime:
                    nextMove, startTime = motor.moveUP()
                    status = 0


    except KeyboardInterrupt:
        motor.eStop()
        GPIO.cleanup()
#!/usr/bin/python
# 
# Example of controlling GPIO pins with Python
# 

import Adafruit_BBIO.GPIO as GPIO
GPIO.setup("P8_10", GPIO.OUT)
GPIO.output("P8_10", GPIO.HIGH)
GPIO.cleanup()

GPIO.setup("GPIO0_26", GPIO.OUT)
GPIO.setup("P8_14", GPIO.IN)
if GPIO.input("P8_14"):
    print("HIGH")
else:
    print("LOW")

GPIO.add_event_detect("P9_12", GPIO.FALLING)
#your amazing code here
#detect wherever:
if GPIO.event_detected("P9_12"):
    print "event detected!"

GPIO.cleanup()
示例#53
0
                                    cam_frame_center[1] - face_center[1])
                    pan_servo.position = center_delta[0] * pos_to_angle[0]
                    tilt_servo.position = center_delta[1] * pos_to_angle[1]
                    last_found = time.time()
                else:
                    cv2.circle(frame, face_center, w, (0, 0, 255), 1)

            # Otherwise, zero the platform if we haven't seen any faces for
            # a specified number of seconds
            else:
                if time.time() - last_found > 5:
                    pan_servo.position = 0
                    tilt_servo.position = 0

            # If the button has been pressed
            if GPIO.event_detected(BUTTON_PIN):

                # Grab the current time for a timestamp in the filename
                # and generate the file path & name
                snap_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
                output_file = 'snaps/snap_{}.jpeg'.format(snap_time)
                jpeg_settings = [int(cv2.IMWRITE_JPEG_QUALITY), 90]

                # Write the frame to the file
                cv2.imwrite(output_file, frame, jpeg_settings)

            # Display the resulting frame
            cv2.imshow(window_name, frame)
            cv2.waitKey(1)

    except KeyboardInterrupt:
示例#54
0
GPIO.add_event_detect(BUTTON_4, GPIO.RISING)
GPIO.add_event_detect(BUTTON_CLR, GPIO.RISING)

size = 8
currentX = 0
currentY = 0
board = [[0 for col in range(size)] for row in range(size)]
board[currentX][currentY] = 1

board[currentX][currentY] = 1
display.set_pixel(currentX, currentY, 1)
display.write_display()

pos1_0 = eQEP1.get_position()
pos2_0 = eQEP2.get_position()

while (True):
    posX = currentX + (-(eQEP1.get_position() - pos1_0)/4)
    posY = currentY + (-(eQEP2.get_position() - pos2_0)/4)
    print posX, posY
    if ( posX >= 0 and posX < size and posY >= 0 and posY < size):
        display.set_pixel(posX, posY, 1)
        display.write_display()
        #sleep(0.2)
	if GPIO.event_detected(BUTTON_CLR):
		display.clear();
		display.write_display()
		sleep(0.2)
			

示例#55
0
def main():

	# Pinout Variables
	pAccelerationUp = "P8_14"
	pAccelerationDown = "P8_15"
	pRegen = "P9_13"
	pLeft = "P9_26"
	pRight = "P9_24"
	pCruise = "P8_16"

	# Bluetooth Variables
	revC_addr = "00:19:0E:15:AD:EF"
	uuid =  "94f39d29-7d6d-437d-973b-fba39e49d4ee"
	send_data = " "

	# Global Variables
	global data	
	global cruiseSpeed
	global cruiseText
	global speedText
	global minimumSpeed
	global cruiseFlag
	global coastFlag
	global regenFlag
	global driver_log

	minimumSpeed = 0
	cruiseSpeed = 0
	desired_torque = 0

	#GPIO Variables
	GPIO.setup( pAccelerationUp, GPIO.IN ) #Acceleration Up
	GPIO.add_event_detect( pAccelerationUp, GPIO.BOTH )

	GPIO.setup( pAccelerationDown, GPIO.IN ) #Acceleration Down
        GPIO.add_event_detect( pAccelerationDown, GPIO.BOTH )

	GPIO.setup( pRegen, GPIO.IN )	# Regen
	GPIO.add_event_detect( pRegen, GPIO.BOTH )

	GPIO.setup( pLeft, GPIO.IN )	#Left
	GPIO.add_event_detect( pLeft, GPIO.BOTH )

	GPIO.setup( pRight, GPIO.IN )	#Right
	GPIO.add_event_detect( pRight, GPIO.BOTH )

	GPIO.setup( pCruise, GPIO.IN) # Cruise
	GPIO.add_event_detect( pCruise, GPIO.BOTH )

	# Connect to other BBB. Wait for connection to open.
	while True:
		service_matches = bluetooth.find_service( uuid = uuid, 
						  address = revC_addr 
						)
	
		if len(service_matches) == 0:
			print "Couldn't find other BBB"
	#		sys.exit(0)
		else:
			break
		# Wait and try to connect again
		t.sleep(1)

	first_match = service_matches[0]
	port = first_match["port"]
	name = first_match["name"]
	host = first_match["host"]

	print "Connecting to \"%s\" on %s" % (name, host)
	sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
	sock.connect((host, port))

	print "Connected."
	while True:

		# Regen
		if GPIO.event_detected( pRegen ):
#			print "Regen Change"
			if GPIO.input( pRegen ):
				regenEnable()
		
		#Set Left Turn Signal
		if GPIO.event_detected( pLeft ):
#                        print "Left Turn Signal"
                        if GPIO.input( pLeft ):
                                if data[1] == 0:
	        			data[1] = 1
					data[2] = 0
		                else:
        	                        data[1] = 0

		#Set Right Turn Signal
		if GPIO.event_detected( pRight ):
#                        print "Right Turn Signal"
                        if GPIO.input( pRight ):
 	                	if data[2] == 0:
					data[2] = 1
					data[1] = 0
				else:
                        		data[2] = 0

		# Set Cruise
		if GPIO.event_detected( pCruise ):
	                if GPIO.input( pCruise ):
				if not cruiseFlag:
					cruiseFlag = True
					cruiseSpeed = data[4]
				else:
					cruiseFlag = False		
#			cruiseFlag = not cruiseFlag
		
		if not cruiseFlag:
                        cruiseText.set( "Off")
                        cruiseSpeed = 0
#			speedText.set( str( data[4] ) + " mph" )
                else:
                        # Used to lock in speed
                        cruiseText.set( str( cruiseSpeed ) + " dA" )
#			speedText.set( str( cruiseSpeed ) + " mph" )
		
			

		# Set Acceleration. Throttle MUST be enabled.
		if data[9] == 1: 
			if GPIO.input( pAccelerationUp ):
				if data[4] < ( 500 + minimumSpeed) :
					data[4] = data[4] + 5
					if cruiseFlag:
						cruiseSpeed = cruiseSpeed + 5
			elif not cruiseFlag:
				if data[4] > 0:
					data[4] = data[4] - 5

			if ( cruiseFlag and GPIO.input( pAccelerationDown ) ):
#				speedText.set( str( cruiseSpeed ) + " mph" )
				if data[4] > 0:
					data[4] = data[4] -5
					cruiseSpeed = data[4]
		
		# Coast Select.
#		if data[10] == 1:
#			data[4] = 0
#			cruiseFlag = False

		if data[4] > 0:
			data[6] = 0
			data[10] = 0

		# Send data
		if len(data) == 0 : break
		send_data = ""

#		data[4] = str( hex( desired_torque ).split( 'x' )[1] )
#                if len(data[4] == 1):
#                        data[4] = "000" + data[4]
#                elif len(data[4] == 2):
#                        data[4] = "00" + data[4]
#                elif len(data[4] == 3):
#                        data[4] = "0" + data[4]

#                print data[4]
		for x in data:
			send_data += (str(x) + ",")
#		print "data to send %s" % data
#		print "send as %s" % send_data
#		print send_data

		sock.send(send_data)
		incoming = []
		incoming = sock.recv(1024).split(",")
		print incoming

		# Update UI based on info received	
		data[11] = incoming[11]
		data[12] = incoming[12]
		data[13] = incoming[13]
	
		data[14] = incoming[14]

		t.sleep(0.1)

	# Close GPIO and BT communication on exit
	GPIO.cleanup()
	sock.close()
示例#56
0
GPIO.output(EnB, GPIO.HIGH)
 
 
def call(unused):
    time.sleep(0.1)
    print ("Button pressed")
    if GPIO.input(Bt):
        #print "start"
        GPIO.output(EnA, GPIO.HIGH)
        GPIO.output(EnB, GPIO.HIGH)
    else:
        #print "stop"
        GPIO.output(EnA, GPIO.LOW)
        GPIO.output(EnB, GPIO.LOW)
 
GPIO.event_detected(Bt)
 
def testP():
    GPIO.output(ln1, GPIO.HIGH)
    GPIO.output(ln2, GPIO.LOW)
    GPIO.output(ln3, GPIO.HIGH)
    GPIO.output(ln4, GPIO.LOW)
    for x in range(0, 8):
        GPIO.output(EnA, GPIO.HIGH)
        GPIO.output(EnB, GPIO.HIGH)
        time.sleep(15)
 
 
def testH():
    while(1):
        GPIO.output(ln1, GPIO.HIGH)
示例#57
0
print_echo("Listening CLP - Keep-alive bit: " + str(GPIO.input("P8_16")))

delay_test = 10
backup = pygame.display.get_surface().copy()
screen_saver = 0
try:
	#__PERMANENT_LOOP
	t_browser = time.time()
	t_ping = time.time()
	t_test = time.time()
	t_msg = time.time()
	t_screen_saver = time.time()
	while True:
		client.loop(timeout=0.2)
		if GPIO.event_detected("P8_16"):
			clp_keep_alive()
			t_browser = time.time()
			t_msg = t_browser
			t_screen_saver = t_browser
		if GPIO.event_detected("P8_14"):
			new_msg()
			t_browser = time.time()
			t_msg = t_browser
			t_screen_saver = t_browser
		if time.time() - t_ping >= delay_ping:
			#print_echo("Inside Ping")
			t_ping = time.time()
			output, error = subprocess.Popen(["ping","-c 2","-W 0.2","-w 2",hostname],stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()
			#print_echo("After subprocess")
			#output, error = subprocess.Popen("ping -c 2 -W 0.2 "+hostname,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()