Package rstem :: Module button
[hide private]
[frames] | no frames]

Source Code for Module rstem.button

 1  # 
 2  # Copyright (c) 2014, Scott Silver Labs, LLC. 
 3  # 
 4  # Licensed under the Apache License, Version 2.0 (the "License"); 
 5  # you may not use this file except in compliance with the License. 
 6  # You may obtain a copy of the License at 
 7  # 
 8  #       http://www.apache.org/licenses/LICENSE-2.0 
 9  # 
10  # Unless required by applicable law or agreed to in writing, software 
11  # distributed under the License is distributed on an "AS IS" BASIS, 
12  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
13  # See the License for the specific language governing permissions and 
14  # limitations under the License. 
15  # 
16   
17  from rstem import gpio 
18   
19   
20  PRESSED = gpio.FALLING 
21  RELEASED = gpio.RISING 
22  BOTH = gpio.BOTH 
23   
24  A = 4 
25  B = 17 
26  UP = 25 
27  DOWN = 24 
28  LEFT = 23 
29  RIGHT = 18 
30  START = 27 
31  SELECT = 22 
32   
33   
34 -class Button(object):
35 """ A button from a GPIO port""" 36
37 - def __init__(self, port):
38 """ 39 @param port: GPIO number (BCM mode) that button is plugged into 40 @type port: int 41 """ 42 self.port = port 43 self.gpio = gpio.Pin(port) 44 self.gpio.configure(gpio.INPUT)
45
46 - def is_pressed(self):
47 """@returns: True if button is pressed""" 48 return not bool(self.gpio.get_level())
49
50 - def was_clicked(self):
51 return self.gpio.was_clicked()
52
53 - def _verify_change_value(change):
54 if change not in [PRESSED, RELEASED, BOTH]: 55 raise ValueError("Invalid change")
56
57 - def call_on_change(self, event_callback, change=PRESSED, bouncetime=300):
58 """Calls given event_callback function when button changes state (example pressed). 59 60 @param event_callback: function to call when button changes state 61 @type event_callback: function 62 @param change: type of event to watch for (either button.PRESSED, button.RELEASED, or button.BOTH) 63 @param bouncetime: msec to debounce button 64 @type bouncetime: int8 65 66 @warning: Function must have the first argument be the port number 67 """ 68 Button._verify_change_value(change) 69 self.gpio.edge_detect(change, event_callback, bouncetime)
70
71 - def remove_call_on_change(self):
72 """Removes the callback function set for this button. 73 Does nothing if no callback function is set 74 """ 75 self.gpio.remove_edge_detect()
76
77 - def wait_for_change(self, change=PRESSED):
78 """Blocks until given change event happens 79 80 @param change: type of event to watch for (either button.PRESSED, button.RELEASED, or button.BOTH) 81 """ 82 Button._verify_change_value(change) 83 self.gpio.wait_for_edge(change)
84