Example #1
0
 def test_switchbounce(self):
     self.switchcount = 0
     print "\nSwitch bounce test.  Press switch at least 10 times and count..."
     GPIO.add_event_detect(SWITCH_PIN, GPIO.FALLING, callback=self.cb, bouncetime=200)
     while self.switchcount < 10:
         time.sleep(1)
     GPIO.remove_event_detect(SWITCH_PIN)
def initSiren():
	GPIO.remove_event_detect(PORT_PIR01)
	GPIO.remove_event_detect(PORT_PIR02)
	#Give a warning siren
	sirenWarn()
	print "Wait 5 seconds"
	sleep(5)
	#Check if still armed
	if isArmed() is False:
		print "Siren sequence stopped"
		GPIO.add_event_detect(PORT_PIR01,GPIO.FALLING, callback=isrPIR01 , bouncetime=200)
		GPIO.add_event_detect(PORT_PIR02,GPIO.FALLING, callback=isrPIR02 , bouncetime=200)
		return
	else:
		print "Siren still armed"
	sirenWarn()
	sleep(10)
	#Check if still armed
	if isArmed() is False:
		print "Siren sequence stopped"
		GPIO.add_event_detect(PORT_PIR01,GPIO.FALLING, callback=isrPIR01 , bouncetime=200)
		GPIO.add_event_detect(PORT_PIR02,GPIO.FALLING, callback=isrPIR02 , bouncetime=200)
		return
	else:
		print "Siren still armed"
	sirenActivate()
	GPIO.add_event_detect(PORT_PIR01,GPIO.FALLING, callback=isrPIR01 , bouncetime=200)
	GPIO.add_event_detect(PORT_PIR02,GPIO.FALLING, callback=isrPIR02 , bouncetime=200)
def buttonPressed(channel):
    """Callback called when GPIO detects button is pressed"""
    global pressedUpTime
    pressedDuration = time.time() - pressedUpTime
    #software switch deboucing
    if pressedDuration <= MIN_DELAY_TIME:
        return
    else:
        #if button is pressed
        if VERBOSE:
            print("Button Depressed")
        #check that this is not the first time
        if pressedUpTime != 0:
            #use gap to determine if new morse character, new letter, or new word.
            gapDuration = time.time() - pressedUpTime
            #get gap
            gap = detectGap(gapDuration)
            addToResult(gap)
            if VERBOSE:
                print(morseToString(gap))
        global pressedDownTime
        pressedDownTime = time.time()
        #reset event detection
        GPIO.remove_event_detect(23)
        GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(23, GPIO.RISING, callback=buttonReleased)
Example #4
0
def stop_count():
    try:
        GPIO.remove_event_detect(pedal)
    except Exception:
        pass
    GPIO.output(red, True)
    GPIO.output(green, False)
Example #5
0
def Measure():
    start = 0
    GPIO.output(TRIGGER, True)
    time.sleep(0.00001)
    GPIO.output(TRIGGER, False)

    channel = GPIO.wait_for_edge(ECHO, GPIO.BOTH, timeout=200)
    if channel is None:
        print("Ultrasonic sensor timed out (pre-echo).")
        GPIO.remove_event_detect(ECHO)
        restart()
    # else:
        # print("Echo start detected")
    start = time.time()
          
    GPIO.wait_for_edge(ECHO, GPIO.BOTH,  timeout=400)
    if channel is None:
        print("Ultrasonic sensor timed out (post-echo).")
        GPIO.remove_event_detect(ECHO)
        restart()
    # else:
        # print("Echo finish detected")
    stop = time.time()
   
    elapsed = stop-start
    distance = (elapsed * 34300)/2 # Using speed of sound at 20C (68F)

    return distance
Example #6
0
def playTimerFired(data):
    if data.time <= 0:
        data.mode = "Entering Score"
        GPIO.remove_event_detect(channel)
        data.time = data.temporalLength
    else:
        data.time -= 1
