0
# Input Devices
1
2
GPIO input devices for sensors, buttons, and analog input components. All input devices support event-driven programming and can be used as sources for other devices through the source/values chaining system.
3
4
## Base Classes
5
6
### InputDevice
7
8
Base class for all GPIO input devices with pull-up/pull-down configuration.
9
10
```python { .api }
11
class InputDevice(GPIODevice):
12
def __init__(self, pin=None, *, pull_up=False, active_state=None, pin_factory=None):
13
"""
14
Generic GPIO input device.
15
16
Parameters:
17
- pin: int or str - GPIO pin number or name
18
- pull_up: bool or None - True for pull-up, False for pull-down, None for floating
19
- active_state: bool or None - True if HIGH is active, False if LOW is active (required when pull_up=None)
20
- pin_factory: Factory or None - Pin factory for advanced usage
21
"""
22
23
@property
24
def pull_up(self) -> bool | None:
25
"""Returns True if using pull-up resistor, False for pull-down, None for floating."""
26
27
@property
28
def is_active(self) -> bool:
29
"""Returns True if device is currently active."""
30
31
@property
32
def value(self) -> float:
33
"""Returns current value (0.0 for inactive, 1.0 for active)."""
34
```
35
36
### DigitalInputDevice
37
38
Base class for digital input devices with event handling and debouncing.
39
40
```python { .api }
41
class DigitalInputDevice(EventsMixin, InputDevice):
42
def __init__(self, pin=None, *, pull_up=False, active_state=None, bounce_time=None, pin_factory=None):
43
"""
44
Digital input device with event handling.
45
46
Parameters:
47
- pin: int or str - GPIO pin number or name
48
- pull_up: bool or None - Pull resistor configuration
49
- active_state: bool or None - Active state definition
50
- bounce_time: float or None - Debounce time in seconds
51
- pin_factory: Factory or None - Pin factory for advanced usage
52
"""
53
54
@property
55
def when_activated(self) -> callable:
56
"""Callback function called when device becomes active."""
57
58
@when_activated.setter
59
def when_activated(self, value: callable): ...
60
61
@property
62
def when_deactivated(self) -> callable:
63
"""Callback function called when device becomes inactive."""
64
65
@when_deactivated.setter
66
def when_deactivated(self, value: callable): ...
67
68
def wait_for_active(self, timeout: float = None) -> bool:
69
"""Wait for device to become active. Returns True if activated, False if timeout."""
70
71
def wait_for_inactive(self, timeout: float = None) -> bool:
72
"""Wait for device to become inactive. Returns True if deactivated, False if timeout."""
73
```
74
75
### SmoothedInputDevice
76
77
Base class for input devices requiring smoothed readings (analog sensors).
78
79
```python { .api }
80
class SmoothedInputDevice(InputDevice):
81
def __init__(self, pin=None, *, pull_up=False, active_state=None, threshold=0.5, queue_len=5, sample_rate=100, partial=False, pin_factory=None):
82
"""
83
Input device with value smoothing.
84
85
Parameters:
86
- pin: int or str - GPIO pin number or name
87
- pull_up: bool or None - Pull resistor configuration
88
- active_state: bool or None - Active state definition
89
- threshold: float - Activation threshold (0.0-1.0)
90
- queue_len: int - Number of samples for smoothing
91
- sample_rate: float - Sampling frequency in Hz
92
- partial: bool - If True, return values before queue is full
93
- pin_factory: Factory or None - Pin factory for advanced usage
94
"""
95
96
@property
97
def threshold(self) -> float:
98
"""Activation threshold value (0.0-1.0)."""
99
100
@threshold.setter
101
def threshold(self, value: float): ...
102
103
@property
104
def partial(self) -> bool:
105
"""If True, returns values before queue is full."""
106
```
107
108
## Specific Input Devices
109
110
### Button
111
112
Push button with hold detection and event handling.
113
114
```python { .api }
115
class Button(DigitalInputDevice, HoldMixin):
116
def __init__(self, pin=None, *, pull_up=True, bounce_time=None, hold_time=1, hold_repeat=False, pin_factory=None):
117
"""
118
Push button input device.
119
120
Parameters:
121
- pin: int or str - GPIO pin number or name
122
- pull_up: bool - True for pull-up (default), False for pull-down
123
- bounce_time: float or None - Debounce time in seconds
124
- hold_time: float - Time in seconds before button is considered held
125
- hold_repeat: bool - If True, when_held fires repeatedly while held
126
- pin_factory: Factory or None - Pin factory for advanced usage
127
"""
128
129
@property
130
def is_pressed(self) -> bool:
131
"""Returns True if button is currently pressed."""
132
133
@property
134
def is_held(self) -> bool:
135
"""Returns True if button is currently held."""
136
137
@property
138
def when_pressed(self) -> callable:
139
"""Callback function called when button is pressed."""
140
141
@when_pressed.setter
142
def when_pressed(self, value: callable): ...
143
144
@property
145
def when_released(self) -> callable:
146
"""Callback function called when button is released."""
147
148
@when_released.setter
149
def when_released(self, value: callable): ...
150
151
@property
152
def when_held(self) -> callable:
153
"""Callback function called when button is held."""
154
155
@when_held.setter
156
def when_held(self, value: callable): ...
157
158
@property
159
def hold_time(self) -> float:
160
"""Time in seconds before button is considered held."""
161
162
@hold_time.setter
163
def hold_time(self, value: float): ...
164
165
@property
166
def hold_repeat(self) -> bool:
167
"""If True, when_held fires repeatedly while held."""
168
169
@hold_repeat.setter
170
def hold_repeat(self, value: bool): ...
171
172
def wait_for_press(self, timeout: float = None) -> bool:
173
"""Wait for button to be pressed."""
174
175
def wait_for_release(self, timeout: float = None) -> bool:
176
"""Wait for button to be released."""
177
```
178
179
### MotionSensor
180
181
Passive infrared (PIR) motion sensor.
182
183
```python { .api }
184
class MotionSensor(SmoothedInputDevice):
185
def __init__(self, pin=None, *, queue_len=1, sample_rate=10, threshold=0.5, partial=False, pin_factory=None):
186
"""
187
PIR motion sensor.
188
189
Parameters:
190
- pin: int or str - GPIO pin number or name
191
- queue_len: int - Number of samples for motion detection
192
- sample_rate: float - Sampling frequency in Hz
193
- threshold: float - Motion detection threshold (0.0-1.0)
194
- partial: bool - If True, return values before queue is full
195
- pin_factory: Factory or None - Pin factory for advanced usage
196
"""
197
198
@property
199
def motion_detected(self) -> bool:
200
"""Returns True if motion is currently detected."""
201
202
@property
203
def when_motion(self) -> callable:
204
"""Callback function called when motion is detected."""
205
206
@when_motion.setter
207
def when_motion(self, value: callable): ...
208
209
@property
210
def when_no_motion(self) -> callable:
211
"""Callback function called when motion stops."""
212
213
@when_no_motion.setter
214
def when_no_motion(self, value: callable): ...
215
216
def wait_for_motion(self, timeout: float = None) -> bool:
217
"""Wait for motion to be detected."""
218
219
def wait_for_no_motion(self, timeout: float = None) -> bool:
220
"""Wait for motion to stop."""
221
```
222
223
### LightSensor
224
225
Light dependent resistor (LDR) sensor.
226
227
```python { .api }
228
class LightSensor(SmoothedInputDevice):
229
def __init__(self, pin=None, *, queue_len=5, charge_time_limit=0.01, threshold=0.1, partial=False, pin_factory=None):
230
"""
231
Light dependent resistor sensor.
232
233
Parameters:
234
- pin: int or str - GPIO pin number or name
235
- queue_len: int - Number of samples for smoothing
236
- charge_time_limit: float - Maximum time to wait for capacitor charge
237
- threshold: float - Light detection threshold (0.0-1.0)
238
- partial: bool - If True, return values before queue is full
239
- pin_factory: Factory or None - Pin factory for advanced usage
240
"""
241
242
@property
243
def light_detected(self) -> bool:
244
"""Returns True if light level is above threshold."""
245
246
@property
247
def when_light(self) -> callable:
248
"""Callback function called when light is detected."""
249
250
@when_light.setter
251
def when_light(self, value: callable): ...
252
253
@property
254
def when_dark(self) -> callable:
255
"""Callback function called when it gets dark."""
256
257
@when_dark.setter
258
def when_dark(self, value: callable): ...
259
260
def wait_for_light(self, timeout: float = None) -> bool:
261
"""Wait for light to be detected."""
262
263
def wait_for_dark(self, timeout: float = None) -> bool:
264
"""Wait for darkness."""
265
```
266
267
### LineSensor
268
269
Line detection sensor (typically infrared).
270
271
```python { .api }
272
class LineSensor(SmoothedInputDevice):
273
def __init__(self, pin=None, *, queue_len=5, charge_time_limit=0.01, threshold=0.1, partial=False, pin_factory=None):
274
"""
275
Line detection sensor.
276
277
Parameters:
278
- pin: int or str - GPIO pin number or name
279
- queue_len: int - Number of samples for smoothing
280
- charge_time_limit: float - Maximum time to wait for capacitor charge
281
- threshold: float - Line detection threshold (0.0-1.0)
282
- partial: bool - If True, return values before queue is full
283
- pin_factory: Factory or None - Pin factory for advanced usage
284
"""
285
286
@property
287
def line_detected(self) -> bool:
288
"""Returns True if line is detected."""
289
290
@property
291
def when_line(self) -> callable:
292
"""Callback function called when line is detected."""
293
294
@when_line.setter
295
def when_line(self, value: callable): ...
296
297
@property
298
def when_no_line(self) -> callable:
299
"""Callback function called when line is lost."""
300
301
@when_no_line.setter
302
def when_no_line(self, value: callable): ...
303
304
def wait_for_line(self, timeout: float = None) -> bool:
305
"""Wait for line to be detected."""
306
307
def wait_for_no_line(self, timeout: float = None) -> bool:
308
"""Wait for line to be lost."""
309
```
310
311
### DistanceSensor
312
313
Ultrasonic distance sensor (HC-SR04 style).
314
315
```python { .api }
316
class DistanceSensor(SmoothedInputDevice):
317
def __init__(self, echo=None, trigger=None, *, queue_len=30, max_distance=1, threshold_distance=0.04, partial=False, pin_factory=None):
318
"""
319
Ultrasonic distance sensor.
320
321
Parameters:
322
- echo: int or str - Echo pin number or name
323
- trigger: int or str - Trigger pin number or name
324
- queue_len: int - Number of distance samples for smoothing
325
- max_distance: float - Maximum measurable distance in meters
326
- threshold_distance: float - Distance threshold for in_range property
327
- partial: bool - If True, return values before queue is full
328
- pin_factory: Factory or None - Pin factory for advanced usage
329
"""
330
331
@property
332
def distance(self) -> float:
333
"""Current distance reading in meters."""
334
335
@property
336
def max_distance(self) -> float:
337
"""Maximum measurable distance in meters."""
338
339
@property
340
def threshold_distance(self) -> float:
341
"""Distance threshold for in_range property."""
342
343
@threshold_distance.setter
344
def threshold_distance(self, value: float): ...
345
346
@property
347
def in_range(self) -> bool:
348
"""Returns True if object is within threshold distance."""
349
350
@property
351
def when_in_range(self) -> callable:
352
"""Callback function called when object enters range."""
353
354
@when_in_range.setter
355
def when_in_range(self, value: callable): ...
356
357
@property
358
def when_out_of_range(self) -> callable:
359
"""Callback function called when object exits range."""
360
361
@when_out_of_range.setter
362
def when_out_of_range(self, value: callable): ...
363
364
def wait_for_in_range(self, timeout: float = None) -> bool:
365
"""Wait for object to enter range."""
366
367
def wait_for_out_of_range(self, timeout: float = None) -> bool:
368
"""Wait for object to exit range."""
369
```
370
371
### RotaryEncoder
372
373
Rotary encoder with A and B phases.
374
375
```python { .api }
376
class RotaryEncoder(CompositeDevice):
377
def __init__(self, a=None, b=None, *, wrap=False, max_steps=0, threshold_steps=(0, 0), pin_factory=None):
378
"""
379
Rotary encoder with quadrature decoding.
380
381
Parameters:
382
- a: int or str - A phase pin number or name
383
- b: int or str - B phase pin number or name
384
- wrap: bool - If True, steps wrap around at max_steps
385
- max_steps: int - Maximum step count (0 for unlimited)
386
- threshold_steps: tuple - (min, max) step thresholds for in_range
387
- pin_factory: Factory or None - Pin factory for advanced usage
388
"""
389
390
@property
391
def steps(self) -> int:
392
"""Current step count."""
393
394
@property
395
def value(self) -> float:
396
"""Normalized value (-1.0 to 1.0 based on steps and max_steps)."""
397
398
@property
399
def max_steps(self) -> int:
400
"""Maximum step count."""
401
402
@property
403
def wrap(self) -> bool:
404
"""If True, steps wrap around at max_steps."""
405
406
@property
407
def threshold_steps(self) -> tuple:
408
"""(min, max) step thresholds for in_range."""
409
410
@threshold_steps.setter
411
def threshold_steps(self, value: tuple): ...
412
413
@property
414
def in_range(self) -> bool:
415
"""Returns True if steps are within threshold range."""
416
417
@property
418
def when_rotated(self) -> callable:
419
"""Callback function called when encoder rotates."""
420
421
@when_rotated.setter
422
def when_rotated(self, value: callable): ...
423
424
@property
425
def when_rotated_clockwise(self) -> callable:
426
"""Callback function called when encoder rotates clockwise."""
427
428
@when_rotated_clockwise.setter
429
def when_rotated_clockwise(self, value: callable): ...
430
431
@property
432
def when_rotated_counter_clockwise(self) -> callable:
433
"""Callback function called when encoder rotates counter-clockwise."""
434
435
@when_rotated_counter_clockwise.setter
436
def when_rotated_counter_clockwise(self, value: callable): ...
437
```
438
439
## Usage Examples
440
441
### Basic Button Control
442
443
```python
444
from gpiozero import Button, LED
445
from signal import pause
446
447
button = Button(2)
448
led = LED(17)
449
450
button.when_pressed = led.on
451
button.when_released = led.off
452
453
pause()
454
```
455
456
### Motion Detection with Multiple Sensors
457
458
```python
459
from gpiozero import MotionSensor, LED
460
from signal import pause
461
462
motion1 = MotionSensor(4)
463
motion2 = MotionSensor(5)
464
alert_led = LED(17)
465
466
def motion_detected():
467
print("Motion detected!")
468
alert_led.on()
469
470
def no_motion():
471
print("No motion")
472
alert_led.off()
473
474
motion1.when_motion = motion_detected
475
motion1.when_no_motion = no_motion
476
motion2.when_motion = motion_detected
477
motion2.when_no_motion = no_motion
478
479
pause()
480
```
481
482
### Distance-Based Alarm
483
484
```python
485
from gpiozero import DistanceSensor, Buzzer
486
from signal import pause
487
488
sensor = DistanceSensor(echo=24, trigger=23, threshold_distance=0.3)
489
buzzer = Buzzer(18)
490
491
sensor.when_in_range = buzzer.on
492
sensor.when_out_of_range = buzzer.off
493
494
pause()
495
```
496
497
### Light-Controlled System
498
499
```python
500
from gpiozero import LightSensor, LED
501
from signal import pause
502
503
light_sensor = LightSensor(7, threshold=0.1)
504
night_light = LED(17)
505
506
# Turn on LED when it gets dark
507
light_sensor.when_dark = night_light.on
508
light_sensor.when_light = night_light.off
509
510
pause()
511
```