Example #7
0
def sendBitmap (channel):
    global cur
    sendRow(cur)
    cur += 1
    if cur >= hROW:
        GPIO.remove_event_detect(PIN)
        cur = 0
Example #8
0
def test_falling():
    def cb(chan):
        print('Callback called - channel %s'%chan)
        
    print('Falling edge test')

    try:
        GPIO.add_event_detect(SWITCH_PIN, GPIO.LOW)
        print('Fail- managed to set LOW as an event')
    except ValueError:
        pass

    print('5 second sample for event_detected function')
    GPIO.add_event_detect(SWITCH_PIN, GPIO.FALLING)
    time.sleep(5)
    if GPIO.event_detected(SWITCH_PIN):
        print('Event detected')
    else:
        print('Event not detected')
    print('5 seconds for callback function')
    input('Press return to start: ')
    GPIO.remove_event_detect(SWITCH_PIN);
    GPIO.add_event_detect(SWITCH_PIN, GPIO.FALLING, callback=cb)
    time.sleep(5)
    GPIO.remove_event_detect(SWITCH_PIN);

    try:
        GPIO.wait_for_edge(SWITCH_PIN, GPIO.LOW)
        print('Fail- managed to wait for a LOW as an event')
    except ValueError:
        pass

    print('Blocking wait for falling edge...')
    GPIO.wait_for_edge(SWITCH_PIN, GPIO.FALLING)
def read_message():
    global inputStr
    global inputframe
    #setup reading state
    GPIO.setup(Thandshakein, GPIO.IN)
    GPIO.remove_event_detect(Thandshakein)
    #GPIO.add_event_detect(Thandshakein, GPIO.BOTH, callback=read_bit, bouncetime=100)
    #GPIO.remove_event_detect(Thandshakeout)
    GPIO.setup(Thandshakeout, GPIO.OUT)

    for x in range(0, 32):
        inputframe.write(False)
    
    isSending = False
    sender = senderID.read(np.uint8, 1)
    print('Sender is: ')
    print(sender)
    reciever = recieverID.read(np.uint8, 1)
    print('Reciever is: ')
    print(reciever)
    while((len(inputframe) // 8) != 0):
        inputStr = inputStr + inputframe.read(str, 1)
    print("inputStr is: ")
    print(inputStr)
    parse_message(sender, reciever, inputStr)
Example #10
0
    def switch_to_port(self, portNum):
        if not self.hasGpio:
            return

        try: #Make sure we arn't still trying to detect events
            GPIO.remove_event_detect(self.hdmiInPin1)
        except:
            pass

        try: #Make sure we arn't still trying to detect events
            GPIO.remove_event_detect(self.hdmiInPin2)
        except:
            pass

        if portNum >= 1 and portNum <= 3:
            #the appropriate stoping condition depending on the port num
            pinCountCondition = self.allPinCountConditons[portNum-1]

            if portNum == 1:
                #stop switching when it goes from port 2 to 1. 
                GPIO.add_event_detect(self.hdmiInPin1, GPIO.FALLING, callback= self.stop_switching)
            elif portNum == 2:
                #stop switching when it goes to port 2. 
                GPIO.add_event_detect(self.hdmiInPin1, GPIO.RISING, callback= self.stop_switching)
            else:
                #stop switching when it goes to port 3. 
                GPIO.add_event_detect(self.hdmiInPin2, GPIO.RISING, callback= self.stop_switching)

        self.keep_switching()
Example #11
0
def waitButton(boton):
    
    global pulsacionCorta
    global pulsacionLarga
    global pulsacionOff

    print "Waiting..."
    time.sleep(3)
    GPIO.output(ledRojo,False)
    GPIO.output(ledVerde,True)
    
    GPIO.remove_event_detect(boton)
    GPIO.wait_for_edge(boton, GPIO.BOTH)
    stamp = time.time()
    GPIO.remove_event_detect(boton)
    GPIO.wait_for_edge(boton, GPIO.BOTH)
    now = time.time()
    if now-stamp > 3:
        print "Pulsacion muy larga"
        pulsacionCorta=False
        pulsacionLarga=False
        pulsacionOff=True

    elif now-stamp > 1:
        print "Pulsacion larga"
        pulsacionCorta=False
        pulsacionLarga=True
        pulsacionOff=False

    else:
        print "Pulsacion corta"
        pulsacionCorta=True
        pulsacionLarga=False
        pulsacionOff=False
def thread_crossing(button, lights):
    
    def my_callback(channel):
        print("start")
        traffic_sequence(lights)
        print("end")
    
    GPIO.setup(button, GPIO.IN)

    for pin in lights:
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.LOW)
        
    print("push button {}".format(button))

    #initial state
    GPIO.output(lights.cg, GPIO.HIGH)
    GPIO.output(lights.pr, GPIO.HIGH)

    GPIO.add_event_detect(button, GPIO.FALLING, callback=my_callback)
    print("main-thread goes to sleep")
    time.sleep(20)

    print("Finished")

    GPIO.remove_event_detect(button)

    for pin in lights:
        GPIO.output(pin, GPIO.LOW)
Example #13
0
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 play(self):
     #turn on all leds
     xmasTree.leds_on(ALL)
     #wait a bit
     sleep(2)
     #get a random number, which will be how many leds will be lit before the green one
     steps = randint(7,14)
     for step in range(0,steps):
         #light a random red led
         ledToLight = LEDS[randint(1,6)]
         xmasTree.leds_on(ledToLight)
         #wait for a random time between 0.5 and 1 second
         timeToSleep = randint(5,10) / 10.0
         sleep(timeToSleep)
     #setup event detection
     self.player1ButtonPressed = False
     self.player2ButtonPressed = False
     GPIO.add_event_detect(P1GAMEBUTTONPIN, GPIO.RISING, callback=self._playerButtonCallback, bouncetime=200)
     GPIO.add_event_detect(P2GAMEBUTTONPIN, GPIO.RISING, callback=self._playerButtonCallback, bouncetime=200)
     #light the green led
     xmasTree.leds_on(L0)
     #wait for a button to be pressed
     while not self.player1ButtonPressed and not self.player2ButtonPressed:
         sleep(0.001)
     #remove event detection
     GPIO.remove_event_detect(P1GAMEBUTTONPIN)
     GPIO.remove_event_detect(P2GAMEBUTTONPIN)
     #who won? display right (1P) or left (2P) led 
     if self.player1ButtonPressed: ledToLight = L3
     if self.player2ButtonPressed: ledToLight = L1
     self._displayWinner(ledToLight)
Example #15
0
    def __init__(self, robot):
        # TODO add a singleton method to avoid errors ??
        # Make a meta event list to avoid messing around with the raw events list
        # make some method to create callbacks or multiple call backs
        # have them executed in a separate thread ?
        # self.pg = rpigpio
        self.debug = False
        self.robot = robot

        # Setup
        if self.robot._board.PGType == 1:
            self.channel = Board.SWITCH
        elif self.robot._board.PGType == 2:
            self.channel = Board.LSWITCH
            #set switch as input with pullup
        GPIO.setup(self.channel, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        self.events = []
        self.double_click = False
        GPIO.remove_event_detect(self.channel)
        GPIO.add_event_detect(self.channel, GPIO.BOTH, callback=self._callback)

        self.click_callback = None
        self.double_click_callback = None
        self.long_click_callback = None
        self.while_long_click_callback = None
def buttonReleased(channel):
    """Callback called when GPIO detects button is released"""
    global pressedDownTime
    pressedDuration = time.time() - pressedDownTime
    #software switch debouncing
    if pressedDuration <= MIN_KEY_TIME:
        return
    else:
        #if button is actually released
        if VERBOSE:
            print("Button Released")
        global pressedUpTime
        pressedUpTime = time.time()
        #reset event detection
        GPIO.remove_event_detect(23)
        GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(23, GPIO.FALLING, callback=buttonPressed)
        #get the character
        morseChar = detectCharacter(pressedDuration)
        addToResult(morseChar)
        if VERBOSE:
            print(morseToString(morseChar))
        #record the last few durations
        global pressedDurations
        if len(pressedDurations) >= LEARNING_CYCLE:
            #remove last item
            del pressedDurations[(len(pressedDurations)-1)]
        pressedDurations.append(pressedDuration)
        if VERBOSE:
            print(pressedDuration)
Example #17
0
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)
Example #18
0
  def disable(self, *args, **kwargs):
    """ Stop listening to events """

    if self.is_enabled:
      self.led_off()
      gpio.remove_event_detect(self.gpio_pin)
      self.is_enabled = False
	def setup_gpio(self):
		try:
			GPIO.remove_event_detect(self.PIN_FILAMENT)
		except:
			pass
		if self.PIN_FILAMENT != -1:
			GPIO.add_event_detect(self.PIN_FILAMENT, GPIO.FALLING, callback=self.check_gpio, bouncetime=self.BOUNCE) 
Example #20
0
def cleanup():
    """ Function to cleanup raspberry pi GPIO at end of code """

    # Restore GPIO to default state
    GPIO.remove_event_detect(15) #Add to end of function
    GPIO.cleanup()
    print("GPIO cleaned!")
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)
Example #22
0
def signal_handler(signal, frame):
    global run
    print "Ending and cleaning up"
    GPIO.remove_event_detect(14)
    GPIO.cleanup()
    client.disconnect()
    run = False
Example #23
0
    def stopArm(self):
        print '\tVideoThread stopArm()'
        timestamp = self.GetTimestamp()
        if self.isArmed == 1:
            self.isArmed = 0
            
            #print '\tclosing camera'
            #self.camera.stop_recording()
            #self.camera.close()
            
            # camera is now initialized in __init__
            #print '\tdeleting self.stream'
            #del self.stream
            
            if self.usePins:
                print '\tVideoThread is releasing GPIO'
                GPIO.remove_event_detect(self.scanimageStartPin)
                GPIO.remove_event_detect(self.scanimageFramePin)
        
            self.logfileWrite(timestamp, 'VideoThreadStopArm')

            self.logFileName = ''
            self.scanImageFrame = 0
            
            print '\tVideoThread stopArm() is done'
Example #24
0
def switch_event_prev(p):
	GPIO.remove_event_detect(p)
#	print "unu"
        global text_line1, text_line2, text_line1_old, text_line2_old
	global current, warp
        global MERGE, radio
	global time_stamp
	time_now = time.time()
#	print time_now-time_stamp
	if (time_now - time_stamp) >= 0.8: 
	        if MERGE ==1:
      		        exec_cmd ('echo "prev"|netcat 127.0.0.1 4222')
	#		print current
		        temp = current -3
		        current = (temp%warp)+4
			index = 4+warp-current
			text_line2=str(radio[index-1][1])
			lcd.line2(text_line2)
	#	        print current
		        station = open('station','w')
		        station.write(str(current))
		        station.close()

	time_stamp = time_now+0.3	
	GPIO.add_event_detect(p, GPIO.RISING, callback=switch_event_prev, bouncetime=500)
        return
Example #25
0
	def __exit__(self, exc_type, exc_value, traceback):
		if self._t1:
			self._stop = True
			self._t1.join()
		if self._mode == 'event':
			GPIO.remove_event_detect(self._channel)
		GPIO.cleanup()
Example #26
0
 def rising(self, channel): 
     gpio.remove_event_detect(23) 
     print 'Button up' 
     gpio.add_event_detect(23, gpio.FALLING, callback=self.falling, bouncetime=10) 
     #TODO: dim red LED
     self.recfile.stop_recording() 
     self.recfile.close() 
Example #27
0
def rotate_callback(channel):
    """
    callback function for the input pin interrupt
    implemented according to the documentation:
    http://www.produktinfo.conrad.com/datenblaetter/700000-724999/705594-da-01-ml-Drehimpulsgeber_stehend_de_en.pdf
    had to place it in a global function, because i had AttributeErrors when
    implemented in a class
    TODO: lock necessary? hm...
    """
    global ROTARY_A_PIN
    global ROTARY_B_PIN
    global SET_COUNT
    global ROTARY_EVENT

    GPIO.remove_event_detect(channel)  # disconnect the interrupt
    a = GPIO.input(channel)
    b = GPIO.input(ROTARY_B_PIN)
    if a == b:
        SET_COUNT -= 1
        CW()
    else:
        SET_COUNT += 1
        CCW()
    # switch the interrupt from rising to falling edge and vice versa
    ROTARY_EVENT = GPIO.FALLING if ROTARY_EVENT == GPIO.RISING else GPIO.RISING
    GPIO.add_event_detect(channel, ROTARY_EVENT, callback=rotate_callback, bouncetime=BOUNCETIME)
def lowBattery(channel):
  #Checking for LED bounce for the duration of the battery Timeout
  for bounceSample in range(1, int(round(batteryTimeout / sampleRate))):
    time.sleep(sampleRate)

    if GPIO.input(batteryGPIO) is 1:
       break
  
  global playerFlag   
  while playerFlag is 1:
    time.sleep(1)
     
  #If the LED is a solid condition, there will be no bounce.  Launch shutdown video and then gracefully shutdown
  if bounceSample is int(round(batteryTimeout / sampleRate)) - 1:
    playerFlag = 1
    os.system("/usr/bin/omxplayer --no-osd --layer 999999 " + shutdownVideo + " --alpha 180;sudo shutdown -h now");
    playerFlag = 0
    sys.exit(0)

  #If the LED is a solid for more than 10% of the timeout, we know that the battery is getting low.  Launch the Low Battery alert. 
  if bounceSample > int(round(batteryTimeout / sampleRate * 0.1)):
    playerFlag = 1
    os.system("/usr/bin/omxplayer --no-osd --layer 999999 " + lowalertVideo + " --alpha 160;");
    playerFlag = 0
    
    #Discovered a bug with the Python GPIO library and threaded events.  Need to unbind and rebind after a System Call or the program will crash
    GPIO.remove_event_detect(batteryGPIO)
    GPIO.add_event_detect(batteryGPIO, GPIO.BOTH, callback=lowBattery, bouncetime=300)
    
    #If we know the battery is low, we aggresively monitor the level to ensure we shutdown once the Power Timeout is exceeded.
    lowBattery(batteryGPIO)
Example #29
0
def row_changed(row):
    global rows
    GPIO.remove_event_detect(row)
    GPIO.setup(row, GPIO.OUT)

    for column in rows[row]:
        GPIO.setup(column, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    # Send signal from row to columns
    GPIO.output(row, 1)
    # sleep(0.05)

    # Read which column it was
    for column in rows[row]:
        columnValue = GPIO.input(column)

        if columnValue:
            key = keys[str(row) + "," + str(column)]
            logging.info("row changed: " + str(row))
            send_key(key)

    # Set row and columns back to original setup
    GPIO.setup(row, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    for column in rows[row]:
        GPIO.remove_event_detect(column)
        GPIO.setup(column, GPIO.OUT)
        GPIO.output(column, 1)

    GPIO.add_event_detect(row, GPIO.RISING, callback=row_changed)
Example #30
0
    def _wait_state(self):
        """Wait state."""
        _log.debug('Entering wait state.')

        gpio.wait_for_edge(self._sensor, gpio.RISING)
        gpio.remove_event_detect(self._sensor)
        self._state = self._photograph_state
Example #31
0
    def testAddEventCallback(self):
        def cb(channel):
            self.callback_count += 1

        # falling test
        self.callback_count = 0
        GPIO.output(LOOP_OUT, GPIO.HIGH)
        GPIO.add_event_detect(LOOP_IN, GPIO.FALLING)
        GPIO.add_event_callback(LOOP_IN, cb)
        time.sleep(0.01)
        for i in range(2048):
            GPIO.output(LOOP_OUT, GPIO.LOW)
            time.sleep(0.001)
            GPIO.output(LOOP_OUT, GPIO.HIGH)
            time.sleep(0.001)
        GPIO.remove_event_detect(LOOP_IN)
        self.assertEqual(self.callback_count, 2048)

        # rising test
        self.callback_count = 0
        GPIO.output(LOOP_OUT, GPIO.LOW)
        GPIO.add_event_detect(LOOP_IN, GPIO.RISING, callback=cb)
        time.sleep(0.01)
        for i in range(2048):
            GPIO.output(LOOP_OUT, GPIO.HIGH)
            time.sleep(0.001)
            GPIO.output(LOOP_OUT, GPIO.LOW)
            time.sleep(0.001)
        GPIO.remove_event_detect(LOOP_IN)
        self.assertEqual(self.callback_count, 2048)

        # both test
        self.callback_count = 0
        GPIO.output(LOOP_OUT, GPIO.LOW)
        GPIO.add_event_detect(LOOP_IN, GPIO.BOTH, callback=cb)
        time.sleep(0.01)
        for i in range(2048):
            GPIO.output(LOOP_OUT, GPIO.HIGH)
            time.sleep(0.001)
            GPIO.output(LOOP_OUT, GPIO.LOW)
            time.sleep(0.001)
        GPIO.remove_event_detect(LOOP_IN)
        self.assertEqual(self.callback_count, 4096)
Example #32
0
def button_pin_sequence(correct_pin, line=LCD_module_420.LCD_LINE_3):
	input_pin_code = ''
	new_char = ''
	CORR_PIN_LEN = len(correct_pin)
	#Add events to buttons.
	GPIO.add_event_detect(A_BUTTON, GPIO.RISING, bouncetime=200)
	GPIO.add_event_detect(B_BUTTON, GPIO.RISING, bouncetime=200)
	GPIO.add_event_detect(C_BUTTON, GPIO.RISING, bouncetime=200)

	LCD_module_420.LCD_text('PIN:  ', line)
	#This is very ugly and I'm sorry
	while input_pin_code != correct_pin:
		sleep(.1)		
		a, b, c = GPIO.event_detected(A_BUTTON), GPIO.event_detected(B_BUTTON), GPIO.event_detected(C_BUTTON)
		new_char =''
		#If any events detected, add the the assigned char to string
		if a:
			new_char = '1'
		elif b:
			new_char = '2'
		elif c:
			new_char = '3'

		if a or b or c:
			input_pin_code += new_char

			if len(input_pin_code) > CORR_PIN_LEN:
				#input is longer than correct pin, reset!
				#Flash red light
				Thread(target=blink_RED_LED).start()
				input_pin_code = ''
				new_char = ''
				LCD_module_420.LCD_text('PIN:  ', line)

			else:
				#Mask all string except for new char to ***, like you would see on a password field in a phone.
				LCD_module_420.LCD_text('PIN:  ' + '*'*(len(input_pin_code)-1) + new_char, line)

	LCD_module_420.LCD_text('PIN:  ' + '*'*CORR_PIN_LEN, line)
	GPIO.remove_event_detect(A_BUTTON)
	GPIO.remove_event_detect(B_BUTTON)
	GPIO.remove_event_detect(C_BUTTON)
Example #33
0
	def runUntill(self,limitSwitchPos):
		#private methode

		#class all event
		GPIO.remove_event_detect(self.LMUP)
		GPIO.remove_event_detect(self.LMDOWN)
                GPIO.remove_event_detect(self.LMCENTER)

		#fire only disired event
		if limitSwitchPos == self.LMUP:
                        GPIO.add_event_detect(self.LMUP,GPIO.FALLING,callback=self.stopAndClear,bouncetime=300)

		elif limitSwitchPos == self.LMDOWN:
                        GPIO.add_event_detect(self.LMDOWN,GPIO.FALLING,callback=self.stopAndClear,bouncetime=300)

		elif limitSwitchPos == self.LMCENTER:
        	        GPIO.add_event_detect(self.LMCENTER,GPIO.FALLING,callback=self.stopAndClear,bouncetime=300)

		else :
			pass # TO DO :must throw error rowng pin thers no limit switch at limitswitchpos
 def pushbutton(self):
     if GPIOcontrol:
         while mutestopbutton:
             time.sleep(.1)
             if GPIO.event_detected(stoppushbutton):
                 GPIO.remove_event_detect(stoppushbutton)
                 now = time.time()
                 count = 1
                 while time.time() < now + 1:
                     if GPIO.event_detected(stoppushbutton):
                         count += 1
                         time.sleep(.25)
                 if count == 2:
                     self.buttonSinglePress()
                     GPIO.remove_event_detect(stoppushbutton)
                     GPIO.add_event_detect(stoppushbutton, GPIO.FALLING)
                 elif count == 3:
                     self.buttonTriplePress()
                     GPIO.remove_event_detect(stoppushbutton)
                     GPIO.add_event_detect(stoppushbutton, GPIO.FALLING)
Example #35
0
            cnt += 1
            last_time = time.time()


def interval_proc():
    while True:
        print("sleep start")
        time.sleep(10)
        print("sleep end")


if __name__ == '__main__':
    try:
        print("処理キャンセル:CTRL+C")
        init_gpio()
        set_event()
        interval_proc()
    except KeyboardInterrupt:
        print("終了処理中...")
        GPIO.remove_event_detect(SENSOR_PIN)
        GPIO.cleanup()
        print("GPIO clean完了")
# 終了処理
# KeyboardInterrupt側に持たせたので不要
"""
finally:
    GPIO.cleanup()
    print("finally GPIO clean完了")
"""
Example #36
0
def onExit():
    print('Play-Control exiting')
    GPIO.remove_event_detect(PLAY_GPIO)
    GPIO.remove_event_detect(NEXT_GPIO)
    GPIO.remove_event_detect(PREV_GPIO)
    GPIO.cleanup(channels)
Example #37
0
def removeInterrupts():
    GPIO.remove_event_detect(
        20
    )  #, GPIO.BOTH, callback=lambda x :detection(podLen,'spice',20,60),bouncetime=300)
    GPIO.remove_event_detect(
        16
    )  #, GPIO.BOTH, callback=lambda x :detection(podLen,'spice',16,120),bouncetime=300)
    GPIO.remove_event_detect(
        12
    )  #, GPIO.BOTH, callback=lambda x :detection(podLen,'spice',12,180),bouncetime=300)
    GPIO.remove_event_detect(
        25
    )  #, GPIO.BOTH, callback=lambda x :detection(podLen,'spice',25,240),bouncetime=300)
    GPIO.remove_event_detect(
        24
    )  #, GPIO.BOTH, callback=lambda x :detection(podLen,'spice',24,300),bouncetime=300)
    GPIO.remove_event_detect(
        23
    )  #, GPIO.BOTH, callback=lambda x :detection(podLen,'spice',23,360),bouncetime=300)
Example #38
0
GPIO.setmode(GPIO.BCM)
# GPIO.wait_for_edge(testpin, GPIO.BOTH_EDGE, 2000, 66660)
# print("pass1")
# GPIO.wait_for_edge(testpin, GPIO.BOTH_EDGE, 2000, 66660)
# print("pass2")

GPIO.setup(18, GPIO.OUT, GPIO.PUD_OFF, 0)
GPIO.setup(25, GPIO.IN, GPIO.PUD_OFF)
GPIO.add_event_detect(testpin, GPIO.RISING, callback_one, 1)

print("ADD CALLBACK ONE")

input()

print("Event detected:", GPIO.event_detected(testpin))

print("ADD CALLBACK TWO")
GPIO.add_event_callback(testpin, callback_two)

input()

print("REMOVE EVENT DETECTION")

GPIO.remove_event_detect(25)

input()

print("ALL DONE")

GPIO.cleanup()
Example #39
0
 def disable_interrupt(self):
     """
     Disable radio chip hardware interrupt
     """
     if (gpio_enabled):
         GPIO.remove_event_detect(self.gpio_nirq)